vimsupport.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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 tempfile
  22. import json
  23. import re
  24. from ycmd.utils import ToUtf8IfNeeded
  25. from ycmd import user_options_store
  26. BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
  27. 'horizontal-split' : 'split',
  28. 'vertical-split' : 'vsplit',
  29. 'new-tab' : 'tabedit' }
  30. def CurrentLineAndColumn():
  31. """Returns the 0-based current line and 0-based current column."""
  32. # See the comment in CurrentColumn about the calculation for the line and
  33. # column number
  34. line, column = vim.current.window.cursor
  35. line -= 1
  36. return line, column
  37. def CurrentColumn():
  38. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  39. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  40. line. Only the chars before the current column exist in vim.current.line."""
  41. # vim's columns are 1-based while vim.current.line columns are 0-based
  42. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  43. # columns are 0-based, while the line from that same tuple is 1-based.
  44. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  45. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  46. return vim.current.window.cursor[ 1 ]
  47. def CurrentLineContents():
  48. return vim.current.line
  49. def TextAfterCursor():
  50. """Returns the text after CurrentColumn."""
  51. return vim.current.line[ CurrentColumn(): ]
  52. def TextBeforeCursor():
  53. """Returns the text before CurrentColumn."""
  54. return vim.current.line[ :CurrentColumn() ]
  55. # Expects version_string in 'MAJOR.MINOR.PATCH' format, e.g. '7.4.301'
  56. def VimVersionAtLeast( version_string ):
  57. major, minor, patch = [ int( x ) for x in version_string.split( '.' ) ]
  58. # For Vim 7.4.301, v:version is '704'
  59. actual_major_and_minor = GetIntValue( 'v:version' )
  60. matching_major_and_minor = major * 100 + minor
  61. if actual_major_and_minor != matching_major_and_minor:
  62. return actual_major_and_minor > matching_major_and_minor
  63. return GetBoolValue( 'has("patch{0}")'.format( patch ) )
  64. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  65. # the same.
  66. def GetBufferOption( buffer_object, option ):
  67. # NOTE: We used to check for the 'options' property on the buffer_object which
  68. # is available in recent versions of Vim and would then use:
  69. #
  70. # buffer_object.options[ option ]
  71. #
  72. # to read the value, BUT this caused annoying flickering when the
  73. # buffer_object was a hidden buffer (with option = 'ft'). This was all due to
  74. # a Vim bug. Until this is fixed, we won't use it.
  75. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  76. return GetVariableValue( to_eval )
  77. def BufferModified( buffer_object ):
  78. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  79. def GetUnsavedAndCurrentBufferData():
  80. buffers_data = {}
  81. for buffer_object in vim.buffers:
  82. if not ( BufferModified( buffer_object ) or
  83. buffer_object == vim.current.buffer ):
  84. continue
  85. buffers_data[ GetBufferFilepath( buffer_object ) ] = {
  86. # Add a newline to match what gets saved to disk. See #1455 for details.
  87. 'contents': '\n'.join( buffer_object ) + '\n',
  88. 'filetypes': FiletypesForBuffer( buffer_object )
  89. }
  90. return buffers_data
  91. def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
  92. return GetIntValue( u"bufnr('{0}', {1})".format(
  93. EscapeForVim( os.path.realpath( filename ) ),
  94. int( open_file_if_needed ) ) )
  95. def GetCurrentBufferFilepath():
  96. return GetBufferFilepath( vim.current.buffer )
  97. def BufferIsVisible( buffer_number ):
  98. if buffer_number < 0:
  99. return False
  100. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  101. return window_number != -1
  102. def GetBufferFilepath( buffer_object ):
  103. if buffer_object.name:
  104. return buffer_object.name
  105. # Buffers that have just been created by a command like :enew don't have any
  106. # buffer name so we use the buffer number for that. Also, os.getcwd() throws
  107. # an exception when the CWD has been deleted so we handle that.
  108. try:
  109. folder_path = os.getcwd()
  110. except OSError:
  111. folder_path = tempfile.gettempdir()
  112. return os.path.join( folder_path, str( buffer_object.number ) )
  113. def UnplaceSignInBuffer( buffer_number, sign_id ):
  114. if buffer_number < 0:
  115. return
  116. vim.command(
  117. 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format(
  118. sign_id, buffer_number ) )
  119. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  120. # libclang can give us diagnostics that point "outside" the file; Vim borks
  121. # on these.
  122. if line_num < 1:
  123. line_num = 1
  124. sign_name = 'YcmError' if is_error else 'YcmWarning'
  125. vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format(
  126. sign_id, line_num, sign_name, buffer_num ) )
  127. def PlaceDummySign( sign_id, buffer_num, line_num ):
  128. if buffer_num < 0 or line_num < 0:
  129. return
  130. vim.command( 'sign define ycm_dummy_sign' )
  131. vim.command(
  132. 'sign place {0} name=ycm_dummy_sign line={1} buffer={2}'.format(
  133. sign_id,
  134. line_num,
  135. buffer_num,
  136. )
  137. )
  138. def UnPlaceDummySign( sign_id, buffer_num ):
  139. if buffer_num < 0:
  140. return
  141. vim.command( 'sign undefine ycm_dummy_sign' )
  142. vim.command( 'sign unplace {0} buffer={1}'.format( sign_id, buffer_num ) )
  143. def ClearYcmSyntaxMatches():
  144. matches = VimExpressionToPythonType( 'getmatches()' )
  145. for match in matches:
  146. if match[ 'group' ].startswith( 'Ycm' ):
  147. vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
  148. # Returns the ID of the newly added match
  149. # Both line and column numbers are 1-based
  150. def AddDiagnosticSyntaxMatch( line_num,
  151. column_num,
  152. line_end_num = None,
  153. column_end_num = None,
  154. is_error = True ):
  155. group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
  156. if not line_end_num:
  157. line_end_num = line_num
  158. line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
  159. line_end_num, column_end_num = LineAndColumnNumbersClamped( line_end_num,
  160. column_end_num )
  161. if not column_end_num:
  162. return GetIntValue(
  163. "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
  164. else:
  165. return GetIntValue(
  166. "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format(
  167. group, line_num, column_num, line_end_num, column_end_num ) )
  168. # Clamps the line and column numbers so that they are not past the contents of
  169. # the buffer. Numbers are 1-based.
  170. def LineAndColumnNumbersClamped( line_num, column_num ):
  171. new_line_num = line_num
  172. new_column_num = column_num
  173. max_line = len( vim.current.buffer )
  174. if line_num and line_num > max_line:
  175. new_line_num = max_line
  176. max_column = len( vim.current.buffer[ new_line_num - 1 ] )
  177. if column_num and column_num > max_column:
  178. new_column_num = max_column
  179. return new_line_num, new_column_num
  180. def SetLocationList( diagnostics ):
  181. """Diagnostics should be in qflist format; see ":h setqflist" for details."""
  182. vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
  183. def ConvertDiagnosticsToQfList( diagnostics ):
  184. def ConvertDiagnosticToQfFormat( diagnostic ):
  185. # see :h getqflist for a description of the dictionary fields
  186. # Note that, as usual, Vim is completely inconsistent about whether
  187. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  188. # them to be 1-based.
  189. location = diagnostic[ 'location' ]
  190. line_num = location[ 'line_num' ]
  191. # libclang can give us diagnostics that point "outside" the file; Vim borks
  192. # on these.
  193. if line_num < 1:
  194. line_num = 1
  195. text = diagnostic[ 'text' ]
  196. if diagnostic.get( 'fixit_available', False ):
  197. text += ' (FixIt available)'
  198. return {
  199. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  200. 'lnum' : line_num,
  201. 'col' : location[ 'column_num' ],
  202. 'text' : ToUtf8IfNeeded( text ),
  203. 'type' : diagnostic[ 'kind' ][ 0 ],
  204. 'valid' : 1
  205. }
  206. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  207. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  208. # When |overwrite| is True, overwrites the existing value in Vim.
  209. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  210. extend_option = '"force"' if overwrite else '"keep"'
  211. # We need to use json.dumps because that won't use the 'u' prefix on strings
  212. # which Vim would bork on.
  213. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  214. extend_option ) )
  215. # Changing the returned dict will NOT change the value in Vim.
  216. def GetReadOnlyVimGlobals( force_python_objects = False ):
  217. if force_python_objects:
  218. return vim.eval( 'g:' )
  219. try:
  220. # vim.vars is fairly new so it might not exist
  221. return vim.vars
  222. except:
  223. return vim.eval( 'g:' )
  224. def VimExpressionToPythonType( vim_expression ):
  225. result = vim.eval( vim_expression )
  226. if not isinstance( result, basestring ):
  227. return result
  228. try:
  229. return int( result )
  230. except ValueError:
  231. return result
  232. def HiddenEnabled( buffer_object ):
  233. return bool( int( GetBufferOption( buffer_object, 'hid' ) ) )
  234. def BufferIsUsable( buffer_object ):
  235. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  236. def EscapedFilepath( filepath ):
  237. return filepath.replace( ' ' , r'\ ' )
  238. # Both |line| and |column| need to be 1-based
  239. def TryJumpLocationInOpenedTab( filename, line, column ):
  240. filepath = os.path.realpath( filename )
  241. for tab in vim.tabpages:
  242. for win in tab.windows:
  243. if win.buffer.name == filepath:
  244. vim.current.tabpage = tab
  245. vim.current.window = win
  246. vim.current.window.cursor = ( line, column - 1 )
  247. # Center the screen on the jumped-to location
  248. vim.command( 'normal! zz' )
  249. return
  250. else:
  251. # 'filename' is not opened in any tab pages
  252. raise ValueError
  253. # Both |line| and |column| need to be 1-based
  254. def JumpToLocation( filename, line, column ):
  255. # Add an entry to the jumplist
  256. vim.command( "normal! m'" )
  257. if filename != GetCurrentBufferFilepath():
  258. # We prefix the command with 'keepjumps' so that opening the file is not
  259. # recorded in the jumplist. So when we open the file and move the cursor to
  260. # a location in it, the user can use CTRL-O to jump back to the original
  261. # location, not to the start of the newly opened file.
  262. # Sadly this fails on random occasions and the undesired jump remains in the
  263. # jumplist.
  264. user_command = user_options_store.Value( 'goto_buffer_command' )
  265. if user_command == 'new-or-existing-tab':
  266. try:
  267. TryJumpLocationInOpenedTab( filename, line, column )
  268. return
  269. except ValueError:
  270. user_command = 'new-tab'
  271. command = BUFFER_COMMAND_MAP.get( user_command, 'edit' )
  272. if command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  273. command = 'split'
  274. vim.command( 'keepjumps {0} {1}'.format( command,
  275. EscapedFilepath( filename ) ) )
  276. vim.current.window.cursor = ( line, column - 1 )
  277. # Center the screen on the jumped-to location
  278. vim.command( 'normal! zz' )
  279. def NumLinesInBuffer( buffer_object ):
  280. # This is actually less than obvious, that's why it's wrapped in a function
  281. return len( buffer_object )
  282. # Calling this function from the non-GUI thread will sometimes crash Vim. At
  283. # the time of writing, YCM only uses the GUI thread inside Vim (this used to
  284. # not be the case).
  285. # We redraw the screen before displaying the message to avoid the "Press ENTER
  286. # or type command to continue" prompt when editing a new C-family file.
  287. def PostVimMessage( message ):
  288. vim.command( "redraw | echohl WarningMsg | echom '{0}' | echohl None"
  289. .format( EscapeForVim( str( message ) ) ) )
  290. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  291. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  292. # appear in Vim's message log.
  293. def PostMultiLineNotice( message ):
  294. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  295. .format( EscapeForVim( str( message ) ) ) )
  296. def PresentDialog( message, choices, default_choice_index = 0 ):
  297. """Presents the user with a dialog where a choice can be made.
  298. This will be a dialog for gvim users or a question in the message buffer
  299. for vim users or if `set guioptions+=c` was used.
  300. choices is list of alternatives.
  301. default_choice_index is the 0-based index of the default element
  302. that will get choosen if the user hits <CR>. Use -1 for no default.
  303. PresentDialog will return a 0-based index into the list
  304. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  305. See also:
  306. :help confirm() in vim (Note that vim uses 1-based indexes)
  307. Example call:
  308. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  309. Is this a nice example?
  310. [Y]es, (N)o, May(b)e:"""
  311. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  312. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  313. return int( vim.eval( to_eval ) ) - 1
  314. def Confirm( message ):
  315. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  316. def EchoText( text, log_as_message = True ):
  317. def EchoLine( text ):
  318. command = 'echom' if log_as_message else 'echo'
  319. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  320. for line in str( text ).split( '\n' ):
  321. EchoLine( line )
  322. # Echos text but truncates it so that it all fits on one line
  323. def EchoTextVimWidth( text ):
  324. vim_width = GetIntValue( '&columns' )
  325. truncated_text = ToUtf8IfNeeded( text )[ : int( vim_width * 0.9 ) ]
  326. truncated_text.replace( '\n', ' ' )
  327. old_ruler = GetIntValue( '&ruler' )
  328. old_showcmd = GetIntValue( '&showcmd' )
  329. vim.command( 'set noruler noshowcmd' )
  330. EchoText( truncated_text, False )
  331. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  332. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  333. def EscapeForVim( text ):
  334. return text.replace( "'", "''" )
  335. def CurrentFiletypes():
  336. return vim.eval( "&filetype" ).split( '.' )
  337. def FiletypesForBuffer( buffer_object ):
  338. # NOTE: Getting &ft for other buffers only works when the buffer has been
  339. # visited by the user at least once, which is true for modified buffers
  340. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  341. def VariableExists( variable ):
  342. return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
  343. def SetVariableValue( variable, value ):
  344. vim.command( "let {0} = '{1}'".format( variable, EscapeForVim( value ) ) )
  345. def GetVariableValue( variable ):
  346. return vim.eval( variable )
  347. def GetBoolValue( variable ):
  348. return bool( int( vim.eval( variable ) ) )
  349. def GetIntValue( variable ):
  350. return int( vim.eval( variable ) )
  351. # Replace the chunk of text specified by a contiguous range with the supplied
  352. # text.
  353. # * start and end are objects with line_num and column_num properties
  354. # * the range is inclusive
  355. # * indices are all 1-based
  356. # * the returned character delta is the delta for the last line
  357. #
  358. # returns the delta (in lines and characters) that any position after the end
  359. # needs to be adjusted by.
  360. def ReplaceChunk( start, end, replacement_text, line_delta, char_delta,
  361. vim_buffer = None ):
  362. if vim_buffer is None:
  363. vim_buffer = vim.current.buffer
  364. # ycmd's results are all 1-based, but vim's/python's are all 0-based
  365. # (so we do -1 on all of the values)
  366. start_line = start[ 'line_num' ] - 1 + line_delta
  367. end_line = end[ 'line_num' ] - 1 + line_delta
  368. source_lines_count = end_line - start_line + 1
  369. start_column = start[ 'column_num' ] - 1 + char_delta
  370. end_column = end[ 'column_num' ] - 1
  371. if source_lines_count == 1:
  372. end_column += char_delta
  373. replacement_lines = replacement_text.splitlines( False )
  374. if not replacement_lines:
  375. replacement_lines = [ '' ]
  376. replacement_lines_count = len( replacement_lines )
  377. end_existing_text = vim_buffer[ end_line ][ end_column : ]
  378. start_existing_text = vim_buffer[ start_line ][ : start_column ]
  379. new_char_delta = ( len( replacement_lines[ -1 ] )
  380. - ( end_column - start_column ) )
  381. if replacement_lines_count > 1:
  382. new_char_delta -= start_column
  383. replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  384. replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
  385. vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
  386. new_line_delta = replacement_lines_count - source_lines_count
  387. return ( new_line_delta, new_char_delta )
  388. def InsertNamespace( namespace ):
  389. if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
  390. expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
  391. if expr:
  392. SetVariableValue( "g:ycm_namespace_to_insert", namespace )
  393. vim.eval( expr )
  394. return
  395. pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  396. line = SearchInCurrentBuffer( pattern )
  397. existing_line = LineTextInCurrentBuffer( line )
  398. existing_indent = re.sub( r"\S.*", "", existing_line )
  399. new_line = "{0}using {1};\n\n".format( existing_indent, namespace )
  400. replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  401. ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0 )
  402. PostVimMessage( "Add namespace: {0}".format( namespace ) )
  403. def SearchInCurrentBuffer( pattern ):
  404. return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
  405. def LineTextInCurrentBuffer( line ):
  406. return vim.current.buffer[ line ]