vimsupport.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  228. # When |overwrite| is True, overwrites the existing value in Vim.
  229. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  230. extend_option = '"force"' if overwrite else '"keep"'
  231. # We need to use json.dumps because that won't use the 'u' prefix on strings
  232. # which Vim would bork on.
  233. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  234. extend_option ) )
  235. # Changing the returned dict will NOT change the value in Vim.
  236. def GetReadOnlyVimGlobals( force_python_objects = False ):
  237. if force_python_objects:
  238. return vim.eval( 'g:' )
  239. try:
  240. # vim.vars is fairly new so it might not exist
  241. return vim.vars
  242. except:
  243. return vim.eval( 'g:' )
  244. def VimExpressionToPythonType( vim_expression ):
  245. result = vim.eval( vim_expression )
  246. if not isinstance( result, str ):
  247. return result
  248. try:
  249. return int( result )
  250. except ValueError:
  251. return result
  252. def HiddenEnabled( buffer_object ):
  253. return bool( int( GetBufferOption( buffer_object, 'hid' ) ) )
  254. def BufferIsUsable( buffer_object ):
  255. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  256. def EscapedFilepath( filepath ):
  257. return filepath.replace( ' ' , r'\ ' )
  258. # Both |line| and |column| need to be 1-based
  259. def TryJumpLocationInOpenedTab( filename, line, column ):
  260. filepath = os.path.realpath( filename )
  261. for tab in vim.tabpages:
  262. for win in tab.windows:
  263. if win.buffer.name == filepath:
  264. vim.current.tabpage = tab
  265. vim.current.window = win
  266. vim.current.window.cursor = ( line, column - 1 )
  267. # Center the screen on the jumped-to location
  268. vim.command( 'normal! zz' )
  269. return True
  270. # 'filename' is not opened in any tab pages
  271. return False
  272. # Maps User command to vim command
  273. def GetVimCommand( user_command, default = 'edit' ):
  274. vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
  275. if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  276. vim_command = 'split'
  277. return vim_command
  278. # Both |line| and |column| need to be 1-based
  279. def JumpToLocation( filename, line, column ):
  280. # Add an entry to the jumplist
  281. vim.command( "normal! m'" )
  282. if filename != GetCurrentBufferFilepath():
  283. # We prefix the command with 'keepjumps' so that opening the file is not
  284. # recorded in the jumplist. So when we open the file and move the cursor to
  285. # a location in it, the user can use CTRL-O to jump back to the original
  286. # location, not to the start of the newly opened file.
  287. # Sadly this fails on random occasions and the undesired jump remains in the
  288. # jumplist.
  289. user_command = user_options_store.Value( 'goto_buffer_command' )
  290. if user_command == 'new-or-existing-tab':
  291. if TryJumpLocationInOpenedTab( filename, line, column ):
  292. return
  293. user_command = 'new-tab'
  294. vim_command = GetVimCommand( user_command )
  295. try:
  296. vim.command( 'keepjumps {0} {1}'.format( vim_command,
  297. EscapedFilepath( filename ) ) )
  298. # When the file we are trying to jump to has a swap file
  299. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  300. # or KeyboardInterrupt after user selects one of the options.
  301. except vim.error as e:
  302. if 'E325' not in str( e ):
  303. raise
  304. # Do nothing if the target file is still not opened (user chose (Q)uit)
  305. if filename != GetCurrentBufferFilepath():
  306. return
  307. # Thrown when user chooses (A)bort in .swp message box
  308. except KeyboardInterrupt:
  309. return
  310. vim.current.window.cursor = ( line, column - 1 )
  311. # Center the screen on the jumped-to location
  312. vim.command( 'normal! zz' )
  313. def NumLinesInBuffer( buffer_object ):
  314. # This is actually less than obvious, that's why it's wrapped in a function
  315. return len( buffer_object )
  316. # Calling this function from the non-GUI thread will sometimes crash Vim. At
  317. # the time of writing, YCM only uses the GUI thread inside Vim (this used to
  318. # not be the case).
  319. # We redraw the screen before displaying the message to avoid the "Press ENTER
  320. # or type command to continue" prompt when editing a new C-family file.
  321. def PostVimMessage( message ):
  322. vim.command( "redraw | echohl WarningMsg | echom '{0}' | echohl None"
  323. .format( EscapeForVim( ToUnicode( message ) ) ) )
  324. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  325. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  326. # appear in Vim's message log.
  327. def PostMultiLineNotice( message ):
  328. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  329. .format( EscapeForVim( ToUnicode( message ) ) ) )
  330. def PresentDialog( message, choices, default_choice_index = 0 ):
  331. """Presents the user with a dialog where a choice can be made.
  332. This will be a dialog for gvim users or a question in the message buffer
  333. for vim users or if `set guioptions+=c` was used.
  334. choices is list of alternatives.
  335. default_choice_index is the 0-based index of the default element
  336. that will get choosen if the user hits <CR>. Use -1 for no default.
  337. PresentDialog will return a 0-based index into the list
  338. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  339. See also:
  340. :help confirm() in vim (Note that vim uses 1-based indexes)
  341. Example call:
  342. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  343. Is this a nice example?
  344. [Y]es, (N)o, May(b)e:"""
  345. to_eval = "confirm('{0}', '{1}', {2})".format(
  346. EscapeForVim( ToUnicode( message ) ),
  347. EscapeForVim( ToUnicode( "\n" .join( choices ) ) ),
  348. default_choice_index + 1 )
  349. return int( vim.eval( to_eval ) ) - 1
  350. def Confirm( message ):
  351. """Display |message| with Ok/Cancel operations. Returns True if the user
  352. selects Ok"""
  353. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  354. def EchoText( text, log_as_message = True ):
  355. def EchoLine( text ):
  356. command = 'echom' if log_as_message else 'echo'
  357. vim.command( "{0} '{1}'".format( command,
  358. EscapeForVim( text ) ) )
  359. for line in ToUnicode( text ).split( '\n' ):
  360. EchoLine( line )
  361. # Echos text but truncates it so that it all fits on one line
  362. def EchoTextVimWidth( text ):
  363. vim_width = GetIntValue( '&columns' )
  364. truncated_text = ToUnicode( text )[ : int( vim_width * 0.9 ) ]
  365. truncated_text.replace( '\n', ' ' )
  366. old_ruler = GetIntValue( '&ruler' )
  367. old_showcmd = GetIntValue( '&showcmd' )
  368. vim.command( 'set noruler noshowcmd' )
  369. vim.command( 'redraw' )
  370. EchoText( truncated_text, False )
  371. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  372. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  373. def EscapeForVim( text ):
  374. return ToUnicode( text.replace( "'", "''" ) )
  375. def CurrentFiletypes():
  376. return vim.eval( "&filetype" ).split( '.' )
  377. def FiletypesForBuffer( buffer_object ):
  378. # NOTE: Getting &ft for other buffers only works when the buffer has been
  379. # visited by the user at least once, which is true for modified buffers
  380. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  381. def VariableExists( variable ):
  382. return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
  383. def SetVariableValue( variable, value ):
  384. vim.command( "let {0} = '{1}'".format( variable, EscapeForVim( value ) ) )
  385. def GetVariableValue( variable ):
  386. return vim.eval( variable )
  387. def GetBoolValue( variable ):
  388. return bool( int( vim.eval( variable ) ) )
  389. def GetIntValue( variable ):
  390. return int( vim.eval( variable ) )
  391. def _SortChunksByFile( chunks ):
  392. """Sort the members of the list |chunks| (which must be a list of dictionaries
  393. conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new
  394. list in arbitrary order."""
  395. chunks_by_file = defaultdict( list )
  396. for chunk in chunks:
  397. filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ]
  398. chunks_by_file[ filepath ].append( chunk )
  399. return chunks_by_file
  400. def _GetNumNonVisibleFiles( file_list ):
  401. """Returns the number of file in the iterable list of files |file_list| which
  402. are not curerntly open in visible windows"""
  403. return len(
  404. [ f for f in file_list
  405. if not BufferIsVisible( GetBufferNumberForFilename( f, False ) ) ] )
  406. def _OpenFileInSplitIfNeeded( filepath ):
  407. """Ensure that the supplied filepath is open in a visible window, opening a
  408. new split if required. Returns the buffer number of the file and an indication
  409. of whether or not a new split was opened.
  410. If the supplied filename is already open in a visible window, return just
  411. return its buffer number. If the supplied file is not visible in a window
  412. in the current tab, opens it in a new vertical split.
  413. Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer
  414. number and whether or not this method created a new split. If the user opts
  415. not to open a file, or if opening fails, this method raises RuntimeError,
  416. otherwise, guarantees to return a visible buffer number in buffer_num."""
  417. buffer_num = GetBufferNumberForFilename( filepath, False )
  418. # We only apply changes in the current tab page (i.e. "visible" windows).
  419. # Applying changes in tabs does not lead to a better user experience, as the
  420. # quickfix list no longer works as you might expect (doesn't jump into other
  421. # tabs), and the complexity of choosing where to apply edits is significant.
  422. if BufferIsVisible( buffer_num ):
  423. # file is already open and visible, just return that buffer number (and an
  424. # idicator that we *didn't* open a split)
  425. return ( buffer_num, False )
  426. # The file is not open in a visible window, so we open it in a split.
  427. # We open the file with a small, fixed height. This means that we don't
  428. # make the current buffer the smallest after a series of splits.
  429. OpenFilename( filepath, {
  430. 'focus': True,
  431. 'fix': True,
  432. 'size': GetIntValue( '&previewheight' ),
  433. } )
  434. # OpenFilename returns us to the original cursor location. This is what we
  435. # want, because we don't want to disorientate the user, but we do need to
  436. # know the (now open) buffer number for the filename
  437. buffer_num = GetBufferNumberForFilename( filepath, False )
  438. if not BufferIsVisible( buffer_num ):
  439. # This happens, for example, if there is a swap file and the user
  440. # selects the "Quit" or "Abort" options. We just raise an exception to
  441. # make it clear to the user that the abort has left potentially
  442. # partially-applied changes.
  443. raise RuntimeError(
  444. 'Unable to open file: {0}\nFixIt/Refactor operation '
  445. 'aborted prior to completion. Your files have not been '
  446. 'fully updated. Please use undo commands to revert the '
  447. 'applied changes.'.format( filepath ) )
  448. # We opened this file in a split
  449. return ( buffer_num, True )
  450. def ReplaceChunks( chunks ):
  451. """Apply the source file deltas supplied in |chunks| to arbitrary files.
  452. |chunks| is a list of changes defined by ycmd.responses.FixItChunk,
  453. which may apply arbitrary modifications to arbitrary files.
  454. If a file specified in a particular chunk is not currently open in a visible
  455. buffer (i.e., one in a window visible in the current tab), we:
  456. - issue a warning to the user that we're going to open new files (and offer
  457. her the option to abort cleanly)
  458. - open the file in a new split, make the changes, then hide the buffer.
  459. If for some reason a file could not be opened or changed, raises RuntimeError.
  460. Otherwise, returns no meaningful value."""
  461. # We apply the edits file-wise for efficiency, and because we must track the
  462. # file-wise offset deltas (caused by the modifications to the text).
  463. chunks_by_file = _SortChunksByFile( chunks )
  464. # We sort the file list simply to enable repeatable testing
  465. sorted_file_list = sorted( iterkeys( chunks_by_file ) )
  466. # Make sure the user is prepared to have her screen mutilated by the new
  467. # buffers
  468. num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list )
  469. if num_files_to_open > 0:
  470. if not Confirm(
  471. FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ):
  472. return
  473. # Store the list of locations where we applied changes. We use this to display
  474. # the quickfix window showing the user where we applied changes.
  475. locations = []
  476. for filepath in sorted_file_list:
  477. ( buffer_num, close_window ) = _OpenFileInSplitIfNeeded( filepath )
  478. ReplaceChunksInBuffer( chunks_by_file[ filepath ],
  479. vim.buffers[ buffer_num ],
  480. locations )
  481. # When opening tons of files, we don't want to have a split for each new
  482. # file, as this simply does not scale, so we open the window, make the
  483. # edits, then hide the window.
  484. if close_window:
  485. # Some plugins (I'm looking at you, syntastic) might open a location list
  486. # for the window we just opened. We don't want that location list hanging
  487. # around, so we close it. lclose is a no-op if there is no location list.
  488. vim.command( 'lclose' )
  489. # Note that this doesn't lose our changes. It simply "hides" the buffer,
  490. # which can later be re-accessed via the quickfix list or `:ls`
  491. vim.command( 'hide' )
  492. # Open the quickfix list, populated with entries for each location we changed.
  493. if locations:
  494. SetQuickFixList( locations, True )
  495. EchoTextVimWidth( "Applied " + str( len( chunks ) ) + " changes" )
  496. def ReplaceChunksInBuffer( chunks, vim_buffer, locations ):
  497. """Apply changes in |chunks| to the buffer-like object |buffer|. Append each
  498. chunk's start to the list |locations|"""
  499. # We need to track the difference in length, but ensuring we apply fixes
  500. # in ascending order of insertion point.
  501. chunks.sort( key = lambda chunk: (
  502. chunk[ 'range' ][ 'start' ][ 'line_num' ],
  503. chunk[ 'range' ][ 'start' ][ 'column_num' ]
  504. ) )
  505. # Remember the line number we're processing. Negative line number means we
  506. # haven't processed any lines yet (by nature of being not equal to any
  507. # real line number).
  508. last_line = -1
  509. line_delta = 0
  510. for chunk in chunks:
  511. if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line:
  512. # If this chunk is on a different line than the previous chunk,
  513. # then ignore previous deltas (as offsets won't have changed).
  514. last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ]
  515. char_delta = 0
  516. ( new_line_delta, new_char_delta ) = ReplaceChunk(
  517. chunk[ 'range' ][ 'start' ],
  518. chunk[ 'range' ][ 'end' ],
  519. chunk[ 'replacement_text' ],
  520. line_delta, char_delta,
  521. vim_buffer,
  522. locations )
  523. line_delta += new_line_delta
  524. char_delta += new_char_delta
  525. # Replace the chunk of text specified by a contiguous range with the supplied
  526. # text.
  527. # * start and end are objects with line_num and column_num properties
  528. # * the range is inclusive
  529. # * indices are all 1-based
  530. # * the returned character delta is the delta for the last line
  531. #
  532. # returns the delta (in lines and characters) that any position after the end
  533. # needs to be adjusted by.
  534. def ReplaceChunk( start, end, replacement_text, line_delta, char_delta,
  535. vim_buffer, locations = None ):
  536. # ycmd's results are all 1-based, but vim's/python's are all 0-based
  537. # (so we do -1 on all of the values)
  538. start_line = start[ 'line_num' ] - 1 + line_delta
  539. end_line = end[ 'line_num' ] - 1 + line_delta
  540. source_lines_count = end_line - start_line + 1
  541. start_column = start[ 'column_num' ] - 1 + char_delta
  542. end_column = end[ 'column_num' ] - 1
  543. if source_lines_count == 1:
  544. end_column += char_delta
  545. replacement_lines = replacement_text.splitlines( False )
  546. if not replacement_lines:
  547. replacement_lines = [ '' ]
  548. replacement_lines_count = len( replacement_lines )
  549. end_existing_text = vim_buffer[ end_line ][ end_column : ]
  550. start_existing_text = vim_buffer[ start_line ][ : start_column ]
  551. new_char_delta = ( len( replacement_lines[ -1 ] )
  552. - ( end_column - start_column ) )
  553. if replacement_lines_count > 1:
  554. new_char_delta -= start_column
  555. replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  556. replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
  557. vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
  558. if locations is not None:
  559. locations.append( {
  560. 'bufnr': vim_buffer.number,
  561. 'filename': vim_buffer.name,
  562. # line and column numbers are 1-based in qflist
  563. 'lnum': start_line + 1,
  564. 'col': start_column + 1,
  565. 'text': replacement_text,
  566. 'type': 'F',
  567. } )
  568. new_line_delta = replacement_lines_count - source_lines_count
  569. return ( new_line_delta, new_char_delta )
  570. def InsertNamespace( namespace ):
  571. if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
  572. expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
  573. if expr:
  574. SetVariableValue( "g:ycm_namespace_to_insert", namespace )
  575. vim.eval( expr )
  576. return
  577. pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  578. line = SearchInCurrentBuffer( pattern )
  579. existing_line = LineTextInCurrentBuffer( line )
  580. existing_indent = re.sub( r"\S.*", "", existing_line )
  581. new_line = "{0}using {1};\n\n".format( existing_indent, namespace )
  582. replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  583. ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0 )
  584. PostVimMessage( "Add namespace: {0}".format( namespace ) )
  585. def SearchInCurrentBuffer( pattern ):
  586. return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
  587. def LineTextInCurrentBuffer( line ):
  588. return vim.current.buffer[ line ]
  589. def ClosePreviewWindow():
  590. """ Close the preview window if it is present, otherwise do nothing """
  591. vim.command( 'silent! pclose!' )
  592. def JumpToPreviewWindow():
  593. """ Jump the vim cursor to the preview window, which must be active. Returns
  594. boolean indicating if the cursor ended up in the preview window """
  595. vim.command( 'silent! wincmd P' )
  596. return vim.current.window.options[ 'previewwindow' ]
  597. def JumpToPreviousWindow():
  598. """ Jump the vim cursor to its previous window position """
  599. vim.command( 'silent! wincmd p' )
  600. def JumpToTab( tab_number ):
  601. """Jump to Vim tab with corresponding number """
  602. vim.command( 'silent! tabn {0}'.format( tab_number ) )
  603. def OpenFileInPreviewWindow( filename ):
  604. """ Open the supplied filename in the preview window """
  605. vim.command( 'silent! pedit! ' + filename )
  606. def WriteToPreviewWindow( message ):
  607. """ Display the supplied message in the preview window """
  608. # This isn't something that comes naturally to Vim. Vim only wants to show
  609. # tags and/or actual files in the preview window, so we have to hack it a
  610. # little bit. We generate a temporary file name and "open" that, then write
  611. # the data to it. We make sure the buffer can't be edited or saved. Other
  612. # approaches include simply opening a split, but we want to take advantage of
  613. # the existing Vim options for preview window height, etc.
  614. ClosePreviewWindow()
  615. OpenFileInPreviewWindow( vim.eval( 'tempname()' ) )
  616. if JumpToPreviewWindow():
  617. # We actually got to the preview window. By default the preview window can't
  618. # be changed, so we make it writable, write to it, then make it read only
  619. # again.
  620. vim.current.buffer.options[ 'modifiable' ] = True
  621. vim.current.buffer.options[ 'readonly' ] = False
  622. vim.current.buffer[:] = message.splitlines()
  623. vim.current.buffer.options[ 'buftype' ] = 'nofile'
  624. vim.current.buffer.options[ 'swapfile' ] = False
  625. vim.current.buffer.options[ 'modifiable' ] = False
  626. vim.current.buffer.options[ 'readonly' ] = True
  627. # We need to prevent closing the window causing a warning about unsaved
  628. # file, so we pretend to Vim that the buffer has not been changed.
  629. vim.current.buffer.options[ 'modified' ] = False
  630. JumpToPreviousWindow()
  631. else:
  632. # We couldn't get to the preview window, but we still want to give the user
  633. # the information we have. The only remaining option is to echo to the
  634. # status area.
  635. EchoText( message )
  636. def CheckFilename( filename ):
  637. """Check if filename is openable."""
  638. try:
  639. open( filename ).close()
  640. except TypeError:
  641. raise RuntimeError( "'{0}' is not a valid filename".format( filename ) )
  642. except IOError as error:
  643. raise RuntimeError(
  644. "filename '{0}' cannot be opened. {1}".format( filename, error ) )
  645. def BufferIsVisibleForFilename( filename ):
  646. """Check if a buffer exists for a specific file."""
  647. buffer_number = GetBufferNumberForFilename( filename, False )
  648. return BufferIsVisible( buffer_number )
  649. def CloseBuffersForFilename( filename ):
  650. """Close all buffers for a specific file."""
  651. buffer_number = GetBufferNumberForFilename( filename, False )
  652. while buffer_number != -1:
  653. vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) )
  654. new_buffer_number = GetBufferNumberForFilename( filename, False )
  655. if buffer_number == new_buffer_number:
  656. raise RuntimeError( "Buffer {0} for filename '{1}' should already be "
  657. "wiped out.".format( buffer_number, filename ) )
  658. buffer_number = new_buffer_number
  659. def OpenFilename( filename, options = {} ):
  660. """Open a file in Vim. Following options are available:
  661. - command: specify which Vim command is used to open the file. Choices
  662. are same-buffer, horizontal-split, vertical-split, and new-tab (default:
  663. horizontal-split);
  664. - size: set the height of the window for a horizontal split or the width for
  665. a vertical one (default: '');
  666. - fix: set the winfixheight option for a horizontal split or winfixwidth for
  667. a vertical one (default: False). See :h winfix for details;
  668. - focus: focus the opened file (default: False);
  669. - watch: automatically watch for changes (default: False). This is useful
  670. for logs;
  671. - position: set the position where the file is opened (default: start).
  672. Choices are start and end."""
  673. # Set the options.
  674. command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
  675. 'horizontal-split' )
  676. size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
  677. '' )
  678. focus = options.get( 'focus', False )
  679. # There is no command in Vim to return to the previous tab so we need to
  680. # remember the current tab if needed.
  681. if not focus and command == 'tabedit':
  682. previous_tab = GetIntValue( 'tabpagenr()' )
  683. else:
  684. previous_tab = None
  685. # Open the file
  686. CheckFilename( filename )
  687. try:
  688. vim.command( '{0}{1} {2}'.format( size, command, filename ) )
  689. # When the file we are trying to jump to has a swap file,
  690. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  691. # or KeyboardInterrupt after user selects one of the options which actually
  692. # opens the file (Open read-only/Edit anyway).
  693. except vim.error as e:
  694. if 'E325' not in str( e ):
  695. raise
  696. # Otherwise, the user might have chosen Quit. This is detectable by the
  697. # current file not being the target file
  698. if filename != GetCurrentBufferFilepath():
  699. return
  700. except KeyboardInterrupt:
  701. # Raised when the user selects "Abort" after swap-exists-choices
  702. return
  703. _SetUpLoadedBuffer( command,
  704. filename,
  705. options.get( 'fix', False ),
  706. options.get( 'position', 'start' ),
  707. options.get( 'watch', False ) )
  708. # Vim automatically set the focus to the opened file so we need to get the
  709. # focus back (if the focus option is disabled) when opening a new tab or
  710. # window.
  711. if not focus:
  712. if command == 'tabedit':
  713. JumpToTab( previous_tab )
  714. if command in [ 'split', 'vsplit' ]:
  715. JumpToPreviousWindow()
  716. def _SetUpLoadedBuffer( command, filename, fix, position, watch ):
  717. """After opening a buffer, configure it according to the supplied options,
  718. which are as defined by the OpenFilename method."""
  719. if command == 'split':
  720. vim.current.window.options[ 'winfixheight' ] = fix
  721. if command == 'vsplit':
  722. vim.current.window.options[ 'winfixwidth' ] = fix
  723. if watch:
  724. vim.current.buffer.options[ 'autoread' ] = True
  725. vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
  726. .format( filename ) )
  727. if position == 'end':
  728. vim.command( 'silent! normal G zz' )