vimsupport.py 42 KB

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