1
0

vimsupport.py 55 KB

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