vimsupport.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2011, 2012 Google Inc.
  4. #
  5. # This file is part of YouCompleteMe.
  6. #
  7. # YouCompleteMe is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # YouCompleteMe is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  19. import vim
  20. import os
  21. import tempfile
  22. import json
  23. import re
  24. from ycmd.utils import ToUtf8IfNeeded
  25. from ycmd import user_options_store
  26. BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
  27. 'horizontal-split' : 'split',
  28. 'vertical-split' : 'vsplit',
  29. 'new-tab' : 'tabedit' }
  30. def CurrentLineAndColumn():
  31. """Returns the 0-based current line and 0-based current column."""
  32. # See the comment in CurrentColumn about the calculation for the line and
  33. # column number
  34. line, column = vim.current.window.cursor
  35. line -= 1
  36. return line, column
  37. def CurrentColumn():
  38. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  39. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  40. line. Only the chars before the current column exist in vim.current.line."""
  41. # vim's columns are 1-based while vim.current.line columns are 0-based
  42. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  43. # columns are 0-based, while the line from that same tuple is 1-based.
  44. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  45. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  46. return vim.current.window.cursor[ 1 ]
  47. def CurrentLineContents():
  48. return vim.current.line
  49. def TextAfterCursor():
  50. """Returns the text after CurrentColumn."""
  51. return vim.current.line[ CurrentColumn(): ]
  52. def TextBeforeCursor():
  53. """Returns the text before CurrentColumn."""
  54. return vim.current.line[ :CurrentColumn() ]
  55. # Expects version_string in 'MAJOR.MINOR.PATCH' format, e.g. '7.4.301'
  56. def VimVersionAtLeast( version_string ):
  57. major, minor, patch = [ int( x ) for x in version_string.split( '.' ) ]
  58. # For Vim 7.4.301, v:version is '704'
  59. actual_major_and_minor = GetIntValue( 'v:version' )
  60. matching_major_and_minor = major * 100 + minor
  61. if actual_major_and_minor != matching_major_and_minor:
  62. return actual_major_and_minor > matching_major_and_minor
  63. return GetBoolValue( 'has("patch{0}")'.format( patch ) )
  64. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  65. # the same.
  66. def GetBufferOption( buffer_object, option ):
  67. # NOTE: We used to check for the 'options' property on the buffer_object which
  68. # is available in recent versions of Vim and would then use:
  69. #
  70. # buffer_object.options[ option ]
  71. #
  72. # to read the value, BUT this caused annoying flickering when the
  73. # buffer_object was a hidden buffer (with option = 'ft'). This was all due to
  74. # a Vim bug. Until this is fixed, we won't use it.
  75. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  76. return GetVariableValue( to_eval )
  77. def BufferModified( buffer_object ):
  78. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  79. def GetUnsavedAndCurrentBufferData():
  80. buffers_data = {}
  81. for buffer_object in vim.buffers:
  82. if not ( BufferModified( buffer_object ) or
  83. buffer_object == vim.current.buffer ):
  84. continue
  85. buffers_data[ GetBufferFilepath( buffer_object ) ] = {
  86. # Add a newline to match what gets saved to disk. See #1455 for details.
  87. 'contents': '\n'.join( buffer_object ) + '\n',
  88. 'filetypes': FiletypesForBuffer( buffer_object )
  89. }
  90. return buffers_data
  91. def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
  92. return GetIntValue( u"bufnr('{0}', {1})".format(
  93. EscapeForVim( os.path.realpath( filename ) ),
  94. int( open_file_if_needed ) ) )
  95. def GetCurrentBufferFilepath():
  96. return GetBufferFilepath( vim.current.buffer )
  97. def BufferIsVisible( buffer_number ):
  98. if buffer_number < 0:
  99. return False
  100. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  101. return window_number != -1
  102. def GetBufferFilepath( buffer_object ):
  103. if buffer_object.name:
  104. return buffer_object.name
  105. # Buffers that have just been created by a command like :enew don't have any
  106. # buffer name so we use the buffer number for that. Also, os.getcwd() throws
  107. # an exception when the CWD has been deleted so we handle that.
  108. try:
  109. folder_path = os.getcwd()
  110. except OSError:
  111. folder_path = tempfile.gettempdir()
  112. return os.path.join( folder_path, str( buffer_object.number ) )
  113. def UnplaceSignInBuffer( buffer_number, sign_id ):
  114. if buffer_number < 0:
  115. return
  116. vim.command(
  117. 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format(
  118. sign_id, buffer_number ) )
  119. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  120. # libclang can give us diagnostics that point "outside" the file; Vim borks
  121. # on these.
  122. if line_num < 1:
  123. line_num = 1
  124. sign_name = 'YcmError' if is_error else 'YcmWarning'
  125. vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format(
  126. sign_id, line_num, sign_name, buffer_num ) )
  127. def PlaceDummySign( sign_id, buffer_num, line_num ):
  128. if buffer_num < 0 or line_num < 0:
  129. return
  130. vim.command( 'sign define ycm_dummy_sign' )
  131. vim.command(
  132. 'sign place {0} name=ycm_dummy_sign line={1} buffer={2}'.format(
  133. sign_id,
  134. line_num,
  135. buffer_num,
  136. )
  137. )
  138. def UnPlaceDummySign( sign_id, buffer_num ):
  139. if buffer_num < 0:
  140. return
  141. vim.command( 'sign undefine ycm_dummy_sign' )
  142. vim.command( 'sign unplace {0} buffer={1}'.format( sign_id, buffer_num ) )
  143. def ClearYcmSyntaxMatches():
  144. matches = VimExpressionToPythonType( 'getmatches()' )
  145. for match in matches:
  146. if match[ 'group' ].startswith( 'Ycm' ):
  147. vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
  148. # Returns the ID of the newly added match
  149. # Both line and column numbers are 1-based
  150. def AddDiagnosticSyntaxMatch( line_num,
  151. column_num,
  152. line_end_num = None,
  153. column_end_num = None,
  154. is_error = True ):
  155. group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
  156. if not line_end_num:
  157. line_end_num = line_num
  158. line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
  159. line_end_num, column_end_num = LineAndColumnNumbersClamped( line_end_num,
  160. column_end_num )
  161. if not column_end_num:
  162. return GetIntValue(
  163. "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
  164. else:
  165. return GetIntValue(
  166. "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format(
  167. group, line_num, column_num, line_end_num, column_end_num ) )
  168. # Clamps the line and column numbers so that they are not past the contents of
  169. # the buffer. Numbers are 1-based.
  170. def LineAndColumnNumbersClamped( line_num, column_num ):
  171. new_line_num = line_num
  172. new_column_num = column_num
  173. max_line = len( vim.current.buffer )
  174. if line_num and line_num > max_line:
  175. new_line_num = max_line
  176. max_column = len( vim.current.buffer[ new_line_num - 1 ] )
  177. if column_num and column_num > max_column:
  178. new_column_num = max_column
  179. return new_line_num, new_column_num
  180. def SetLocationList( diagnostics ):
  181. """Diagnostics should be in qflist format; see ":h setqflist" for details."""
  182. vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
  183. def ConvertDiagnosticsToQfList( diagnostics ):
  184. def ConvertDiagnosticToQfFormat( diagnostic ):
  185. # See :h getqflist for a description of the dictionary fields.
  186. # Note that, as usual, Vim is completely inconsistent about whether
  187. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  188. # them to be 1-based. The documentation states quite clearly that it
  189. # expects a byte offset, by which it means "1-based column number" as
  190. # described in :h getqflist ("the first column is 1").
  191. location = diagnostic[ 'location' ]
  192. line_num = location[ 'line_num' ]
  193. # libclang can give us diagnostics that point "outside" the file; Vim borks
  194. # on these.
  195. if line_num < 1:
  196. line_num = 1
  197. text = diagnostic[ 'text' ]
  198. if diagnostic.get( 'fixit_available', False ):
  199. text += ' (FixIt available)'
  200. return {
  201. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  202. 'lnum' : line_num,
  203. 'col' : location[ 'column_num' ],
  204. 'text' : ToUtf8IfNeeded( text ),
  205. 'type' : diagnostic[ 'kind' ][ 0 ],
  206. 'valid' : 1
  207. }
  208. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  209. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  210. # When |overwrite| is True, overwrites the existing value in Vim.
  211. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  212. extend_option = '"force"' if overwrite else '"keep"'
  213. # We need to use json.dumps because that won't use the 'u' prefix on strings
  214. # which Vim would bork on.
  215. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  216. extend_option ) )
  217. # Changing the returned dict will NOT change the value in Vim.
  218. def GetReadOnlyVimGlobals( force_python_objects = False ):
  219. if force_python_objects:
  220. return vim.eval( 'g:' )
  221. try:
  222. # vim.vars is fairly new so it might not exist
  223. return vim.vars
  224. except:
  225. return vim.eval( 'g:' )
  226. def VimExpressionToPythonType( vim_expression ):
  227. result = vim.eval( vim_expression )
  228. if not isinstance( result, basestring ):
  229. return result
  230. try:
  231. return int( result )
  232. except ValueError:
  233. return result
  234. def HiddenEnabled( buffer_object ):
  235. return bool( int( GetBufferOption( buffer_object, 'hid' ) ) )
  236. def BufferIsUsable( buffer_object ):
  237. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  238. def EscapedFilepath( filepath ):
  239. return filepath.replace( ' ' , r'\ ' )
  240. # Both |line| and |column| need to be 1-based
  241. def TryJumpLocationInOpenedTab( filename, line, column ):
  242. filepath = os.path.realpath( filename )
  243. for tab in vim.tabpages:
  244. for win in tab.windows:
  245. if win.buffer.name == filepath:
  246. vim.current.tabpage = tab
  247. vim.current.window = win
  248. vim.current.window.cursor = ( line, column - 1 )
  249. # Center the screen on the jumped-to location
  250. vim.command( 'normal! zz' )
  251. return True
  252. # 'filename' is not opened in any tab pages
  253. return False
  254. # Maps User command to vim command
  255. def GetVimCommand( user_command, default = 'edit' ):
  256. vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
  257. if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  258. vim_command = 'split'
  259. return vim_command
  260. # Both |line| and |column| need to be 1-based
  261. def JumpToLocation( filename, line, column ):
  262. # Add an entry to the jumplist
  263. vim.command( "normal! m'" )
  264. if filename != GetCurrentBufferFilepath():
  265. # We prefix the command with 'keepjumps' so that opening the file is not
  266. # recorded in the jumplist. So when we open the file and move the cursor to
  267. # a location in it, the user can use CTRL-O to jump back to the original
  268. # location, not to the start of the newly opened file.
  269. # Sadly this fails on random occasions and the undesired jump remains in the
  270. # jumplist.
  271. user_command = user_options_store.Value( 'goto_buffer_command' )
  272. if user_command == 'new-or-existing-tab':
  273. if TryJumpLocationInOpenedTab( filename, line, column ):
  274. return
  275. user_command = 'new-tab'
  276. vim_command = GetVimCommand( user_command )
  277. try:
  278. vim.command( 'keepjumps {0} {1}'.format( vim_command,
  279. EscapedFilepath( filename ) ) )
  280. # When the file we are trying to jump to has a swap file
  281. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  282. # or KeyboardInterrupt after user selects one of the options.
  283. except vim.error as e:
  284. if 'E325' not in str( e ):
  285. raise
  286. # Do nothing if the target file is still not opened (user chose (Q)uit)
  287. if filename != GetCurrentBufferFilepath():
  288. return
  289. # Thrown when user chooses (A)bort in .swp message box
  290. except KeyboardInterrupt:
  291. return
  292. vim.current.window.cursor = ( line, column - 1 )
  293. # Center the screen on the jumped-to location
  294. vim.command( 'normal! zz' )
  295. def NumLinesInBuffer( buffer_object ):
  296. # This is actually less than obvious, that's why it's wrapped in a function
  297. return len( buffer_object )
  298. # Calling this function from the non-GUI thread will sometimes crash Vim. At
  299. # the time of writing, YCM only uses the GUI thread inside Vim (this used to
  300. # not be the case).
  301. # We redraw the screen before displaying the message to avoid the "Press ENTER
  302. # or type command to continue" prompt when editing a new C-family file.
  303. def PostVimMessage( message ):
  304. vim.command( "redraw | echohl WarningMsg | echom '{0}' | echohl None"
  305. .format( EscapeForVim( str( message ) ) ) )
  306. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  307. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  308. # appear in Vim's message log.
  309. def PostMultiLineNotice( message ):
  310. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  311. .format( EscapeForVim( str( message ) ) ) )
  312. def PresentDialog( message, choices, default_choice_index = 0 ):
  313. """Presents the user with a dialog where a choice can be made.
  314. This will be a dialog for gvim users or a question in the message buffer
  315. for vim users or if `set guioptions+=c` was used.
  316. choices is list of alternatives.
  317. default_choice_index is the 0-based index of the default element
  318. that will get choosen if the user hits <CR>. Use -1 for no default.
  319. PresentDialog will return a 0-based index into the list
  320. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  321. See also:
  322. :help confirm() in vim (Note that vim uses 1-based indexes)
  323. Example call:
  324. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  325. Is this a nice example?
  326. [Y]es, (N)o, May(b)e:"""
  327. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  328. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  329. return int( vim.eval( to_eval ) ) - 1
  330. def Confirm( message ):
  331. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  332. def EchoText( text, log_as_message = True ):
  333. def EchoLine( text ):
  334. command = 'echom' if log_as_message else 'echo'
  335. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  336. for line in str( text ).split( '\n' ):
  337. EchoLine( line )
  338. # Echos text but truncates it so that it all fits on one line
  339. def EchoTextVimWidth( text ):
  340. vim_width = GetIntValue( '&columns' )
  341. truncated_text = ToUtf8IfNeeded( text )[ : int( vim_width * 0.9 ) ]
  342. truncated_text.replace( '\n', ' ' )
  343. old_ruler = GetIntValue( '&ruler' )
  344. old_showcmd = GetIntValue( '&showcmd' )
  345. vim.command( 'set noruler noshowcmd' )
  346. EchoText( truncated_text, False )
  347. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  348. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  349. def EscapeForVim( text ):
  350. return text.replace( "'", "''" )
  351. def CurrentFiletypes():
  352. return vim.eval( "&filetype" ).split( '.' )
  353. def FiletypesForBuffer( buffer_object ):
  354. # NOTE: Getting &ft for other buffers only works when the buffer has been
  355. # visited by the user at least once, which is true for modified buffers
  356. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  357. def VariableExists( variable ):
  358. return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
  359. def SetVariableValue( variable, value ):
  360. vim.command( "let {0} = '{1}'".format( variable, EscapeForVim( value ) ) )
  361. def GetVariableValue( variable ):
  362. return vim.eval( variable )
  363. def GetBoolValue( variable ):
  364. return bool( int( vim.eval( variable ) ) )
  365. def GetIntValue( variable ):
  366. return int( vim.eval( variable ) )
  367. def ReplaceChunksList( chunks, vim_buffer = None ):
  368. if vim_buffer is None:
  369. vim_buffer = vim.current.buffer
  370. # We need to track the difference in length, but ensuring we apply fixes
  371. # in ascending order of insertion point.
  372. chunks.sort( key = lambda chunk: (
  373. chunk[ 'range' ][ 'start' ][ 'line_num' ],
  374. chunk[ 'range' ][ 'start' ][ 'column_num' ]
  375. ) )
  376. # Remember the line number we're processing. Negative line number means we
  377. # haven't processed any lines yet (by nature of being not equal to any
  378. # real line number).
  379. last_line = -1
  380. line_delta = 0
  381. for chunk in chunks:
  382. if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line:
  383. # If this chunk is on a different line than the previous chunk,
  384. # then ignore previous deltas (as offsets won't have changed).
  385. last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ]
  386. char_delta = 0
  387. ( new_line_delta, new_char_delta ) = ReplaceChunk(
  388. chunk[ 'range' ][ 'start' ],
  389. chunk[ 'range' ][ 'end' ],
  390. chunk[ 'replacement_text' ],
  391. line_delta, char_delta,
  392. vim_buffer )
  393. line_delta += new_line_delta
  394. char_delta += new_char_delta
  395. # Replace the chunk of text specified by a contiguous range with the supplied
  396. # text.
  397. # * start and end are objects with line_num and column_num properties
  398. # * the range is inclusive
  399. # * indices are all 1-based
  400. # * the returned character delta is the delta for the last line
  401. #
  402. # returns the delta (in lines and characters) that any position after the end
  403. # needs to be adjusted by.
  404. def ReplaceChunk( start, end, replacement_text, line_delta, char_delta,
  405. vim_buffer ):
  406. # ycmd's results are all 1-based, but vim's/python's are all 0-based
  407. # (so we do -1 on all of the values)
  408. start_line = start[ 'line_num' ] - 1 + line_delta
  409. end_line = end[ 'line_num' ] - 1 + line_delta
  410. source_lines_count = end_line - start_line + 1
  411. start_column = start[ 'column_num' ] - 1 + char_delta
  412. end_column = end[ 'column_num' ] - 1
  413. if source_lines_count == 1:
  414. end_column += char_delta
  415. replacement_lines = replacement_text.splitlines( False )
  416. if not replacement_lines:
  417. replacement_lines = [ '' ]
  418. replacement_lines_count = len( replacement_lines )
  419. end_existing_text = vim_buffer[ end_line ][ end_column : ]
  420. start_existing_text = vim_buffer[ start_line ][ : start_column ]
  421. new_char_delta = ( len( replacement_lines[ -1 ] )
  422. - ( end_column - start_column ) )
  423. if replacement_lines_count > 1:
  424. new_char_delta -= start_column
  425. replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  426. replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
  427. vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
  428. new_line_delta = replacement_lines_count - source_lines_count
  429. return ( new_line_delta, new_char_delta )
  430. def InsertNamespace( namespace ):
  431. if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
  432. expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
  433. if expr:
  434. SetVariableValue( "g:ycm_namespace_to_insert", namespace )
  435. vim.eval( expr )
  436. return
  437. pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  438. line = SearchInCurrentBuffer( pattern )
  439. existing_line = LineTextInCurrentBuffer( line )
  440. existing_indent = re.sub( r"\S.*", "", existing_line )
  441. new_line = "{0}using {1};\n\n".format( existing_indent, namespace )
  442. replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  443. ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0 )
  444. PostVimMessage( "Add namespace: {0}".format( namespace ) )
  445. def SearchInCurrentBuffer( pattern ):
  446. return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
  447. def LineTextInCurrentBuffer( line ):
  448. return vim.current.buffer[ line ]
  449. def ClosePreviewWindow():
  450. """ Close the preview window if it is present, otherwise do nothing """
  451. vim.command( 'silent! pclose!' )
  452. def JumpToPreviewWindow():
  453. """ Jump the vim cursor to the preview window, which must be active. Returns
  454. boolean indicating if the cursor ended up in the preview window """
  455. vim.command( 'silent! wincmd P' )
  456. return vim.current.window.options[ 'previewwindow' ]
  457. def JumpToPreviousWindow():
  458. """ Jump the vim cursor to its previous window position """
  459. vim.command( 'silent! wincmd p' )
  460. def JumpToTab( tab_number ):
  461. """Jump to Vim tab with corresponding number """
  462. vim.command( 'silent! tabn {0}'.format( tab_number ) )
  463. def OpenFileInPreviewWindow( filename ):
  464. """ Open the supplied filename in the preview window """
  465. vim.command( 'silent! pedit! ' + filename )
  466. def WriteToPreviewWindow( message ):
  467. """ Display the supplied message in the preview window """
  468. # This isn't something that comes naturally to Vim. Vim only wants to show
  469. # tags and/or actual files in the preview window, so we have to hack it a
  470. # little bit. We generate a temporary file name and "open" that, then write
  471. # the data to it. We make sure the buffer can't be edited or saved. Other
  472. # approaches include simply opening a split, but we want to take advantage of
  473. # the existing Vim options for preview window height, etc.
  474. ClosePreviewWindow()
  475. OpenFileInPreviewWindow( vim.eval( 'tempname()' ) )
  476. if JumpToPreviewWindow():
  477. # We actually got to the preview window. By default the preview window can't
  478. # be changed, so we make it writable, write to it, then make it read only
  479. # again.
  480. vim.current.buffer.options[ 'modifiable' ] = True
  481. vim.current.buffer.options[ 'readonly' ] = False
  482. vim.current.buffer[:] = message.splitlines()
  483. vim.current.buffer.options[ 'buftype' ] = 'nofile'
  484. vim.current.buffer.options[ 'swapfile' ] = False
  485. vim.current.buffer.options[ 'modifiable' ] = False
  486. vim.current.buffer.options[ 'readonly' ] = True
  487. # We need to prevent closing the window causing a warning about unsaved
  488. # file, so we pretend to Vim that the buffer has not been changed.
  489. vim.current.buffer.options[ 'modified' ] = False
  490. JumpToPreviousWindow()
  491. else:
  492. # We couldn't get to the preview window, but we still want to give the user
  493. # the information we have. The only remaining option is to echo to the
  494. # status area.
  495. EchoText( message )
  496. def CheckFilename( filename ):
  497. """Check if filename is openable."""
  498. try:
  499. open( filename ).close()
  500. except TypeError:
  501. raise RuntimeError( "'{0}' is not a valid filename".format( filename ) )
  502. except IOError as error:
  503. raise RuntimeError(
  504. "filename '{0}' cannot be opened. {1}".format( filename, error ) )
  505. def BufferIsVisibleForFilename( filename ):
  506. """Check if a buffer exists for a specific file."""
  507. buffer_number = GetBufferNumberForFilename( filename, False )
  508. return BufferIsVisible( buffer_number )
  509. def CloseBuffersForFilename( filename ):
  510. """Close all buffers for a specific file."""
  511. buffer_number = GetBufferNumberForFilename( filename, False )
  512. while buffer_number is not -1:
  513. vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) )
  514. new_buffer_number = GetBufferNumberForFilename( filename, False )
  515. if buffer_number == new_buffer_number:
  516. raise RuntimeError( "Buffer {0} for filename '{1}' should already be "
  517. "wiped out.".format( buffer_number, filename ) )
  518. buffer_number = new_buffer_number
  519. def OpenFilename( filename, options = {} ):
  520. """Open a file in Vim. Following options are available:
  521. - command: specify which Vim command is used to open the file. Choices
  522. are same-buffer, horizontal-split, vertical-split, and new-tab (default:
  523. horizontal-split);
  524. - size: set the height of the window for a horizontal split or the width for
  525. a vertical one (default: '');
  526. - fix: set the winfixheight option for a horizontal split or winfixwidth for
  527. a vertical one (default: False). See :h winfix for details;
  528. - focus: focus the opened file (default: False);
  529. - watch: automatically watch for changes (default: False). This is useful
  530. for logs;
  531. - position: set the position where the file is opened (default: start).
  532. Choices are start and end."""
  533. # Set the options.
  534. command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
  535. 'horizontal-split' )
  536. size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
  537. '' )
  538. focus = options.get( 'focus', False )
  539. watch = options.get( 'watch', False )
  540. position = options.get( 'position', 'start' )
  541. # There is no command in Vim to return to the previous tab so we need to
  542. # remember the current tab if needed.
  543. if not focus and command is 'tabedit':
  544. previous_tab = GetIntValue( 'tabpagenr()' )
  545. # Open the file
  546. CheckFilename( filename )
  547. vim.command( 'silent! {0}{1} {2}'.format( size, command, filename ) )
  548. if command is 'split':
  549. vim.current.window.options[ 'winfixheight' ] = options.get( 'fix', False )
  550. if command is 'vsplit':
  551. vim.current.window.options[ 'winfixwidth' ] = options.get( 'fix', False )
  552. if watch:
  553. vim.current.buffer.options[ 'autoread' ] = True
  554. vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
  555. .format( filename ) )
  556. if position is 'end':
  557. vim.command( 'silent! normal G zz' )
  558. # Vim automatically set the focus to the opened file so we need to get the
  559. # focus back (if the focus option is disabled) when opening a new tab or
  560. # window.
  561. if not focus:
  562. if command is 'tabedit':
  563. JumpToTab( previous_tab )
  564. if command in [ 'split', 'vsplit' ]:
  565. JumpToPreviousWindow()