vimsupport.py 38 KB

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