vimsupport.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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.
  189. location = diagnostic[ 'location' ]
  190. line_num = location[ 'line_num' ]
  191. # libclang can give us diagnostics that point "outside" the file; Vim borks
  192. # on these.
  193. if line_num < 1:
  194. line_num = 1
  195. text = diagnostic[ 'text' ]
  196. if diagnostic.get( 'fixit_available', False ):
  197. text += ' (FixIt available)'
  198. return {
  199. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  200. 'lnum' : line_num,
  201. 'col' : location[ 'column_num' ],
  202. 'text' : ToUtf8IfNeeded( text ),
  203. 'type' : diagnostic[ 'kind' ][ 0 ],
  204. 'valid' : 1
  205. }
  206. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  207. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  208. # When |overwrite| is True, overwrites the existing value in Vim.
  209. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  210. extend_option = '"force"' if overwrite else '"keep"'
  211. # We need to use json.dumps because that won't use the 'u' prefix on strings
  212. # which Vim would bork on.
  213. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  214. extend_option ) )
  215. # Changing the returned dict will NOT change the value in Vim.
  216. def GetReadOnlyVimGlobals( force_python_objects = False ):
  217. if force_python_objects:
  218. return vim.eval( 'g:' )
  219. try:
  220. # vim.vars is fairly new so it might not exist
  221. return vim.vars
  222. except:
  223. return vim.eval( 'g:' )
  224. def VimExpressionToPythonType( vim_expression ):
  225. result = vim.eval( vim_expression )
  226. if not isinstance( result, basestring ):
  227. return result
  228. try:
  229. return int( result )
  230. except ValueError:
  231. return result
  232. def HiddenEnabled( buffer_object ):
  233. return bool( int( GetBufferOption( buffer_object, 'hid' ) ) )
  234. def BufferIsUsable( buffer_object ):
  235. return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
  236. def EscapedFilepath( filepath ):
  237. return filepath.replace( ' ' , r'\ ' )
  238. # Both |line| and |column| need to be 1-based
  239. def TryJumpLocationInOpenedTab( filename, line, column ):
  240. filepath = os.path.realpath( filename )
  241. for tab in vim.tabpages:
  242. for win in tab.windows:
  243. if win.buffer.name == filepath:
  244. vim.current.tabpage = tab
  245. vim.current.window = win
  246. vim.current.window.cursor = ( line, column - 1 )
  247. # Center the screen on the jumped-to location
  248. vim.command( 'normal! zz' )
  249. return True
  250. # 'filename' is not opened in any tab pages
  251. return False
  252. # Maps User jump command to vim jump command
  253. def GetVimJumpCommand( user_command ):
  254. vim_command = BUFFER_COMMAND_MAP.get( user_command, 'edit' )
  255. if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
  256. vim_command = 'split'
  257. return vim_command
  258. # Both |line| and |column| need to be 1-based
  259. def JumpToLocation( filename, line, column ):
  260. # Add an entry to the jumplist
  261. vim.command( "normal! m'" )
  262. if filename != GetCurrentBufferFilepath():
  263. # We prefix the command with 'keepjumps' so that opening the file is not
  264. # recorded in the jumplist. So when we open the file and move the cursor to
  265. # a location in it, the user can use CTRL-O to jump back to the original
  266. # location, not to the start of the newly opened file.
  267. # Sadly this fails on random occasions and the undesired jump remains in the
  268. # jumplist.
  269. user_command = user_options_store.Value( 'goto_buffer_command' )
  270. if user_command == 'new-or-existing-tab':
  271. if TryJumpLocationInOpenedTab( filename, line, column ):
  272. return
  273. user_command = 'new-tab'
  274. vim_command = GetVimJumpCommand( user_command )
  275. try:
  276. vim.command( 'keepjumps {0} {1}'.format( vim_command,
  277. EscapedFilepath( filename ) ) )
  278. # When the file we are trying to jump to has a swap file
  279. # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  280. # or KeyboardInterrupt after user selects one of the options.
  281. except vim.error as e:
  282. if 'E325' not in str( e ):
  283. raise
  284. # Do nothing if the target file is still not opened (user chose (Q)uit)
  285. if filename != GetCurrentBufferFilepath():
  286. return
  287. # Thrown when user chooses (A)bort in .swp message box
  288. except KeyboardInterrupt:
  289. return
  290. vim.current.window.cursor = ( line, column - 1 )
  291. # Center the screen on the jumped-to location
  292. vim.command( 'normal! zz' )
  293. def NumLinesInBuffer( buffer_object ):
  294. # This is actually less than obvious, that's why it's wrapped in a function
  295. return len( buffer_object )
  296. # Calling this function from the non-GUI thread will sometimes crash Vim. At
  297. # the time of writing, YCM only uses the GUI thread inside Vim (this used to
  298. # not be the case).
  299. # We redraw the screen before displaying the message to avoid the "Press ENTER
  300. # or type command to continue" prompt when editing a new C-family file.
  301. def PostVimMessage( message ):
  302. vim.command( "redraw | echohl WarningMsg | echom '{0}' | echohl None"
  303. .format( EscapeForVim( str( message ) ) ) )
  304. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  305. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  306. # appear in Vim's message log.
  307. def PostMultiLineNotice( message ):
  308. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  309. .format( EscapeForVim( str( message ) ) ) )
  310. def PresentDialog( message, choices, default_choice_index = 0 ):
  311. """Presents the user with a dialog where a choice can be made.
  312. This will be a dialog for gvim users or a question in the message buffer
  313. for vim users or if `set guioptions+=c` was used.
  314. choices is list of alternatives.
  315. default_choice_index is the 0-based index of the default element
  316. that will get choosen if the user hits <CR>. Use -1 for no default.
  317. PresentDialog will return a 0-based index into the list
  318. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  319. See also:
  320. :help confirm() in vim (Note that vim uses 1-based indexes)
  321. Example call:
  322. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  323. Is this a nice example?
  324. [Y]es, (N)o, May(b)e:"""
  325. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  326. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  327. return int( vim.eval( to_eval ) ) - 1
  328. def Confirm( message ):
  329. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  330. def EchoText( text, log_as_message = True ):
  331. def EchoLine( text ):
  332. command = 'echom' if log_as_message else 'echo'
  333. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  334. for line in str( text ).split( '\n' ):
  335. EchoLine( line )
  336. # Echos text but truncates it so that it all fits on one line
  337. def EchoTextVimWidth( text ):
  338. vim_width = GetIntValue( '&columns' )
  339. truncated_text = ToUtf8IfNeeded( text )[ : int( vim_width * 0.9 ) ]
  340. truncated_text.replace( '\n', ' ' )
  341. old_ruler = GetIntValue( '&ruler' )
  342. old_showcmd = GetIntValue( '&showcmd' )
  343. vim.command( 'set noruler noshowcmd' )
  344. EchoText( truncated_text, False )
  345. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  346. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  347. def EscapeForVim( text ):
  348. return text.replace( "'", "''" )
  349. def CurrentFiletypes():
  350. return vim.eval( "&filetype" ).split( '.' )
  351. def FiletypesForBuffer( buffer_object ):
  352. # NOTE: Getting &ft for other buffers only works when the buffer has been
  353. # visited by the user at least once, which is true for modified buffers
  354. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  355. def VariableExists( variable ):
  356. return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
  357. def SetVariableValue( variable, value ):
  358. vim.command( "let {0} = '{1}'".format( variable, EscapeForVim( value ) ) )
  359. def GetVariableValue( variable ):
  360. return vim.eval( variable )
  361. def GetBoolValue( variable ):
  362. return bool( int( vim.eval( variable ) ) )
  363. def GetIntValue( variable ):
  364. return int( vim.eval( variable ) )
  365. def ReplaceChunksList( chunks, vim_buffer = None ):
  366. if vim_buffer is None:
  367. vim_buffer = vim.current.buffer
  368. # We need to track the difference in length, but ensuring we apply fixes
  369. # in ascending order of insertion point.
  370. chunks.sort( key = lambda chunk: (
  371. chunk[ 'range' ][ 'start' ][ 'line_num' ],
  372. chunk[ 'range' ][ 'start' ][ 'column_num' ]
  373. ) )
  374. # Remember the line number we're processing. Negative line number means we
  375. # haven't processed any lines yet (by nature of being not equal to any
  376. # real line number).
  377. last_line = -1
  378. line_delta = 0
  379. for chunk in chunks:
  380. if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line:
  381. # If this chunk is on a different line than the previous chunk,
  382. # then ignore previous deltas (as offsets won't have changed).
  383. last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ]
  384. char_delta = 0
  385. ( new_line_delta, new_char_delta ) = ReplaceChunk(
  386. chunk[ 'range' ][ 'start' ],
  387. chunk[ 'range' ][ 'end' ],
  388. chunk[ 'replacement_text' ],
  389. line_delta, char_delta,
  390. vim_buffer )
  391. line_delta += new_line_delta
  392. char_delta += new_char_delta
  393. # Replace the chunk of text specified by a contiguous range with the supplied
  394. # text.
  395. # * start and end are objects with line_num and column_num properties
  396. # * the range is inclusive
  397. # * indices are all 1-based
  398. # * the returned character delta is the delta for the last line
  399. #
  400. # returns the delta (in lines and characters) that any position after the end
  401. # needs to be adjusted by.
  402. def ReplaceChunk( start, end, replacement_text, line_delta, char_delta,
  403. vim_buffer ):
  404. # ycmd's results are all 1-based, but vim's/python's are all 0-based
  405. # (so we do -1 on all of the values)
  406. start_line = start[ 'line_num' ] - 1 + line_delta
  407. end_line = end[ 'line_num' ] - 1 + line_delta
  408. source_lines_count = end_line - start_line + 1
  409. start_column = start[ 'column_num' ] - 1 + char_delta
  410. end_column = end[ 'column_num' ] - 1
  411. if source_lines_count == 1:
  412. end_column += char_delta
  413. replacement_lines = replacement_text.splitlines( False )
  414. if not replacement_lines:
  415. replacement_lines = [ '' ]
  416. replacement_lines_count = len( replacement_lines )
  417. end_existing_text = vim_buffer[ end_line ][ end_column : ]
  418. start_existing_text = vim_buffer[ start_line ][ : start_column ]
  419. new_char_delta = ( len( replacement_lines[ -1 ] )
  420. - ( end_column - start_column ) )
  421. if replacement_lines_count > 1:
  422. new_char_delta -= start_column
  423. replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  424. replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
  425. vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
  426. new_line_delta = replacement_lines_count - source_lines_count
  427. return ( new_line_delta, new_char_delta )
  428. def InsertNamespace( namespace ):
  429. if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
  430. expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
  431. if expr:
  432. SetVariableValue( "g:ycm_namespace_to_insert", namespace )
  433. vim.eval( expr )
  434. return
  435. pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  436. line = SearchInCurrentBuffer( pattern )
  437. existing_line = LineTextInCurrentBuffer( line )
  438. existing_indent = re.sub( r"\S.*", "", existing_line )
  439. new_line = "{0}using {1};\n\n".format( existing_indent, namespace )
  440. replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  441. ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0 )
  442. PostVimMessage( "Add namespace: {0}".format( namespace ) )
  443. def SearchInCurrentBuffer( pattern ):
  444. return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
  445. def LineTextInCurrentBuffer( line ):
  446. return vim.current.buffer[ line ]
  447. def ClosePreviewWindow():
  448. """ Close the preview window if it is present, otherwise do nothing """
  449. vim.command( 'silent! pclose!' )
  450. def JumpToPreviewWindow():
  451. """ Jump the vim cursor to the preview window, which must be active. Returns
  452. boolean indicating if the cursor ended up in the preview window """
  453. vim.command( 'silent! wincmd P' )
  454. return vim.current.window.options[ 'previewwindow' ]
  455. def JumpToPreviousWindow():
  456. """ Jump the vim cursor to its previous window position """
  457. vim.command( 'silent! wincmd p' )
  458. def OpenFileInPreviewWindow( filename ):
  459. """ Open the supplied filename in the preview window """
  460. vim.command( 'silent! pedit! ' + filename )
  461. def WriteToPreviewWindow( message ):
  462. """ Display the supplied message in the preview window """
  463. # This isn't something that comes naturally to Vim. Vim only wants to show
  464. # tags and/or actual files in the preview window, so we have to hack it a
  465. # little bit. We generate a temporary file name and "open" that, then write
  466. # the data to it. We make sure the buffer can't be edited or saved. Other
  467. # approaches include simply opening a split, but we want to take advantage of
  468. # the existing Vim options for preview window height, etc.
  469. ClosePreviewWindow()
  470. OpenFileInPreviewWindow( vim.eval( 'tempname()' ) )
  471. if JumpToPreviewWindow():
  472. # We actually got to the preview window. By default the preview window can't
  473. # be changed, so we make it writable, write to it, then make it read only
  474. # again.
  475. vim.current.buffer.options[ 'modifiable' ] = True
  476. vim.current.buffer.options[ 'readonly' ] = False
  477. vim.current.buffer[:] = message.splitlines()
  478. vim.current.buffer.options[ 'buftype' ] = 'nofile'
  479. vim.current.buffer.options[ 'swapfile' ] = False
  480. vim.current.buffer.options[ 'modifiable' ] = False
  481. vim.current.buffer.options[ 'readonly' ] = True
  482. # We need to prevent closing the window causing a warning about unsaved
  483. # file, so we pretend to Vim that the buffer has not been changed.
  484. vim.current.buffer.options[ 'modified' ] = False
  485. JumpToPreviousWindow()
  486. else:
  487. # We couldn't get to the preview window, but we still want to give the user
  488. # the information we have. The only remaining option is to echo to the
  489. # status area.
  490. EchoText( message )