vimsupport.py 55 KB

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