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