vimsupport.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. # Copyright (C) 2011-2012 Google Inc.
  2. # 2016 YouCompleteMe contributors
  3. #
  4. # This file is part of YouCompleteMe.
  5. #
  6. # YouCompleteMe is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # YouCompleteMe is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  18. from __future__ import unicode_literals
  19. from __future__ import print_function
  20. from __future__ import division
  21. from __future__ import absolute_import
  22. # Not installing aliases from python-future; it's unreliable and slow.
  23. from builtins import * # noqa
  24. from future.utils import iterkeys
  25. import vim
  26. import os
  27. import json
  28. import re
  29. from collections import defaultdict
  30. from ycmd.utils import ( ByteOffsetToCodepointOffset, GetCurrentDirectory,
  31. JoinLinesAsUnicode, ToBytes, ToUnicode )
  32. from ycmd import user_options_store
  33. BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
  34. 'horizontal-split' : 'split',
  35. 'vertical-split' : 'vsplit',
  36. 'new-tab' : 'tabedit' }
  37. FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = (
  38. 'The requested operation will apply changes to {0} files which are not '
  39. 'currently open. This will therefore open {0} new files in the hidden '
  40. 'buffers. The quickfix list can then be used to review the changes. No '
  41. 'files will be written to disk. Do you wish to continue?' )
  42. NO_SELECTION_MADE_MSG = "No valid selection was made; aborting."
  43. def CurrentLineAndColumn():
  44. """Returns the 0-based current line and 0-based current column."""
  45. # See the comment in CurrentColumn about the calculation for the line and
  46. # column number
  47. line, column = vim.current.window.cursor
  48. line -= 1
  49. return line, column
  50. def SetCurrentLineAndColumn( line, column ):
  51. """Sets the cursor position to the 0-based line and 0-based column."""
  52. # Line from vim.current.window.cursor is 1-based.
  53. vim.current.window.cursor = ( line + 1, column )
  54. def CurrentColumn():
  55. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  56. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  57. line. Only the chars before the current column exist in vim.current.line."""
  58. # vim's columns are 1-based while vim.current.line columns are 0-based
  59. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  60. # columns are 0-based, while the line from that same tuple is 1-based.
  61. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  62. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  63. return vim.current.window.cursor[ 1 ]
  64. def CurrentLineContents():
  65. return ToUnicode( vim.current.line )
  66. def CurrentLineContentsAndCodepointColumn():
  67. """Returns the line contents as a unicode string and the 0-based current
  68. column as a codepoint offset. If the current column is outside the line,
  69. returns the column position at the end of the line."""
  70. line = CurrentLineContents()
  71. byte_column = CurrentColumn()
  72. # ByteOffsetToCodepointOffset expects 1-based offset.
  73. column = ByteOffsetToCodepointOffset( line, byte_column + 1 ) - 1
  74. return line, column
  75. def TextAfterCursor():
  76. """Returns the text after CurrentColumn."""
  77. return ToUnicode( vim.current.line[ CurrentColumn(): ] )
  78. def TextBeforeCursor():
  79. """Returns the text before CurrentColumn."""
  80. return ToUnicode( vim.current.line[ :CurrentColumn() ] )
  81. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  82. # the same.
  83. def GetBufferOption( buffer_object, option ):
  84. # NOTE: We used to check for the 'options' property on the buffer_object which
  85. # is available in recent versions of Vim and would then use:
  86. #
  87. # buffer_object.options[ option ]
  88. #
  89. # to read the value, BUT this caused annoying flickering when the
  90. # buffer_object was a hidden buffer (with option = 'ft'). This was all due to
  91. # a Vim bug. Until this is fixed, we won't use it.
  92. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  93. return GetVariableValue( to_eval )
  94. def BufferModified( buffer_object ):
  95. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  96. def GetUnsavedAndSpecifiedBufferData( including_filepath ):
  97. """Build part of the request containing the contents and filetypes of all
  98. dirty buffers as well as the buffer with filepath |including_filepath|."""
  99. buffers_data = {}
  100. for buffer_object in vim.buffers:
  101. buffer_filepath = GetBufferFilepath( buffer_object )
  102. if not ( BufferModified( buffer_object ) or
  103. buffer_filepath == including_filepath ):
  104. continue
  105. buffers_data[ buffer_filepath ] = {
  106. # Add a newline to match what gets saved to disk. See #1455 for details.
  107. 'contents': JoinLinesAsUnicode( buffer_object ) + '\n',
  108. 'filetypes': FiletypesForBuffer( buffer_object )
  109. }
  110. return buffers_data
  111. def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
  112. return GetIntValue( u"bufnr('{0}', {1})".format(
  113. EscapeForVim( os.path.realpath( filename ) ),
  114. int( open_file_if_needed ) ) )
  115. def GetCurrentBufferFilepath():
  116. return GetBufferFilepath( vim.current.buffer )
  117. def BufferIsVisible( buffer_number ):
  118. if buffer_number < 0:
  119. return False
  120. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  121. return window_number != -1
  122. def GetBufferFilepath( buffer_object ):
  123. if buffer_object.name:
  124. return ToUnicode( buffer_object.name )
  125. # Buffers that have just been created by a command like :enew don't have any
  126. # buffer name so we use the buffer number for that.
  127. return os.path.join( GetCurrentDirectory(), str( buffer_object.number ) )
  128. def GetCurrentBufferNumber():
  129. return vim.current.buffer.number
  130. def GetBufferChangedTick( bufnr ):
  131. return GetIntValue( 'getbufvar({0}, "changedtick")'.format( bufnr ) )
  132. def UnplaceSignInBuffer( buffer_number, sign_id ):
  133. if buffer_number < 0:
  134. return
  135. vim.command(
  136. 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format(
  137. sign_id, buffer_number ) )
  138. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  139. # libclang can give us diagnostics that point "outside" the file; Vim borks
  140. # on these.
  141. if line_num < 1:
  142. line_num = 1
  143. sign_name = 'YcmError' if is_error else 'YcmWarning'
  144. vim.command( 'sign place {0} name={1} line={2} buffer={3}'.format(
  145. sign_id, sign_name, line_num, buffer_num ) )
  146. def ClearYcmSyntaxMatches():
  147. matches = VimExpressionToPythonType( 'getmatches()' )
  148. for match in matches:
  149. if match[ 'group' ].startswith( 'Ycm' ):
  150. vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
  151. def AddDiagnosticSyntaxMatch( line_num,
  152. column_num,
  153. line_end_num = None,
  154. column_end_num = None,
  155. is_error = True ):
  156. """Highlight a range in the current window starting from
  157. (|line_num|, |column_num|) included to (|line_end_num|, |column_end_num|)
  158. excluded. If |line_end_num| or |column_end_num| are not given, highlight the
  159. character at (|line_num|, |column_num|). Both line and column numbers are
  160. 1-based. Return the ID of the newly added match."""
  161. group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
  162. line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
  163. if not line_end_num or not column_end_num:
  164. return GetIntValue(
  165. "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
  166. # -1 and then +1 to account for column end not included in the range.
  167. line_end_num, column_end_num = LineAndColumnNumbersClamped(
  168. line_end_num, column_end_num - 1 )
  169. column_end_num += 1
  170. return GetIntValue(
  171. "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format(
  172. group, line_num, column_num, line_end_num, column_end_num ) )
  173. # Clamps the line and column numbers so that they are not past the contents of
  174. # the buffer. Numbers are 1-based byte offsets.
  175. def LineAndColumnNumbersClamped( line_num, column_num ):
  176. new_line_num = line_num
  177. new_column_num = column_num
  178. max_line = len( vim.current.buffer )
  179. if line_num and line_num > max_line:
  180. new_line_num = max_line
  181. max_column = len( vim.current.buffer[ new_line_num - 1 ] )
  182. if column_num and column_num > max_column:
  183. new_column_num = max_column
  184. return new_line_num, new_column_num
  185. def SetLocationList( diagnostics ):
  186. """Populate the location list with diagnostics. Diagnostics should be in
  187. qflist format; see ":h setqflist" for details."""
  188. vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
  189. def OpenLocationList( focus = False, autoclose = False ):
  190. """Open the location list to full width at the bottom of the screen with its
  191. height automatically set to fit all entries. This behavior can be overridden
  192. by using the YcmLocationOpened autocommand. When focus is set to True, the
  193. location list window becomes the active window. When autoclose is set to True,
  194. the location list window is automatically closed after an entry is
  195. selected."""
  196. vim.command( 'botright lopen' )
  197. SetFittingHeightForCurrentWindow()
  198. if autoclose:
  199. # This autocommand is automatically removed when the location list window is
  200. # closed.
  201. vim.command( 'au WinLeave <buffer> q' )
  202. if VariableExists( '#User#YcmLocationOpened' ):
  203. vim.command( 'doautocmd User YcmLocationOpened' )
  204. if not focus:
  205. JumpToPreviousWindow()
  206. def SetQuickFixList( quickfix_list ):
  207. """Populate the quickfix list and open it. List should be in qflist format:
  208. see ":h setqflist" for details."""
  209. vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) )
  210. def OpenQuickFixList( focus = False, autoclose = False ):
  211. """Open the quickfix list to full width at the bottom of the screen with its
  212. height automatically set to fit all entries. This behavior can be overridden
  213. by using the YcmQuickFixOpened autocommand.
  214. See the OpenLocationList function for the focus and autoclose options."""
  215. vim.command( 'botright copen' )
  216. SetFittingHeightForCurrentWindow()
  217. if autoclose:
  218. # This autocommand is automatically removed when the quickfix window is
  219. # closed.
  220. vim.command( 'au WinLeave <buffer> q' )
  221. if VariableExists( '#User#YcmQuickFixOpened' ):
  222. vim.command( 'doautocmd User YcmQuickFixOpened' )
  223. if not focus:
  224. JumpToPreviousWindow()
  225. def SetFittingHeightForCurrentWindow():
  226. window_width = GetIntValue( 'winwidth( 0 )' )
  227. fitting_height = 0
  228. for line in vim.current.buffer:
  229. fitting_height += len( line ) // window_width + 1
  230. vim.command( '{0}wincmd _'.format( fitting_height ) )
  231. def ConvertDiagnosticsToQfList( diagnostics ):
  232. def ConvertDiagnosticToQfFormat( diagnostic ):
  233. # See :h getqflist for a description of the dictionary fields.
  234. # Note that, as usual, Vim is completely inconsistent about whether
  235. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  236. # them to be 1-based. The documentation states quite clearly that it
  237. # expects a byte offset, by which it means "1-based column number" as
  238. # described in :h getqflist ("the first column is 1").
  239. location = diagnostic[ 'location' ]
  240. line_num = location[ 'line_num' ]
  241. # libclang can give us diagnostics that point "outside" the file; Vim borks
  242. # on these.
  243. if line_num < 1:
  244. line_num = 1
  245. text = diagnostic[ 'text' ]
  246. if diagnostic.get( 'fixit_available', False ):
  247. text += ' (FixIt available)'
  248. return {
  249. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  250. 'lnum' : line_num,
  251. 'col' : location[ 'column_num' ],
  252. 'text' : text,
  253. 'type' : diagnostic[ 'kind' ][ 0 ],
  254. 'valid' : 1
  255. }
  256. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  257. def GetVimGlobalsKeys():
  258. return vim.eval( 'keys( g: )' )
  259. def VimExpressionToPythonType( vim_expression ):
  260. """Returns a Python type from the return value of the supplied Vim expression.
  261. If the expression returns a list, dict or other non-string type, then it is
  262. returned unmodified. If the string return can be converted to an
  263. integer, returns an integer, otherwise returns the result converted to a
  264. Unicode string."""
  265. result = vim.eval( vim_expression )
  266. if not ( isinstance( result, str ) or isinstance( result, bytes ) ):
  267. return result
  268. try:
  269. return int( result )
  270. except ValueError:
  271. return ToUnicode( result )
  272. def HiddenEnabled( buffer_object ):
  273. if GetBufferOption( buffer_object, 'bh' ) == "hide":
  274. return True
  275. return GetBoolValue( '&hidden' )
  276. def BufferIsUsable( buffer_object ):
  277. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  278. def EscapedFilepath( filepath ):
  279. return filepath.replace( ' ' , r'\ ' )
  280. # Both |line| and |column| need to be 1-based
  281. def TryJumpLocationInOpenedTab( filename, line, column ):
  282. filepath = os.path.realpath( filename )
  283. for tab in vim.tabpages:
  284. for win in tab.windows:
  285. if GetBufferFilepath( win.buffer ) == filepath:
  286. vim.current.tabpage = tab
  287. vim.current.window = win
  288. vim.current.window.cursor = ( line, column - 1 )
  289. # Center the screen on the jumped-to location
  290. vim.command( 'normal! zz' )
  291. return True
  292. # 'filename' is not opened in any tab pages
  293. return False
  294. # Maps User command to vim command
  295. def GetVimCommand( user_command, default = 'edit' ):
  296. vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
  297. if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  298. vim_command = 'split'
  299. return vim_command
  300. # Both |line| and |column| need to be 1-based
  301. def JumpToLocation( filename, line, column ):
  302. # Add an entry to the jumplist
  303. vim.command( "normal! m'" )
  304. if filename != GetCurrentBufferFilepath():
  305. # We prefix the command with 'keepjumps' so that opening the file is not
  306. # recorded in the jumplist. So when we open the file and move the cursor to
  307. # a location in it, the user can use CTRL-O to jump back to the original
  308. # location, not to the start of the newly opened file.
  309. # Sadly this fails on random occasions and the undesired jump remains in the
  310. # jumplist.
  311. user_command = user_options_store.Value( 'goto_buffer_command' )
  312. if user_command == 'new-or-existing-tab':
  313. if TryJumpLocationInOpenedTab( filename, line, column ):
  314. return
  315. user_command = 'new-tab'
  316. vim_command = GetVimCommand( user_command )
  317. try:
  318. vim.command( 'keepjumps {0} {1}'.format( vim_command,
  319. EscapedFilepath( filename ) ) )
  320. # When the file we are trying to jump to has a swap file
  321. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  322. # or KeyboardInterrupt after user selects one of the options.
  323. except vim.error as e:
  324. if 'E325' not in str( e ):
  325. raise
  326. # Do nothing if the target file is still not opened (user chose (Q)uit)
  327. if filename != GetCurrentBufferFilepath():
  328. return
  329. # Thrown when user chooses (A)bort in .swp message box
  330. except KeyboardInterrupt:
  331. return
  332. vim.current.window.cursor = ( line, column - 1 )
  333. # Center the screen on the jumped-to location
  334. vim.command( 'normal! zz' )
  335. def NumLinesInBuffer( buffer_object ):
  336. # This is actually less than obvious, that's why it's wrapped in a function
  337. return len( buffer_object )
  338. # Calling this function from the non-GUI thread will sometimes crash Vim. At
  339. # the time of writing, YCM only uses the GUI thread inside Vim (this used to
  340. # not be the case).
  341. def PostVimMessage( message, warning = True, truncate = False ):
  342. """Display a message on the Vim status line. By default, the message is
  343. highlighted and logged to Vim command-line history (see :h history).
  344. Unset the |warning| parameter to disable this behavior. Set the |truncate|
  345. parameter to avoid hit-enter prompts (see :h hit-enter) when the message is
  346. longer than the window width."""
  347. echo_command = 'echom' if warning else 'echo'
  348. # Displaying a new message while previous ones are still on the status line
  349. # might lead to a hit-enter prompt or the message appearing without a
  350. # newline so we do a redraw first.
  351. vim.command( 'redraw' )
  352. if warning:
  353. vim.command( 'echohl WarningMsg' )
  354. message = ToUnicode( message )
  355. if truncate:
  356. vim_width = GetIntValue( '&columns' )
  357. message = message.replace( '\n', ' ' )
  358. if len( message ) > vim_width:
  359. message = message[ : vim_width - 4 ] + '...'
  360. old_ruler = GetIntValue( '&ruler' )
  361. old_showcmd = GetIntValue( '&showcmd' )
  362. vim.command( 'set noruler noshowcmd' )
  363. vim.command( "{0} '{1}'".format( echo_command,
  364. EscapeForVim( message ) ) )
  365. SetVariableValue( '&ruler', old_ruler )
  366. SetVariableValue( '&showcmd', old_showcmd )
  367. else:
  368. for line in message.split( '\n' ):
  369. vim.command( "{0} '{1}'".format( echo_command,
  370. EscapeForVim( line ) ) )
  371. if warning:
  372. vim.command( 'echohl None' )
  373. def PresentDialog( message, choices, default_choice_index = 0 ):
  374. """Presents the user with a dialog where a choice can be made.
  375. This will be a dialog for gvim users or a question in the message buffer
  376. for vim users or if `set guioptions+=c` was used.
  377. choices is list of alternatives.
  378. default_choice_index is the 0-based index of the default element
  379. that will get choosen if the user hits <CR>. Use -1 for no default.
  380. PresentDialog will return a 0-based index into the list
  381. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  382. If you are presenting a list of options for the user to choose from, such as
  383. a list of imports, or lines to insert (etc.), SelectFromList is a better
  384. option.
  385. See also:
  386. :help confirm() in vim (Note that vim uses 1-based indexes)
  387. Example call:
  388. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  389. Is this a nice example?
  390. [Y]es, (N)o, May(b)e:"""
  391. to_eval = "confirm('{0}', '{1}', {2})".format(
  392. EscapeForVim( ToUnicode( message ) ),
  393. EscapeForVim( ToUnicode( "\n" .join( choices ) ) ),
  394. default_choice_index + 1 )
  395. try:
  396. return GetIntValue( to_eval ) - 1
  397. except KeyboardInterrupt:
  398. return -1
  399. def Confirm( message ):
  400. """Display |message| with Ok/Cancel operations. Returns True if the user
  401. selects Ok"""
  402. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  403. def SelectFromList( prompt, items ):
  404. """Ask the user to select an item from the list |items|.
  405. Presents the user with |prompt| followed by a numbered list of |items|,
  406. from which they select one. The user is asked to enter the number of an
  407. item or click it.
  408. |items| should not contain leading ordinals: they are added automatically.
  409. Returns the 0-based index in the list |items| that the user selected, or a
  410. negative number if no valid item was selected.
  411. See also :help inputlist()."""
  412. vim_items = [ prompt ]
  413. vim_items.extend( [ "{0}: {1}".format( i + 1, item )
  414. for i, item in enumerate( items ) ] )
  415. # The vim documentation warns not to present lists larger than the number of
  416. # lines of display. This is sound advice, but there really isn't any sensible
  417. # thing we can do in that scenario. Testing shows that Vim just pages the
  418. # message; that behaviour is as good as any, so we don't manipulate the list,
  419. # or attempt to page it.
  420. # For an explanation of the purpose of inputsave() / inputrestore(),
  421. # see :help input(). Briefly, it makes inputlist() work as part of a mapping.
  422. vim.eval( 'inputsave()' )
  423. try:
  424. # Vim returns the number the user entered, or the line number the user
  425. # clicked. This may be wildly out of range for our list. It might even be
  426. # negative.
  427. #
  428. # The first item is index 0, and this maps to our "prompt", so we subtract 1
  429. # from the result and return that, assuming it is within the range of the
  430. # supplied list. If not, we return negative.
  431. #
  432. # See :help input() for explanation of the use of inputsave() and inpput
  433. # restore(). It is done in try/finally in case vim.eval ever throws an
  434. # exception (such as KeyboardInterrupt)
  435. selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1
  436. except KeyboardInterrupt:
  437. selected = -1
  438. finally:
  439. vim.eval( 'inputrestore()' )
  440. if selected < 0 or selected >= len( items ):
  441. # User selected something outside of the range
  442. raise RuntimeError( NO_SELECTION_MADE_MSG )
  443. return selected
  444. def EscapeForVim( text ):
  445. return ToUnicode( text.replace( "'", "''" ) )
  446. def CurrentFiletypes():
  447. return VimExpressionToPythonType( "&filetype" ).split( '.' )
  448. def GetBufferFiletypes( bufnr ):
  449. command = 'getbufvar({0}, "&ft")'.format( bufnr )
  450. return VimExpressionToPythonType( command ).split( '.' )
  451. def FiletypesForBuffer( buffer_object ):
  452. # NOTE: Getting &ft for other buffers only works when the buffer has been
  453. # visited by the user at least once, which is true for modified buffers
  454. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  455. def VariableExists( variable ):
  456. return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
  457. def SetVariableValue( variable, value ):
  458. vim.command( "let {0} = {1}".format( variable, json.dumps( value ) ) )
  459. def GetVariableValue( variable ):
  460. return vim.eval( variable )
  461. def GetBoolValue( variable ):
  462. return bool( int( vim.eval( variable ) ) )
  463. def GetIntValue( variable ):
  464. return int( vim.eval( variable ) )
  465. def _SortChunksByFile( chunks ):
  466. """Sort the members of the list |chunks| (which must be a list of dictionaries
  467. conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new
  468. list in arbitrary order."""
  469. chunks_by_file = defaultdict( list )
  470. for chunk in chunks:
  471. filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ]
  472. chunks_by_file[ filepath ].append( chunk )
  473. return chunks_by_file
  474. def _GetNumNonVisibleFiles( file_list ):
  475. """Returns the number of file in the iterable list of files |file_list| which
  476. are not curerntly open in visible windows"""
  477. return len(
  478. [ f for f in file_list
  479. if not BufferIsVisible( GetBufferNumberForFilename( f, False ) ) ] )
  480. def _OpenFileInSplitIfNeeded( filepath ):
  481. """Ensure that the supplied filepath is open in a visible window, opening a
  482. new split if required. Returns the buffer number of the file and an indication
  483. of whether or not a new split was opened.
  484. If the supplied filename is already open in a visible window, return just
  485. return its buffer number. If the supplied file is not visible in a window
  486. in the current tab, opens it in a new vertical split.
  487. Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer
  488. number and whether or not this method created a new split. If the user opts
  489. not to open a file, or if opening fails, this method raises RuntimeError,
  490. otherwise, guarantees to return a visible buffer number in buffer_num."""
  491. buffer_num = GetBufferNumberForFilename( filepath, False )
  492. # We only apply changes in the current tab page (i.e. "visible" windows).
  493. # Applying changes in tabs does not lead to a better user experience, as the
  494. # quickfix list no longer works as you might expect (doesn't jump into other
  495. # tabs), and the complexity of choosing where to apply edits is significant.
  496. if BufferIsVisible( buffer_num ):
  497. # file is already open and visible, just return that buffer number (and an
  498. # idicator that we *didn't* open a split)
  499. return ( buffer_num, False )
  500. # The file is not open in a visible window, so we open it in a split.
  501. # We open the file with a small, fixed height. This means that we don't
  502. # make the current buffer the smallest after a series of splits.
  503. OpenFilename( filepath, {
  504. 'focus': True,
  505. 'fix': True,
  506. 'size': GetIntValue( '&previewheight' ),
  507. } )
  508. # OpenFilename returns us to the original cursor location. This is what we
  509. # want, because we don't want to disorientate the user, but we do need to
  510. # know the (now open) buffer number for the filename
  511. buffer_num = GetBufferNumberForFilename( filepath, False )
  512. if not BufferIsVisible( buffer_num ):
  513. # This happens, for example, if there is a swap file and the user
  514. # selects the "Quit" or "Abort" options. We just raise an exception to
  515. # make it clear to the user that the abort has left potentially
  516. # partially-applied changes.
  517. raise RuntimeError(
  518. 'Unable to open file: {0}\nFixIt/Refactor operation '
  519. 'aborted prior to completion. Your files have not been '
  520. 'fully updated. Please use undo commands to revert the '
  521. 'applied changes.'.format( filepath ) )
  522. # We opened this file in a split
  523. return ( buffer_num, True )
  524. def ReplaceChunks( chunks ):
  525. """Apply the source file deltas supplied in |chunks| to arbitrary files.
  526. |chunks| is a list of changes defined by ycmd.responses.FixItChunk,
  527. which may apply arbitrary modifications to arbitrary files.
  528. If a file specified in a particular chunk is not currently open in a visible
  529. buffer (i.e., one in a window visible in the current tab), we:
  530. - issue a warning to the user that we're going to open new files (and offer
  531. her the option to abort cleanly)
  532. - open the file in a new split, make the changes, then hide the buffer.
  533. If for some reason a file could not be opened or changed, raises RuntimeError.
  534. Otherwise, returns no meaningful value."""
  535. # We apply the edits file-wise for efficiency, and because we must track the
  536. # file-wise offset deltas (caused by the modifications to the text).
  537. chunks_by_file = _SortChunksByFile( chunks )
  538. # We sort the file list simply to enable repeatable testing
  539. sorted_file_list = sorted( iterkeys( chunks_by_file ) )
  540. # Make sure the user is prepared to have her screen mutilated by the new
  541. # buffers
  542. num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list )
  543. if num_files_to_open > 0:
  544. if not Confirm(
  545. FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ):
  546. return
  547. # Store the list of locations where we applied changes. We use this to display
  548. # the quickfix window showing the user where we applied changes.
  549. locations = []
  550. for filepath in sorted_file_list:
  551. ( buffer_num, close_window ) = _OpenFileInSplitIfNeeded( filepath )
  552. ReplaceChunksInBuffer( chunks_by_file[ filepath ],
  553. vim.buffers[ buffer_num ],
  554. locations )
  555. # When opening tons of files, we don't want to have a split for each new
  556. # file, as this simply does not scale, so we open the window, make the
  557. # edits, then hide the window.
  558. if close_window:
  559. # Some plugins (I'm looking at you, syntastic) might open a location list
  560. # for the window we just opened. We don't want that location list hanging
  561. # around, so we close it. lclose is a no-op if there is no location list.
  562. vim.command( 'lclose' )
  563. # Note that this doesn't lose our changes. It simply "hides" the buffer,
  564. # which can later be re-accessed via the quickfix list or `:ls`
  565. vim.command( 'hide' )
  566. # Open the quickfix list, populated with entries for each location we changed.
  567. if locations:
  568. SetQuickFixList( locations )
  569. OpenQuickFixList()
  570. PostVimMessage( 'Applied {0} changes'.format( len( chunks ) ),
  571. warning = False )
  572. def ReplaceChunksInBuffer( chunks, vim_buffer, locations ):
  573. """Apply changes in |chunks| to the buffer-like object |buffer|. Append each
  574. chunk's start to the list |locations|"""
  575. # We need to track the difference in length, but ensuring we apply fixes
  576. # in ascending order of insertion point.
  577. chunks.sort( key = lambda chunk: (
  578. chunk[ 'range' ][ 'start' ][ 'line_num' ],
  579. chunk[ 'range' ][ 'start' ][ 'column_num' ]
  580. ) )
  581. # Remember the line number we're processing. Negative line number means we
  582. # haven't processed any lines yet (by nature of being not equal to any
  583. # real line number).
  584. last_line = -1
  585. line_delta = 0
  586. for chunk in chunks:
  587. if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line:
  588. # If this chunk is on a different line than the previous chunk,
  589. # then ignore previous deltas (as offsets won't have changed).
  590. last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ]
  591. char_delta = 0
  592. ( new_line_delta, new_char_delta ) = ReplaceChunk(
  593. chunk[ 'range' ][ 'start' ],
  594. chunk[ 'range' ][ 'end' ],
  595. chunk[ 'replacement_text' ],
  596. line_delta, char_delta,
  597. vim_buffer,
  598. locations )
  599. line_delta += new_line_delta
  600. char_delta += new_char_delta
  601. # Replace the chunk of text specified by a contiguous range with the supplied
  602. # text.
  603. # * start and end are objects with line_num and column_num properties
  604. # * the range is inclusive
  605. # * indices are all 1-based
  606. # * the returned character delta is the delta for the last line
  607. #
  608. # returns the delta (in lines and characters) that any position after the end
  609. # needs to be adjusted by.
  610. #
  611. # NOTE: Works exclusively with bytes() instances and byte offsets as returned
  612. # by ycmd and used within the Vim buffers
  613. def ReplaceChunk( start, end, replacement_text, line_delta, char_delta,
  614. vim_buffer, locations = None ):
  615. # ycmd's results are all 1-based, but vim's/python's are all 0-based
  616. # (so we do -1 on all of the values)
  617. start_line = start[ 'line_num' ] - 1 + line_delta
  618. end_line = end[ 'line_num' ] - 1 + line_delta
  619. source_lines_count = end_line - start_line + 1
  620. start_column = start[ 'column_num' ] - 1 + char_delta
  621. end_column = end[ 'column_num' ] - 1
  622. if source_lines_count == 1:
  623. end_column += char_delta
  624. # NOTE: replacement_text is unicode, but all our offsets are byte offsets,
  625. # so we convert to bytes
  626. replacement_lines = ToBytes( replacement_text ).splitlines( False )
  627. if not replacement_lines:
  628. replacement_lines = [ bytes( b'' ) ]
  629. replacement_lines_count = len( replacement_lines )
  630. # NOTE: Vim buffers are a list of byte objects on Python 2 but unicode
  631. # objects on Python 3.
  632. end_existing_text = ToBytes( vim_buffer[ end_line ] )[ end_column : ]
  633. start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ]
  634. new_char_delta = ( len( replacement_lines[ -1 ] )
  635. - ( end_column - start_column ) )
  636. if replacement_lines_count > 1:
  637. new_char_delta -= start_column
  638. replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  639. replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
  640. vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
  641. if locations is not None:
  642. locations.append( {
  643. 'bufnr': vim_buffer.number,
  644. 'filename': vim_buffer.name,
  645. # line and column numbers are 1-based in qflist
  646. 'lnum': start_line + 1,
  647. 'col': start_column + 1,
  648. 'text': replacement_text,
  649. 'type': 'F',
  650. } )
  651. new_line_delta = replacement_lines_count - source_lines_count
  652. return ( new_line_delta, new_char_delta )
  653. def InsertNamespace( namespace ):
  654. if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
  655. expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
  656. if expr:
  657. SetVariableValue( "g:ycm_namespace_to_insert", namespace )
  658. vim.eval( expr )
  659. return
  660. pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  661. existing_indent = ''
  662. line = SearchInCurrentBuffer( pattern )
  663. if line:
  664. existing_line = LineTextInCurrentBuffer( line )
  665. existing_indent = re.sub( r"\S.*", "", existing_line )
  666. new_line = "{0}using {1};\n\n".format( existing_indent, namespace )
  667. replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  668. ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0, vim.current.buffer )
  669. PostVimMessage( 'Add namespace: {0}'.format( namespace ), warning = False )
  670. def SearchInCurrentBuffer( pattern ):
  671. """ Returns the 1-indexed line on which the pattern matches
  672. (going UP from the current position) or 0 if not found """
  673. return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
  674. def LineTextInCurrentBuffer( line_number ):
  675. """ Returns the text on the 1-indexed line (NOT 0-indexed) """
  676. return vim.current.buffer[ line_number - 1 ]
  677. def ClosePreviewWindow():
  678. """ Close the preview window if it is present, otherwise do nothing """
  679. vim.command( 'silent! pclose!' )
  680. def JumpToPreviewWindow():
  681. """ Jump the vim cursor to the preview window, which must be active. Returns
  682. boolean indicating if the cursor ended up in the preview window """
  683. vim.command( 'silent! wincmd P' )
  684. return vim.current.window.options[ 'previewwindow' ]
  685. def JumpToPreviousWindow():
  686. """ Jump the vim cursor to its previous window position """
  687. vim.command( 'silent! wincmd p' )
  688. def JumpToTab( tab_number ):
  689. """Jump to Vim tab with corresponding number """
  690. vim.command( 'silent! tabn {0}'.format( tab_number ) )
  691. def OpenFileInPreviewWindow( filename ):
  692. """ Open the supplied filename in the preview window """
  693. vim.command( 'silent! pedit! ' + filename )
  694. def WriteToPreviewWindow( message ):
  695. """ Display the supplied message in the preview window """
  696. # This isn't something that comes naturally to Vim. Vim only wants to show
  697. # tags and/or actual files in the preview window, so we have to hack it a
  698. # little bit. We generate a temporary file name and "open" that, then write
  699. # the data to it. We make sure the buffer can't be edited or saved. Other
  700. # approaches include simply opening a split, but we want to take advantage of
  701. # the existing Vim options for preview window height, etc.
  702. ClosePreviewWindow()
  703. OpenFileInPreviewWindow( vim.eval( 'tempname()' ) )
  704. if JumpToPreviewWindow():
  705. # We actually got to the preview window. By default the preview window can't
  706. # be changed, so we make it writable, write to it, then make it read only
  707. # again.
  708. vim.current.buffer.options[ 'modifiable' ] = True
  709. vim.current.buffer.options[ 'readonly' ] = False
  710. vim.current.buffer[:] = message.splitlines()
  711. vim.current.buffer.options[ 'buftype' ] = 'nofile'
  712. vim.current.buffer.options[ 'bufhidden' ] = 'wipe'
  713. vim.current.buffer.options[ 'buflisted' ] = False
  714. vim.current.buffer.options[ 'swapfile' ] = False
  715. vim.current.buffer.options[ 'modifiable' ] = False
  716. vim.current.buffer.options[ 'readonly' ] = True
  717. # We need to prevent closing the window causing a warning about unsaved
  718. # file, so we pretend to Vim that the buffer has not been changed.
  719. vim.current.buffer.options[ 'modified' ] = False
  720. JumpToPreviousWindow()
  721. else:
  722. # We couldn't get to the preview window, but we still want to give the user
  723. # the information we have. The only remaining option is to echo to the
  724. # status area.
  725. PostVimMessage( message, warning = False )
  726. def BufferIsVisibleForFilename( filename ):
  727. """Check if a buffer exists for a specific file."""
  728. buffer_number = GetBufferNumberForFilename( filename, False )
  729. return BufferIsVisible( buffer_number )
  730. def CloseBuffersForFilename( filename ):
  731. """Close all buffers for a specific file."""
  732. buffer_number = GetBufferNumberForFilename( filename, False )
  733. while buffer_number != -1:
  734. vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) )
  735. new_buffer_number = GetBufferNumberForFilename( filename, False )
  736. if buffer_number == new_buffer_number:
  737. raise RuntimeError( "Buffer {0} for filename '{1}' should already be "
  738. "wiped out.".format( buffer_number, filename ) )
  739. buffer_number = new_buffer_number
  740. def OpenFilename( filename, options = {} ):
  741. """Open a file in Vim. Following options are available:
  742. - command: specify which Vim command is used to open the file. Choices
  743. are same-buffer, horizontal-split, vertical-split, and new-tab (default:
  744. horizontal-split);
  745. - size: set the height of the window for a horizontal split or the width for
  746. a vertical one (default: '');
  747. - fix: set the winfixheight option for a horizontal split or winfixwidth for
  748. a vertical one (default: False). See :h winfix for details;
  749. - focus: focus the opened file (default: False);
  750. - watch: automatically watch for changes (default: False). This is useful
  751. for logs;
  752. - position: set the position where the file is opened (default: start).
  753. Choices are start and end."""
  754. # Set the options.
  755. command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
  756. 'horizontal-split' )
  757. size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
  758. '' )
  759. focus = options.get( 'focus', False )
  760. # There is no command in Vim to return to the previous tab so we need to
  761. # remember the current tab if needed.
  762. if not focus and command == 'tabedit':
  763. previous_tab = GetIntValue( 'tabpagenr()' )
  764. else:
  765. previous_tab = None
  766. # Open the file.
  767. try:
  768. vim.command( '{0}{1} {2}'.format( size, command, filename ) )
  769. # When the file we are trying to jump to has a swap file,
  770. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  771. # or KeyboardInterrupt after user selects one of the options which actually
  772. # opens the file (Open read-only/Edit anyway).
  773. except vim.error as e:
  774. if 'E325' not in str( e ):
  775. raise
  776. # Otherwise, the user might have chosen Quit. This is detectable by the
  777. # current file not being the target file
  778. if filename != GetCurrentBufferFilepath():
  779. return
  780. except KeyboardInterrupt:
  781. # Raised when the user selects "Abort" after swap-exists-choices
  782. return
  783. _SetUpLoadedBuffer( command,
  784. filename,
  785. options.get( 'fix', False ),
  786. options.get( 'position', 'start' ),
  787. options.get( 'watch', False ) )
  788. # Vim automatically set the focus to the opened file so we need to get the
  789. # focus back (if the focus option is disabled) when opening a new tab or
  790. # window.
  791. if not focus:
  792. if command == 'tabedit':
  793. JumpToTab( previous_tab )
  794. if command in [ 'split', 'vsplit' ]:
  795. JumpToPreviousWindow()
  796. def _SetUpLoadedBuffer( command, filename, fix, position, watch ):
  797. """After opening a buffer, configure it according to the supplied options,
  798. which are as defined by the OpenFilename method."""
  799. if command == 'split':
  800. vim.current.window.options[ 'winfixheight' ] = fix
  801. if command == 'vsplit':
  802. vim.current.window.options[ 'winfixwidth' ] = fix
  803. if watch:
  804. vim.current.buffer.options[ 'autoread' ] = True
  805. vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
  806. .format( filename ) )
  807. if position == 'end':
  808. vim.command( 'silent! normal! Gzz' )