vimsupport.py 55 KB

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