vimsupport.py 46 KB

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