vimsupport.py 46 KB

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