vimsupport.py 47 KB

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