vimsupport.py 54 KB

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