vimsupport.py 38 KB

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