vimsupport.py 54 KB

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