vimsupport.py 47 KB

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