1
0

vimsupport.py 34 KB

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