vimsupport.py 34 KB

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