vimsupport.py 45 KB

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