vimsupport.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2011, 2012 Google Inc.
  4. #
  5. # This file is part of YouCompleteMe.
  6. #
  7. # YouCompleteMe is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # YouCompleteMe is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  19. import vim
  20. import os
  21. import json
  22. from ycmd.utils import ToUtf8IfNeeded
  23. from ycmd import user_options_store
  24. BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
  25. 'horizontal-split' : 'split',
  26. 'vertical-split' : 'vsplit',
  27. 'new-tab' : 'tabedit' }
  28. def CurrentLineAndColumn():
  29. """Returns the 0-based current line and 0-based current column."""
  30. # See the comment in CurrentColumn about the calculation for the line and
  31. # column number
  32. line, column = vim.current.window.cursor
  33. line -= 1
  34. return line, column
  35. def CurrentColumn():
  36. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  37. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  38. line. Only the chars before the current column exist in vim.current.line."""
  39. # vim's columns are 1-based while vim.current.line columns are 0-based
  40. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  41. # columns are 0-based, while the line from that same tuple is 1-based.
  42. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  43. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  44. return vim.current.window.cursor[ 1 ]
  45. def TextAfterCursor():
  46. """Returns the text after CurrentColumn."""
  47. return vim.current.line[ CurrentColumn(): ]
  48. # Expects version_string in 'MAJOR.MINOR.PATCH' format, e.g. '7.4.301'
  49. def VimVersionAtLeast( version_string ):
  50. major, minor, patch = [ int( x ) for x in version_string.split( '.' ) ]
  51. # For Vim 7.4.301, v:version is '704'
  52. actual_major_and_minor = GetIntValue( 'v:version' )
  53. if actual_major_and_minor != major * 100 + minor:
  54. return False
  55. return GetBoolValue( 'has("patch{0}")'.format( patch ) )
  56. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  57. # the same.
  58. def GetBufferOption( buffer_object, option ):
  59. # NOTE: We used to check for the 'options' property on the buffer_object which
  60. # is available in recent versions of Vim and would then use:
  61. #
  62. # buffer_object.options[ option ]
  63. #
  64. # to read the value, BUT this caused annoying flickering when the
  65. # buffer_object was a hidden buffer (with option = 'ft'). This was all due to
  66. # a Vim bug. Until this is fixed, we won't use it.
  67. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  68. return GetVariableValue( to_eval )
  69. def BufferModified( buffer_object ):
  70. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  71. def GetUnsavedAndCurrentBufferData():
  72. buffers_data = {}
  73. for buffer_object in vim.buffers:
  74. if not ( BufferModified( buffer_object ) or
  75. buffer_object == vim.current.buffer ):
  76. continue
  77. buffers_data[ GetBufferFilepath( buffer_object ) ] = {
  78. 'contents': '\n'.join( buffer_object ),
  79. 'filetypes': FiletypesForBuffer( buffer_object )
  80. }
  81. return buffers_data
  82. def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
  83. return GetIntValue( "bufnr('{0}', {1})".format(
  84. os.path.realpath( filename ),
  85. int( open_file_if_needed ) ) )
  86. def GetCurrentBufferFilepath():
  87. return GetBufferFilepath( vim.current.buffer )
  88. def BufferIsVisible( buffer_number ):
  89. if buffer_number < 0:
  90. return False
  91. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  92. return window_number != -1
  93. def GetBufferFilepath( buffer_object ):
  94. if buffer_object.name:
  95. return buffer_object.name
  96. # Buffers that have just been created by a command like :enew don't have any
  97. # buffer name so we use the buffer number for that.
  98. return os.path.join( os.getcwd(), str( buffer_object.number ) )
  99. # NOTE: This unplaces *all* signs in a buffer, not just the ones we placed. We
  100. # used to track which signs we ended up placing and would then only unplace
  101. # ours, but that causes flickering Vim since we have to call
  102. # sign unplace <id> buffer=<buffer-num>
  103. # in a loop. So we're forced to unplace all signs, which might conflict with
  104. # other Vim plugins.
  105. def UnplaceAllSignsInBuffer( buffer_number ):
  106. if buffer_number < 0:
  107. return
  108. vim.command( 'sign unplace * buffer={0}'.format( buffer_number ) )
  109. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  110. sign_name = 'YcmError' if is_error else 'YcmWarning'
  111. vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format(
  112. sign_id, line_num, sign_name, buffer_num ) )
  113. def ClearYcmSyntaxMatches():
  114. matches = VimExpressionToPythonType( 'getmatches()' )
  115. for match in matches:
  116. if match[ 'group' ].startswith( 'Ycm' ):
  117. vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
  118. # Returns the ID of the newly added match
  119. # Both line and column numbers are 1-based
  120. def AddDiagnosticSyntaxMatch( line_num,
  121. column_num,
  122. line_end_num = None,
  123. column_end_num = None,
  124. is_error = True ):
  125. group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
  126. if not line_end_num:
  127. line_end_num = line_num
  128. line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
  129. line_end_num, column_end_num = LineAndColumnNumbersClamped( line_end_num,
  130. column_end_num )
  131. if not column_end_num:
  132. return GetIntValue(
  133. "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
  134. else:
  135. return GetIntValue(
  136. "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format(
  137. group, line_num, column_num, line_end_num, column_end_num ) )
  138. # Clamps the line and column numbers so that they are not past the contents of
  139. # the buffer. Numbers are 1-based.
  140. def LineAndColumnNumbersClamped( line_num, column_num ):
  141. new_line_num = line_num
  142. new_column_num = column_num
  143. max_line = len( vim.current.buffer )
  144. if line_num and line_num > max_line:
  145. new_line_num = max_line
  146. max_column = len( vim.current.buffer[ new_line_num - 1 ] )
  147. if column_num and column_num > max_column:
  148. new_column_num = max_column
  149. return new_line_num, new_column_num
  150. def SetLocationList( diagnostics ):
  151. """Diagnostics should be in qflist format; see ":h setqflist" for details."""
  152. vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
  153. def ConvertDiagnosticsToQfList( diagnostics ):
  154. def ConvertDiagnosticToQfFormat( diagnostic ):
  155. # see :h getqflist for a description of the dictionary fields
  156. # Note that, as usual, Vim is completely inconsistent about whether
  157. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  158. # them to be 1-based.
  159. location = diagnostic[ 'location' ]
  160. return {
  161. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  162. 'lnum' : location[ 'line_num' ] + 1,
  163. 'col' : location[ 'column_num' ] + 1,
  164. 'text' : ToUtf8IfNeeded( diagnostic[ 'text' ] ),
  165. 'type' : diagnostic[ 'kind' ],
  166. 'valid' : 1
  167. }
  168. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  169. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  170. # When |overwrite| is True, overwrites the existing value in Vim.
  171. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  172. extend_option = '"force"' if overwrite else '"keep"'
  173. # We need to use json.dumps because that won't use the 'u' prefix on strings
  174. # which Vim would bork on.
  175. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  176. extend_option ) )
  177. # Changing the returned dict will NOT change the value in Vim.
  178. def GetReadOnlyVimGlobals( force_python_objects = False ):
  179. if force_python_objects:
  180. return vim.eval( 'g:' )
  181. try:
  182. # vim.vars is fairly new so it might not exist
  183. return vim.vars
  184. except:
  185. return vim.eval( 'g:' )
  186. def VimExpressionToPythonType( vim_expression ):
  187. result = vim.eval( vim_expression )
  188. if not isinstance( result, basestring ):
  189. return result
  190. try:
  191. return int( result )
  192. except ValueError:
  193. return result
  194. def HiddenEnabled( buffer_object ):
  195. return bool( int( GetBufferOption( buffer_object, 'hid' ) ) )
  196. def BufferIsUsable( buffer_object ):
  197. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  198. def EscapedFilepath( filepath ):
  199. return filepath.replace( ' ' , r'\ ' )
  200. # Both |line| and |column| need to be 1-based
  201. def JumpToLocation( filename, line, column ):
  202. # Add an entry to the jumplist
  203. vim.command( "normal! m'" )
  204. if filename != GetCurrentBufferFilepath():
  205. # We prefix the command with 'keepjumps' so that opening the file is not
  206. # recorded in the jumplist. So when we open the file and move the cursor to
  207. # a location in it, the user can use CTRL-O to jump back to the original
  208. # location, not to the start of the newly opened file.
  209. # Sadly this fails on random occasions and the undesired jump remains in the
  210. # jumplist.
  211. user_command = user_options_store.Value( 'goto_buffer_command' )
  212. command = BUFFER_COMMAND_MAP.get( user_command, 'edit' )
  213. if command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  214. command = 'split'
  215. vim.command( 'keepjumps {0} {1}'.format( command,
  216. EscapedFilepath( filename ) ) )
  217. vim.current.window.cursor = ( line, column - 1 )
  218. # Center the screen on the jumped-to location
  219. vim.command( 'normal! zz' )
  220. def NumLinesInBuffer( buffer_object ):
  221. # This is actually less than obvious, that's why it's wrapped in a function
  222. return len( buffer_object )
  223. # Calling this function from the non-GUI thread will sometimes crash Vim. At the
  224. # time of writing, YCM only uses the GUI thread inside Vim (this used to not be
  225. # the case).
  226. def PostVimMessage( message ):
  227. vim.command( "echohl WarningMsg | echom '{0}' | echohl None"
  228. .format( EscapeForVim( str( message ) ) ) )
  229. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  230. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  231. # appear in Vim's message log.
  232. def PostMultiLineNotice( message ):
  233. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  234. .format( EscapeForVim( str( message ) ) ) )
  235. def PresentDialog( message, choices, default_choice_index = 0 ):
  236. """Presents the user with a dialog where a choice can be made.
  237. This will be a dialog for gvim users or a question in the message buffer
  238. for vim users or if `set guioptions+=c` was used.
  239. choices is list of alternatives.
  240. default_choice_index is the 0-based index of the default element
  241. that will get choosen if the user hits <CR>. Use -1 for no default.
  242. PresentDialog will return a 0-based index into the list
  243. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  244. See also:
  245. :help confirm() in vim (Note that vim uses 1-based indexes)
  246. Example call:
  247. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  248. Is this a nice example?
  249. [Y]es, (N)o, May(b)e:"""
  250. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  251. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  252. return int( vim.eval( to_eval ) ) - 1
  253. def Confirm( message ):
  254. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  255. def EchoText( text, log_as_message = True ):
  256. def EchoLine( text ):
  257. command = 'echom' if log_as_message else 'echo'
  258. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  259. for line in str( text ).split( '\n' ):
  260. EchoLine( line )
  261. # Echos text but truncates it so that it all fits on one line
  262. def EchoTextVimWidth( text ):
  263. vim_width = GetIntValue( '&columns' )
  264. truncated_text = ToUtf8IfNeeded( text )[ : int( vim_width * 0.9 ) ]
  265. truncated_text.replace( '\n', ' ' )
  266. old_ruler = GetIntValue( '&ruler' )
  267. old_showcmd = GetIntValue( '&showcmd' )
  268. vim.command( 'set noruler noshowcmd' )
  269. EchoText( truncated_text, False )
  270. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  271. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  272. def EscapeForVim( text ):
  273. return text.replace( "'", "''" )
  274. def CurrentFiletypes():
  275. return vim.eval( "&filetype" ).split( '.' )
  276. def FiletypesForBuffer( buffer_object ):
  277. # NOTE: Getting &ft for other buffers only works when the buffer has been
  278. # visited by the user at least once, which is true for modified buffers
  279. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  280. def GetVariableValue( variable ):
  281. return vim.eval( variable )
  282. def GetBoolValue( variable ):
  283. return bool( int( vim.eval( variable ) ) )
  284. def GetIntValue( variable ):
  285. return int( vim.eval( variable ) )