vimsupport.py 44 KB

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