vimsupport.py 41 KB

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