vimsupport.py 47 KB

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