vimsupport.py 45 KB

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