1
0

vimsupport.py 38 KB

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