vimsupport.py 51 KB

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