vimsupport.py 53 KB

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