vimsupport.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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. from __future__ import unicode_literals
  18. from __future__ import print_function
  19. from __future__ import division
  20. from __future__ import absolute_import
  21. # Not installing aliases from python-future; it's unreliable and slow.
  22. from builtins import * # noqa
  23. from future.utils import iterkeys
  24. import vim
  25. import os
  26. import json
  27. import re
  28. from collections import defaultdict, namedtuple
  29. from ycmd.utils import ( ByteOffsetToCodepointOffset, GetCurrentDirectory,
  30. JoinLinesAsUnicode, ToBytes, ToUnicode )
  31. from ycmd import user_options_store
  32. BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
  33. 'horizontal-split' : 'split',
  34. 'vertical-split' : 'vsplit',
  35. 'new-tab' : 'tabedit' }
  36. FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = (
  37. 'The requested operation will apply changes to {0} files which are not '
  38. 'currently open. This will therefore open {0} new files in the hidden '
  39. 'buffers. The quickfix list can then be used to review the changes. No '
  40. 'files will be written to disk. Do you wish to continue?' )
  41. NO_SELECTION_MADE_MSG = "No valid selection was made; aborting."
  42. # This is the starting value assigned to the sign's id of each buffer. This
  43. # value is then incremented for each new sign. This should prevent conflicts
  44. # with other plugins using signs.
  45. SIGN_BUFFER_ID_INITIAL_VALUE = 100000000
  46. # This holds the next sign's id to assign for each buffer.
  47. SIGN_ID_FOR_BUFFER = defaultdict( lambda: SIGN_BUFFER_ID_INITIAL_VALUE )
  48. SIGN_PLACE_REGEX = re.compile(
  49. r"^.*=(?P<line>\d+).*=(?P<id>\d+).*=(?P<name>Ycm\w+)$" )
  50. def CurrentLineAndColumn():
  51. """Returns the 0-based current line and 0-based current column."""
  52. # See the comment in CurrentColumn about the calculation for the line and
  53. # column number
  54. line, column = vim.current.window.cursor
  55. line -= 1
  56. return line, column
  57. def SetCurrentLineAndColumn( line, column ):
  58. """Sets the cursor position to the 0-based line and 0-based column."""
  59. # Line from vim.current.window.cursor is 1-based.
  60. vim.current.window.cursor = ( line + 1, column )
  61. def CurrentColumn():
  62. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  63. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  64. line. Only the chars before the current column exist in vim.current.line."""
  65. # vim's columns are 1-based while vim.current.line columns are 0-based
  66. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  67. # columns are 0-based, while the line from that same tuple is 1-based.
  68. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  69. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  70. return vim.current.window.cursor[ 1 ]
  71. def CurrentLineContents():
  72. return ToUnicode( vim.current.line )
  73. def CurrentLineContentsAndCodepointColumn():
  74. """Returns the line contents as a unicode string and the 0-based current
  75. column as a codepoint offset. If the current column is outside the line,
  76. returns the column position at the end of the line."""
  77. line = CurrentLineContents()
  78. byte_column = CurrentColumn()
  79. # ByteOffsetToCodepointOffset expects 1-based offset.
  80. column = ByteOffsetToCodepointOffset( line, byte_column + 1 ) - 1
  81. return line, column
  82. def TextAfterCursor():
  83. """Returns the text after CurrentColumn."""
  84. return ToUnicode( vim.current.line[ CurrentColumn(): ] )
  85. def TextBeforeCursor():
  86. """Returns the text before CurrentColumn."""
  87. return ToUnicode( vim.current.line[ :CurrentColumn() ] )
  88. def BufferModified( buffer_object ):
  89. return buffer_object.options[ 'mod' ]
  90. def GetBufferData( buffer_object ):
  91. return {
  92. # Add a newline to match what gets saved to disk. See #1455 for details.
  93. 'contents': JoinLinesAsUnicode( buffer_object ) + '\n',
  94. 'filetypes': FiletypesForBuffer( buffer_object )
  95. }
  96. def GetUnsavedAndSpecifiedBufferData( included_buffer, included_filepath ):
  97. """Build part of the request containing the contents and filetypes of all
  98. dirty buffers as well as the buffer |included_buffer| with its filepath
  99. |included_filepath|."""
  100. buffers_data = { included_filepath: GetBufferData( included_buffer ) }
  101. for buffer_object in vim.buffers:
  102. if not BufferModified( buffer_object ):
  103. continue
  104. filepath = GetBufferFilepath( buffer_object )
  105. if filepath in buffers_data:
  106. continue
  107. buffers_data[ filepath ] = GetBufferData( buffer_object )
  108. return buffers_data
  109. def GetBufferNumberForFilename( filename, create_buffer_if_needed = False ):
  110. return GetIntValue( u"bufnr('{0}', {1})".format(
  111. EscapeForVim( os.path.realpath( filename ) ),
  112. int( create_buffer_if_needed ) ) )
  113. def GetCurrentBufferFilepath():
  114. return GetBufferFilepath( vim.current.buffer )
  115. def BufferIsVisible( buffer_number ):
  116. if buffer_number < 0:
  117. return False
  118. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  119. return window_number != -1
  120. def GetBufferFilepath( buffer_object ):
  121. if buffer_object.name:
  122. return os.path.normpath( ToUnicode( buffer_object.name ) )
  123. # Buffers that have just been created by a command like :enew don't have any
  124. # buffer name so we use the buffer number for that.
  125. return os.path.join( GetCurrentDirectory(), str( buffer_object.number ) )
  126. def GetCurrentBufferNumber():
  127. return vim.current.buffer.number
  128. def GetBufferChangedTick( bufnr ):
  129. return GetIntValue( 'getbufvar({0}, "changedtick")'.format( bufnr ) )
  130. def CaptureVimCommand( command ):
  131. vim.command( 'redir => b:ycm_command' )
  132. vim.command( 'silent! {}'.format( command ) )
  133. vim.command( 'redir END' )
  134. output = ToUnicode( vim.eval( 'b:ycm_command' ) )
  135. vim.command( 'unlet b:ycm_command' )
  136. return output
  137. class DiagnosticSign( namedtuple( 'DiagnosticSign',
  138. [ 'id', 'line', 'name', 'buffer_number' ] ) ):
  139. # We want two signs that have different ids but the same location to compare
  140. # equal. ID doesn't matter.
  141. def __eq__( self, other ):
  142. return ( self.line == other.line and
  143. self.name == other.name and
  144. self.buffer_number == other.buffer_number )
  145. def GetSignsInBuffer( buffer_number ):
  146. sign_output = CaptureVimCommand(
  147. 'sign place buffer={}'.format( buffer_number ) )
  148. signs = []
  149. for line in sign_output.split( '\n' ):
  150. match = SIGN_PLACE_REGEX.search( line )
  151. if match:
  152. signs.append( DiagnosticSign( int( match.group( 'id' ) ),
  153. int( match.group( 'line' ) ),
  154. match.group( 'name' ),
  155. buffer_number ) )
  156. return signs
  157. def CreateSign( line, name, buffer_number ):
  158. sign_id = SIGN_ID_FOR_BUFFER[ buffer_number ]
  159. SIGN_ID_FOR_BUFFER[ buffer_number ] += 1
  160. return DiagnosticSign( sign_id, line, name, buffer_number )
  161. def UnplaceSign( sign ):
  162. vim.command( 'sign unplace {0} buffer={1}'.format( sign.id,
  163. sign.buffer_number ) )
  164. def PlaceSign( sign ):
  165. vim.command( 'sign place {0} name={1} line={2} buffer={3}'.format(
  166. sign.id, sign.name, sign.line, sign.buffer_number ) )
  167. class DiagnosticMatch( namedtuple( 'DiagnosticMatch',
  168. [ 'id', 'group', 'pattern' ] ) ):
  169. def __eq__( self, other ):
  170. return ( self.group == other.group and
  171. self.pattern == other.pattern )
  172. def GetDiagnosticMatchesInCurrentWindow():
  173. vim_matches = vim.eval( 'getmatches()' )
  174. return [ DiagnosticMatch( match[ 'id' ],
  175. match[ 'group' ],
  176. match[ 'pattern' ] )
  177. for match in vim_matches if match[ 'group' ].startswith( 'Ycm' ) ]
  178. def AddDiagnosticMatch( match ):
  179. return GetIntValue( "matchadd('{}', '{}')".format( match.group,
  180. match.pattern ) )
  181. def RemoveDiagnosticMatch( match ):
  182. return GetIntValue( "matchdelete({})".format( match.id ) )
  183. def GetDiagnosticMatchPattern( line_num,
  184. column_num,
  185. line_end_num = None,
  186. column_end_num = None ):
  187. line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
  188. if not line_end_num or not column_end_num:
  189. return '\%{}l\%{}c'.format( line_num, column_num )
  190. # -1 and then +1 to account for column end not included in the range.
  191. line_end_num, column_end_num = LineAndColumnNumbersClamped(
  192. line_end_num, column_end_num - 1 )
  193. column_end_num += 1
  194. return '\%{}l\%{}c\_.\\{{-}}\%{}l\%{}c'.format( line_num,
  195. column_num,
  196. line_end_num,
  197. column_end_num )
  198. # Clamps the line and column numbers so that they are not past the contents of
  199. # the buffer. Numbers are 1-based byte offsets.
  200. def LineAndColumnNumbersClamped( line_num, column_num ):
  201. new_line_num = line_num
  202. new_column_num = column_num
  203. max_line = len( vim.current.buffer )
  204. if line_num and line_num > max_line:
  205. new_line_num = max_line
  206. # Vim buffers are a list of byte objects on Python 2 but Unicode objects on
  207. # Python 3.
  208. max_column = len( ToBytes( vim.current.buffer[ new_line_num - 1 ] ) )
  209. if column_num and column_num > max_column:
  210. new_column_num = max_column
  211. return new_line_num, new_column_num
  212. def SetLocationList( diagnostics ):
  213. """Set the location list for the current window to the supplied diagnostics"""
  214. SetLocationListForWindow( 0, diagnostics )
  215. def GetWindowNumberForBufferDiagnostics( buffer_number ):
  216. """Return an appropriate window number to use for displaying diagnostics
  217. associated with the buffer number supplied. Always returns a valid window
  218. number or 0 meaning the current window."""
  219. # Location lists are associated with _windows_ not _buffers_. This makes a lot
  220. # of sense, but YCM associates diagnostics with _buffers_, because it is the
  221. # buffer that actually gets parsed.
  222. #
  223. # The heuristic we use is to determine any open window for a specified buffer,
  224. # and set that. If there is no such window on the current tab page, we use the
  225. # current window (by passing 0 as the window number)
  226. if buffer_number == vim.current.buffer.number:
  227. return 0
  228. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  229. if window_number < 0:
  230. return 0
  231. return window_number
  232. def SetLocationListForBuffer( buffer_number, diagnostics ):
  233. """Populate the location list of an apppropriate window for the supplied
  234. buffer number. See SetLocationListForWindow for format of diagnostics."""
  235. return SetLocationListForWindow(
  236. GetWindowNumberForBufferDiagnostics( buffer_number ),
  237. diagnostics )
  238. def SetLocationListForWindow( window_number, diagnostics ):
  239. """Populate the location list with diagnostics. Diagnostics should be in
  240. qflist format; see ":h setqflist" for details."""
  241. vim.eval( 'setloclist( {0}, {1} )'.format( window_number,
  242. json.dumps( diagnostics ) ) )
  243. def OpenLocationList( focus = False, autoclose = False ):
  244. """Open the location list to the bottom of the current window with its
  245. height automatically set to fit all entries. This behavior can be overridden
  246. by using the YcmLocationOpened autocommand. When focus is set to True, the
  247. location list window becomes the active window. When autoclose is set to True,
  248. the location list window is automatically closed after an entry is
  249. selected."""
  250. vim.command( 'lopen' )
  251. SetFittingHeightForCurrentWindow()
  252. if autoclose:
  253. # This autocommand is automatically removed when the location list window is
  254. # closed.
  255. vim.command( 'au WinLeave <buffer> q' )
  256. if VariableExists( '#User#YcmLocationOpened' ):
  257. vim.command( 'doautocmd User YcmLocationOpened' )
  258. if not focus:
  259. JumpToPreviousWindow()
  260. def SetQuickFixList( quickfix_list ):
  261. """Populate the quickfix list and open it. List should be in qflist format:
  262. see ":h setqflist" for details."""
  263. vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) )
  264. def OpenQuickFixList( focus = False, autoclose = False ):
  265. """Open the quickfix list to full width at the bottom of the screen with its
  266. height automatically set to fit all entries. This behavior can be overridden
  267. by using the YcmQuickFixOpened autocommand.
  268. See the OpenLocationList function for the focus and autoclose options."""
  269. vim.command( 'botright copen' )
  270. SetFittingHeightForCurrentWindow()
  271. if autoclose:
  272. # This autocommand is automatically removed when the quickfix window is
  273. # closed.
  274. vim.command( 'au WinLeave <buffer> q' )
  275. if VariableExists( '#User#YcmQuickFixOpened' ):
  276. vim.command( 'doautocmd User YcmQuickFixOpened' )
  277. if not focus:
  278. JumpToPreviousWindow()
  279. def SetFittingHeightForCurrentWindow():
  280. window_width = GetIntValue( 'winwidth( 0 )' )
  281. fitting_height = 0
  282. for line in vim.current.buffer:
  283. fitting_height += len( line ) // window_width + 1
  284. vim.command( '{0}wincmd _'.format( fitting_height ) )
  285. def ConvertDiagnosticsToQfList( diagnostics ):
  286. def ConvertDiagnosticToQfFormat( diagnostic ):
  287. # See :h getqflist for a description of the dictionary fields.
  288. # Note that, as usual, Vim is completely inconsistent about whether
  289. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  290. # them to be 1-based. The documentation states quite clearly that it
  291. # expects a byte offset, by which it means "1-based column number" as
  292. # described in :h getqflist ("the first column is 1").
  293. location = diagnostic[ 'location' ]
  294. line_num = location[ 'line_num' ]
  295. # libclang can give us diagnostics that point "outside" the file; Vim borks
  296. # on these.
  297. if line_num < 1:
  298. line_num = 1
  299. text = diagnostic[ 'text' ]
  300. if diagnostic.get( 'fixit_available', False ):
  301. text += ' (FixIt available)'
  302. return {
  303. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ],
  304. create_buffer_if_needed = True ),
  305. 'lnum' : line_num,
  306. 'col' : location[ 'column_num' ],
  307. 'text' : text,
  308. 'type' : diagnostic[ 'kind' ][ 0 ],
  309. 'valid' : 1
  310. }
  311. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  312. def GetVimGlobalsKeys():
  313. return vim.eval( 'keys( g: )' )
  314. def VimExpressionToPythonType( vim_expression ):
  315. """Returns a Python type from the return value of the supplied Vim expression.
  316. If the expression returns a list, dict or other non-string type, then it is
  317. returned unmodified. If the string return can be converted to an
  318. integer, returns an integer, otherwise returns the result converted to a
  319. Unicode string."""
  320. result = vim.eval( vim_expression )
  321. if not ( isinstance( result, str ) or isinstance( result, bytes ) ):
  322. return result
  323. try:
  324. return int( result )
  325. except ValueError:
  326. return ToUnicode( result )
  327. def HiddenEnabled( buffer_object ):
  328. if buffer_object.options[ 'bh' ] == "hide":
  329. return True
  330. return GetBoolValue( '&hidden' )
  331. def BufferIsUsable( buffer_object ):
  332. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  333. def EscapeFilepathForVimCommand( filepath ):
  334. to_eval = "fnameescape('{0}')".format( EscapeForVim( filepath ) )
  335. return GetVariableValue( to_eval )
  336. # Both |line| and |column| need to be 1-based
  337. def TryJumpLocationInOpenedTab( filename, line, column ):
  338. filepath = os.path.realpath( filename )
  339. for tab in vim.tabpages:
  340. for win in tab.windows:
  341. if GetBufferFilepath( win.buffer ) == filepath:
  342. vim.current.tabpage = tab
  343. vim.current.window = win
  344. vim.current.window.cursor = ( line, column - 1 )
  345. # Center the screen on the jumped-to location
  346. vim.command( 'normal! zz' )
  347. return True
  348. # 'filename' is not opened in any tab pages
  349. return False
  350. # Maps User command to vim command
  351. def GetVimCommand( user_command, default = 'edit' ):
  352. vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
  353. if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  354. vim_command = 'split'
  355. return vim_command
  356. # Both |line| and |column| need to be 1-based
  357. def JumpToLocation( filename, line, column ):
  358. # Add an entry to the jumplist
  359. vim.command( "normal! m'" )
  360. if filename != GetCurrentBufferFilepath():
  361. # We prefix the command with 'keepjumps' so that opening the file is not
  362. # recorded in the jumplist. So when we open the file and move the cursor to
  363. # a location in it, the user can use CTRL-O to jump back to the original
  364. # location, not to the start of the newly opened file.
  365. # Sadly this fails on random occasions and the undesired jump remains in the
  366. # jumplist.
  367. user_command = user_options_store.Value( 'goto_buffer_command' )
  368. if user_command == 'new-or-existing-tab':
  369. if TryJumpLocationInOpenedTab( filename, line, column ):
  370. return
  371. user_command = 'new-tab'
  372. vim_command = GetVimCommand( user_command )
  373. try:
  374. escaped_filename = EscapeFilepathForVimCommand( filename )
  375. vim.command( 'keepjumps {0} {1}'.format( vim_command, escaped_filename ) )
  376. # When the file we are trying to jump to has a swap file
  377. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  378. # or KeyboardInterrupt after user selects one of the options.
  379. except vim.error as e:
  380. if 'E325' not in str( e ):
  381. raise
  382. # Do nothing if the target file is still not opened (user chose (Q)uit)
  383. if filename != GetCurrentBufferFilepath():
  384. return
  385. # Thrown when user chooses (A)bort in .swp message box
  386. except KeyboardInterrupt:
  387. return
  388. vim.current.window.cursor = ( line, column - 1 )
  389. # Center the screen on the jumped-to location
  390. vim.command( 'normal! zz' )
  391. def NumLinesInBuffer( buffer_object ):
  392. # This is actually less than obvious, that's why it's wrapped in a function
  393. return len( buffer_object )
  394. # Calling this function from the non-GUI thread will sometimes crash Vim. At
  395. # the time of writing, YCM only uses the GUI thread inside Vim (this used to
  396. # not be the case).
  397. def PostVimMessage( message, warning = True, truncate = False ):
  398. """Display a message on the Vim status line. By default, the message is
  399. highlighted and logged to Vim command-line history (see :h history).
  400. Unset the |warning| parameter to disable this behavior. Set the |truncate|
  401. parameter to avoid hit-enter prompts (see :h hit-enter) when the message is
  402. longer than the window width."""
  403. echo_command = 'echom' if warning else 'echo'
  404. # Displaying a new message while previous ones are still on the status line
  405. # might lead to a hit-enter prompt or the message appearing without a
  406. # newline so we do a redraw first.
  407. vim.command( 'redraw' )
  408. if warning:
  409. vim.command( 'echohl WarningMsg' )
  410. message = ToUnicode( message )
  411. if truncate:
  412. vim_width = GetIntValue( '&columns' )
  413. message = message.replace( '\n', ' ' )
  414. if len( message ) >= vim_width:
  415. message = message[ : vim_width - 4 ] + '...'
  416. old_ruler = GetIntValue( '&ruler' )
  417. old_showcmd = GetIntValue( '&showcmd' )
  418. vim.command( 'set noruler noshowcmd' )
  419. vim.command( "{0} '{1}'".format( echo_command,
  420. EscapeForVim( message ) ) )
  421. SetVariableValue( '&ruler', old_ruler )
  422. SetVariableValue( '&showcmd', old_showcmd )
  423. else:
  424. for line in message.split( '\n' ):
  425. vim.command( "{0} '{1}'".format( echo_command,
  426. EscapeForVim( line ) ) )
  427. if warning:
  428. vim.command( 'echohl None' )
  429. def PresentDialog( message, choices, default_choice_index = 0 ):
  430. """Presents the user with a dialog where a choice can be made.
  431. This will be a dialog for gvim users or a question in the message buffer
  432. for vim users or if `set guioptions+=c` was used.
  433. choices is list of alternatives.
  434. default_choice_index is the 0-based index of the default element
  435. that will get choosen if the user hits <CR>. Use -1 for no default.
  436. PresentDialog will return a 0-based index into the list
  437. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  438. If you are presenting a list of options for the user to choose from, such as
  439. a list of imports, or lines to insert (etc.), SelectFromList is a better
  440. option.
  441. See also:
  442. :help confirm() in vim (Note that vim uses 1-based indexes)
  443. Example call:
  444. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  445. Is this a nice example?
  446. [Y]es, (N)o, May(b)e:"""
  447. to_eval = "confirm('{0}', '{1}', {2})".format(
  448. EscapeForVim( ToUnicode( message ) ),
  449. EscapeForVim( ToUnicode( "\n" .join( choices ) ) ),
  450. default_choice_index + 1 )
  451. try:
  452. return GetIntValue( to_eval ) - 1
  453. except KeyboardInterrupt:
  454. return -1
  455. def Confirm( message ):
  456. """Display |message| with Ok/Cancel operations. Returns True if the user
  457. selects Ok"""
  458. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  459. def SelectFromList( prompt, items ):
  460. """Ask the user to select an item from the list |items|.
  461. Presents the user with |prompt| followed by a numbered list of |items|,
  462. from which they select one. The user is asked to enter the number of an
  463. item or click it.
  464. |items| should not contain leading ordinals: they are added automatically.
  465. Returns the 0-based index in the list |items| that the user selected, or an
  466. exception if no valid item was selected.
  467. See also :help inputlist()."""
  468. vim_items = [ prompt ]
  469. vim_items.extend( [ "{0}: {1}".format( i + 1, item )
  470. for i, item in enumerate( items ) ] )
  471. # The vim documentation warns not to present lists larger than the number of
  472. # lines of display. This is sound advice, but there really isn't any sensible
  473. # thing we can do in that scenario. Testing shows that Vim just pages the
  474. # message; that behaviour is as good as any, so we don't manipulate the list,
  475. # or attempt to page it.
  476. # For an explanation of the purpose of inputsave() / inputrestore(),
  477. # see :help input(). Briefly, it makes inputlist() work as part of a mapping.
  478. vim.eval( 'inputsave()' )
  479. try:
  480. # Vim returns the number the user entered, or the line number the user
  481. # clicked. This may be wildly out of range for our list. It might even be
  482. # negative.
  483. #
  484. # The first item is index 0, and this maps to our "prompt", so we subtract 1
  485. # from the result and return that, assuming it is within the range of the
  486. # supplied list. If not, we return negative.
  487. #
  488. # See :help input() for explanation of the use of inputsave() and inpput
  489. # restore(). It is done in try/finally in case vim.eval ever throws an
  490. # exception (such as KeyboardInterrupt)
  491. selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1
  492. except KeyboardInterrupt:
  493. selected = -1
  494. finally:
  495. vim.eval( 'inputrestore()' )
  496. if selected < 0 or selected >= len( items ):
  497. # User selected something outside of the range
  498. raise RuntimeError( NO_SELECTION_MADE_MSG )
  499. return selected
  500. def EscapeForVim( text ):
  501. return ToUnicode( text.replace( "'", "''" ) )
  502. def CurrentFiletypes():
  503. return ToUnicode( vim.eval( "&filetype" ) ).split( '.' )
  504. def CurrentFiletypesEnabled( disabled_filetypes ):
  505. """Return False if one of the current filetypes is disabled, True otherwise.
  506. |disabled_filetypes| must be a dictionary where keys are the disabled
  507. filetypes and values are unimportant. The special key '*' matches all
  508. filetypes."""
  509. return ( '*' not in disabled_filetypes and
  510. not any( x in disabled_filetypes for x in CurrentFiletypes() ) )
  511. def GetBufferFiletypes( bufnr ):
  512. command = 'getbufvar({0}, "&ft")'.format( bufnr )
  513. return ToUnicode( vim.eval( command ) ).split( '.' )
  514. def FiletypesForBuffer( buffer_object ):
  515. # NOTE: Getting &ft for other buffers only works when the buffer has been
  516. # visited by the user at least once, which is true for modified buffers
  517. # We don't use
  518. #
  519. # buffer_object.options[ 'ft' ]
  520. #
  521. # to get the filetypes because this causes annoying flickering when the buffer
  522. # is hidden.
  523. return GetBufferFiletypes( buffer_object.number )
  524. def VariableExists( variable ):
  525. return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
  526. def SetVariableValue( variable, value ):
  527. vim.command( "let {0} = {1}".format( variable, json.dumps( value ) ) )
  528. def GetVariableValue( variable ):
  529. return vim.eval( variable )
  530. def GetBoolValue( variable ):
  531. return bool( int( vim.eval( variable ) ) )
  532. def GetIntValue( variable ):
  533. return int( vim.eval( variable ) )
  534. def _SortChunksByFile( chunks ):
  535. """Sort the members of the list |chunks| (which must be a list of dictionaries
  536. conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new
  537. list in arbitrary order."""
  538. chunks_by_file = defaultdict( list )
  539. for chunk in chunks:
  540. filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ]
  541. chunks_by_file[ filepath ].append( chunk )
  542. return chunks_by_file
  543. def _GetNumNonVisibleFiles( file_list ):
  544. """Returns the number of file in the iterable list of files |file_list| which
  545. are not curerntly open in visible windows"""
  546. return len(
  547. [ f for f in file_list
  548. if not BufferIsVisible( GetBufferNumberForFilename( f ) ) ] )
  549. def _OpenFileInSplitIfNeeded( filepath ):
  550. """Ensure that the supplied filepath is open in a visible window, opening a
  551. new split if required. Returns the buffer number of the file and an indication
  552. of whether or not a new split was opened.
  553. If the supplied filename is already open in a visible window, return just
  554. return its buffer number. If the supplied file is not visible in a window
  555. in the current tab, opens it in a new vertical split.
  556. Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer
  557. number and whether or not this method created a new split. If the user opts
  558. not to open a file, or if opening fails, this method raises RuntimeError,
  559. otherwise, guarantees to return a visible buffer number in buffer_num."""
  560. buffer_num = GetBufferNumberForFilename( filepath )
  561. # We only apply changes in the current tab page (i.e. "visible" windows).
  562. # Applying changes in tabs does not lead to a better user experience, as the
  563. # quickfix list no longer works as you might expect (doesn't jump into other
  564. # tabs), and the complexity of choosing where to apply edits is significant.
  565. if BufferIsVisible( buffer_num ):
  566. # file is already open and visible, just return that buffer number (and an
  567. # idicator that we *didn't* open a split)
  568. return ( buffer_num, False )
  569. # The file is not open in a visible window, so we open it in a split.
  570. # We open the file with a small, fixed height. This means that we don't
  571. # make the current buffer the smallest after a series of splits.
  572. OpenFilename( filepath, {
  573. 'focus': True,
  574. 'fix': True,
  575. 'size': GetIntValue( '&previewheight' ),
  576. } )
  577. # OpenFilename returns us to the original cursor location. This is what we
  578. # want, because we don't want to disorientate the user, but we do need to
  579. # know the (now open) buffer number for the filename
  580. buffer_num = GetBufferNumberForFilename( filepath )
  581. if not BufferIsVisible( buffer_num ):
  582. # This happens, for example, if there is a swap file and the user
  583. # selects the "Quit" or "Abort" options. We just raise an exception to
  584. # make it clear to the user that the abort has left potentially
  585. # partially-applied changes.
  586. raise RuntimeError(
  587. 'Unable to open file: {0}\nFixIt/Refactor operation '
  588. 'aborted prior to completion. Your files have not been '
  589. 'fully updated. Please use undo commands to revert the '
  590. 'applied changes.'.format( filepath ) )
  591. # We opened this file in a split
  592. return ( buffer_num, True )
  593. def ReplaceChunks( chunks, silent=False ):
  594. """Apply the source file deltas supplied in |chunks| to arbitrary files.
  595. |chunks| is a list of changes defined by ycmd.responses.FixItChunk,
  596. which may apply arbitrary modifications to arbitrary files.
  597. If a file specified in a particular chunk is not currently open in a visible
  598. buffer (i.e., one in a window visible in the current tab), we:
  599. - issue a warning to the user that we're going to open new files (and offer
  600. her the option to abort cleanly)
  601. - open the file in a new split, make the changes, then hide the buffer.
  602. If for some reason a file could not be opened or changed, raises RuntimeError.
  603. Otherwise, returns no meaningful value."""
  604. # We apply the edits file-wise for efficiency.
  605. chunks_by_file = _SortChunksByFile( chunks )
  606. # We sort the file list simply to enable repeatable testing.
  607. sorted_file_list = sorted( iterkeys( chunks_by_file ) )
  608. if not silent:
  609. # Make sure the user is prepared to have her screen mutilated by the new
  610. # buffers.
  611. num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list )
  612. if num_files_to_open > 0:
  613. if not Confirm(
  614. FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ):
  615. return
  616. # Store the list of locations where we applied changes. We use this to display
  617. # the quickfix window showing the user where we applied changes.
  618. locations = []
  619. for filepath in sorted_file_list:
  620. buffer_num, close_window = _OpenFileInSplitIfNeeded( filepath )
  621. locations.extend( ReplaceChunksInBuffer( chunks_by_file[ filepath ],
  622. vim.buffers[ buffer_num ] ) )
  623. # When opening tons of files, we don't want to have a split for each new
  624. # file, as this simply does not scale, so we open the window, make the
  625. # edits, then hide the window.
  626. if close_window:
  627. # Some plugins (I'm looking at you, syntastic) might open a location list
  628. # for the window we just opened. We don't want that location list hanging
  629. # around, so we close it. lclose is a no-op if there is no location list.
  630. vim.command( 'lclose' )
  631. # Note that this doesn't lose our changes. It simply "hides" the buffer,
  632. # which can later be re-accessed via the quickfix list or `:ls`
  633. vim.command( 'hide' )
  634. # Open the quickfix list, populated with entries for each location we changed.
  635. if not silent:
  636. if locations:
  637. SetQuickFixList( locations )
  638. PostVimMessage( 'Applied {0} changes'.format( len( chunks ) ),
  639. warning = False )
  640. def ReplaceChunksInBuffer( chunks, vim_buffer ):
  641. """Apply changes in |chunks| to the buffer-like object |buffer| and return the
  642. locations for that buffer."""
  643. # We apply the chunks from the bottom to the top of the buffer so that we
  644. # don't need to adjust the position of the remaining chunks due to text
  645. # changes. This assumes that chunks are not overlapping. However, we still
  646. # allow multiple chunks to share the same starting position (because of the
  647. # language server protocol specs). These chunks must be applied in their order
  648. # of appareance. Since Python sorting is stable, if we sort the whole list in
  649. # reverse order of location, these chunks will be reversed. Therefore, we
  650. # need to fully reverse the list then sort it on the starting position in
  651. # reverse order.
  652. chunks.reverse()
  653. chunks.sort( key = lambda chunk: (
  654. chunk[ 'range' ][ 'start' ][ 'line_num' ],
  655. chunk[ 'range' ][ 'start' ][ 'column_num' ]
  656. ), reverse = True )
  657. # However, we still want to display the locations from the top of the buffer
  658. # to its bottom.
  659. return reversed( [ ReplaceChunk( chunk[ 'range' ][ 'start' ],
  660. chunk[ 'range' ][ 'end' ],
  661. chunk[ 'replacement_text' ],
  662. vim_buffer )
  663. for chunk in chunks ] )
  664. def SplitLines( contents ):
  665. """Return a list of each of the lines in the byte string |contents|.
  666. Behavior is equivalent to str.splitlines with the following exceptions:
  667. - empty strings are returned as [ '' ];
  668. - a trailing newline is not ignored (i.e. SplitLines( '\n' )
  669. returns [ '', '' ], not [ '' ] )."""
  670. if contents == b'':
  671. return [ b'' ]
  672. lines = contents.splitlines()
  673. if contents.endswith( b'\r' ) or contents.endswith( b'\n' ):
  674. lines.append( b'' )
  675. return lines
  676. # Replace the chunk of text specified by a contiguous range with the supplied
  677. # text and return the location.
  678. # * start and end are objects with line_num and column_num properties
  679. # * the range is inclusive
  680. # * indices are all 1-based
  681. #
  682. # NOTE: Works exclusively with bytes() instances and byte offsets as returned
  683. # by ycmd and used within the Vim buffers
  684. def ReplaceChunk( start, end, replacement_text, vim_buffer ):
  685. # ycmd's results are all 1-based, but vim's/python's are all 0-based
  686. # (so we do -1 on all of the values)
  687. start_line = start[ 'line_num' ] - 1
  688. end_line = end[ 'line_num' ] - 1
  689. start_column = start[ 'column_num' ] - 1
  690. end_column = end[ 'column_num' ] - 1
  691. # When sending a request to the server, a newline is added to the buffer
  692. # contents to match what gets saved to disk. If the server generates a chunk
  693. # containing that newline, this chunk goes past the Vim buffer contents since
  694. # there is actually no new line. When this happens, recompute the end position
  695. # of where the chunk is applied and remove all trailing characters in the
  696. # chunk.
  697. if end_line >= len( vim_buffer ):
  698. end_column = len( ToBytes( vim_buffer[ -1 ] ) )
  699. end_line = len( vim_buffer ) - 1
  700. replacement_text = replacement_text.rstrip()
  701. # NOTE: replacement_text is unicode, but all our offsets are byte offsets,
  702. # so we convert to bytes
  703. replacement_lines = SplitLines( ToBytes( replacement_text ) )
  704. # NOTE: Vim buffers are a list of byte objects on Python 2 but unicode
  705. # objects on Python 3.
  706. start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ]
  707. end_existing_text = ToBytes( vim_buffer[ end_line ] )[ end_column : ]
  708. replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  709. replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
  710. vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
  711. return {
  712. 'bufnr': vim_buffer.number,
  713. 'filename': vim_buffer.name,
  714. # line and column numbers are 1-based in qflist
  715. 'lnum': start_line + 1,
  716. 'col': start_column + 1,
  717. 'text': replacement_text,
  718. 'type': 'F',
  719. }
  720. def InsertNamespace( namespace ):
  721. if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
  722. expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
  723. if expr:
  724. SetVariableValue( "g:ycm_namespace_to_insert", namespace )
  725. vim.eval( expr )
  726. return
  727. pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  728. existing_indent = ''
  729. line = SearchInCurrentBuffer( pattern )
  730. if line:
  731. existing_line = LineTextInCurrentBuffer( line )
  732. existing_indent = re.sub( r"\S.*", "", existing_line )
  733. new_line = "{0}using {1};\n".format( existing_indent, namespace )
  734. replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  735. ReplaceChunk( replace_pos, replace_pos, new_line, vim.current.buffer )
  736. PostVimMessage( 'Add namespace: {0}'.format( namespace ), warning = False )
  737. def SearchInCurrentBuffer( pattern ):
  738. """ Returns the 1-indexed line on which the pattern matches
  739. (going UP from the current position) or 0 if not found """
  740. return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
  741. def LineTextInCurrentBuffer( line_number ):
  742. """ Returns the text on the 1-indexed line (NOT 0-indexed) """
  743. return vim.current.buffer[ line_number - 1 ]
  744. def ClosePreviewWindow():
  745. """ Close the preview window if it is present, otherwise do nothing """
  746. vim.command( 'silent! pclose!' )
  747. def JumpToPreviewWindow():
  748. """ Jump the vim cursor to the preview window, which must be active. Returns
  749. boolean indicating if the cursor ended up in the preview window """
  750. vim.command( 'silent! wincmd P' )
  751. return vim.current.window.options[ 'previewwindow' ]
  752. def JumpToPreviousWindow():
  753. """ Jump the vim cursor to its previous window position """
  754. vim.command( 'silent! wincmd p' )
  755. def JumpToTab( tab_number ):
  756. """Jump to Vim tab with corresponding number """
  757. vim.command( 'silent! tabn {0}'.format( tab_number ) )
  758. def OpenFileInPreviewWindow( filename ):
  759. """ Open the supplied filename in the preview window """
  760. vim.command( 'silent! pedit! ' + filename )
  761. def WriteToPreviewWindow( message ):
  762. """ Display the supplied message in the preview window """
  763. # This isn't something that comes naturally to Vim. Vim only wants to show
  764. # tags and/or actual files in the preview window, so we have to hack it a
  765. # little bit. We generate a temporary file name and "open" that, then write
  766. # the data to it. We make sure the buffer can't be edited or saved. Other
  767. # approaches include simply opening a split, but we want to take advantage of
  768. # the existing Vim options for preview window height, etc.
  769. ClosePreviewWindow()
  770. OpenFileInPreviewWindow( vim.eval( 'tempname()' ) )
  771. if JumpToPreviewWindow():
  772. # We actually got to the preview window. By default the preview window can't
  773. # be changed, so we make it writable, write to it, then make it read only
  774. # again.
  775. vim.current.buffer.options[ 'modifiable' ] = True
  776. vim.current.buffer.options[ 'readonly' ] = False
  777. vim.current.buffer[:] = message.splitlines()
  778. vim.current.buffer.options[ 'buftype' ] = 'nofile'
  779. vim.current.buffer.options[ 'bufhidden' ] = 'wipe'
  780. vim.current.buffer.options[ 'buflisted' ] = False
  781. vim.current.buffer.options[ 'swapfile' ] = False
  782. vim.current.buffer.options[ 'modifiable' ] = False
  783. vim.current.buffer.options[ 'readonly' ] = True
  784. # We need to prevent closing the window causing a warning about unsaved
  785. # file, so we pretend to Vim that the buffer has not been changed.
  786. vim.current.buffer.options[ 'modified' ] = False
  787. JumpToPreviousWindow()
  788. else:
  789. # We couldn't get to the preview window, but we still want to give the user
  790. # the information we have. The only remaining option is to echo to the
  791. # status area.
  792. PostVimMessage( message, warning = False )
  793. def BufferIsVisibleForFilename( filename ):
  794. """Check if a buffer exists for a specific file."""
  795. buffer_number = GetBufferNumberForFilename( filename )
  796. return BufferIsVisible( buffer_number )
  797. def CloseBuffersForFilename( filename ):
  798. """Close all buffers for a specific file."""
  799. buffer_number = GetBufferNumberForFilename( filename )
  800. while buffer_number != -1:
  801. vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) )
  802. new_buffer_number = GetBufferNumberForFilename( filename )
  803. if buffer_number == new_buffer_number:
  804. raise RuntimeError( "Buffer {0} for filename '{1}' should already be "
  805. "wiped out.".format( buffer_number, filename ) )
  806. buffer_number = new_buffer_number
  807. def OpenFilename( filename, options = {} ):
  808. """Open a file in Vim. Following options are available:
  809. - command: specify which Vim command is used to open the file. Choices
  810. are same-buffer, horizontal-split, vertical-split, and new-tab (default:
  811. horizontal-split);
  812. - size: set the height of the window for a horizontal split or the width for
  813. a vertical one (default: '');
  814. - fix: set the winfixheight option for a horizontal split or winfixwidth for
  815. a vertical one (default: False). See :h winfix for details;
  816. - focus: focus the opened file (default: False);
  817. - watch: automatically watch for changes (default: False). This is useful
  818. for logs;
  819. - position: set the position where the file is opened (default: start).
  820. Choices are start and end."""
  821. # Set the options.
  822. command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
  823. 'horizontal-split' )
  824. size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
  825. '' )
  826. focus = options.get( 'focus', False )
  827. # There is no command in Vim to return to the previous tab so we need to
  828. # remember the current tab if needed.
  829. if not focus and command == 'tabedit':
  830. previous_tab = GetIntValue( 'tabpagenr()' )
  831. else:
  832. previous_tab = None
  833. # Open the file.
  834. try:
  835. vim.command( '{0}{1} {2}'.format( size, command, filename ) )
  836. # When the file we are trying to jump to has a swap file,
  837. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  838. # or KeyboardInterrupt after user selects one of the options which actually
  839. # opens the file (Open read-only/Edit anyway).
  840. except vim.error as e:
  841. if 'E325' not in str( e ):
  842. raise
  843. # Otherwise, the user might have chosen Quit. This is detectable by the
  844. # current file not being the target file
  845. if filename != GetCurrentBufferFilepath():
  846. return
  847. except KeyboardInterrupt:
  848. # Raised when the user selects "Abort" after swap-exists-choices
  849. return
  850. _SetUpLoadedBuffer( command,
  851. filename,
  852. options.get( 'fix', False ),
  853. options.get( 'position', 'start' ),
  854. options.get( 'watch', False ) )
  855. # Vim automatically set the focus to the opened file so we need to get the
  856. # focus back (if the focus option is disabled) when opening a new tab or
  857. # window.
  858. if not focus:
  859. if command == 'tabedit':
  860. JumpToTab( previous_tab )
  861. if command in [ 'split', 'vsplit' ]:
  862. JumpToPreviousWindow()
  863. def _SetUpLoadedBuffer( command, filename, fix, position, watch ):
  864. """After opening a buffer, configure it according to the supplied options,
  865. which are as defined by the OpenFilename method."""
  866. if command == 'split':
  867. vim.current.window.options[ 'winfixheight' ] = fix
  868. if command == 'vsplit':
  869. vim.current.window.options[ 'winfixwidth' ] = fix
  870. if watch:
  871. vim.current.buffer.options[ 'autoread' ] = True
  872. vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
  873. .format( filename ) )
  874. if position == 'end':
  875. vim.command( 'silent! normal! Gzz' )
  876. def BuildRange( start_line, end_line ):
  877. # Vim only returns the starting and ending lines of the range of a command.
  878. # Check if those lines correspond to a previous visual selection and if they
  879. # do, use the columns of that selection to build the range.
  880. start = vim.current.buffer.mark( '<' )
  881. end = vim.current.buffer.mark( '>' )
  882. if not start or not end or start_line != start[ 0 ] or end_line != end[ 0 ]:
  883. start = [ start_line, 0 ]
  884. end = [ end_line, len( vim.current.buffer[ end_line - 1 ] ) ]
  885. # Vim Python API returns 1-based lines and 0-based columns while ycmd expects
  886. # 1-based lines and columns.
  887. return {
  888. 'range': {
  889. 'start': {
  890. 'line_num': start[ 0 ],
  891. 'column_num': start[ 1 ] + 1
  892. },
  893. 'end': {
  894. 'line_num': end[ 0 ],
  895. # Vim returns the maximum 32-bit integer value when a whole line is
  896. # selected. Use the end of line instead.
  897. 'column_num': min( end[ 1 ],
  898. len( vim.current.buffer[ end[ 0 ] - 1 ] ) ) + 1
  899. }
  900. }
  901. }