vimsupport.py 40 KB

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