vimsupport.py 45 KB

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