vimsupport.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io>
  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 json
  22. def CurrentLineAndColumn():
  23. """Returns the 0-based current line and 0-based current column."""
  24. # See the comment in CurrentColumn about the calculation for the line and
  25. # column number
  26. line, column = vim.current.window.cursor
  27. line -= 1
  28. return line, column
  29. def CurrentColumn():
  30. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  31. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  32. line. Only the chars before the current column exist in vim.current.line."""
  33. # vim's columns are 1-based while vim.current.line columns are 0-based
  34. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  35. # columns are 0-based, while the line from that same tuple is 1-based.
  36. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  37. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  38. return vim.current.window.cursor[ 1 ]
  39. def TextAfterCursor():
  40. """Returns the text after CurrentColumn."""
  41. return vim.current.line[ CurrentColumn(): ]
  42. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  43. # the same.
  44. def GetBufferOption( buffer_object, option ):
  45. # NOTE: We used to check for the 'options' property on the buffer_object which
  46. # is available in recent versions of Vim and would then use:
  47. #
  48. # buffer_object.options[ option ]
  49. #
  50. # to read the value, BUT this caused annoying flickering when the
  51. # buffer_object was a hidden buffer (with option = 'ft'). This was all due to
  52. # a Vim bug. Until this is fixed, we won't use it.
  53. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  54. return GetVariableValue( to_eval )
  55. def GetUnsavedAndCurrentBufferData():
  56. def BufferModified( buffer_object ):
  57. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  58. buffers_data = {}
  59. for buffer_object in vim.buffers:
  60. if not ( BufferModified( buffer_object ) or
  61. buffer_object == vim.current.buffer ):
  62. continue
  63. buffers_data[ GetBufferFilepath( buffer_object ) ] = {
  64. 'contents': '\n'.join( buffer_object ),
  65. 'filetypes': FiletypesForBuffer( buffer_object )
  66. }
  67. return buffers_data
  68. def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
  69. return GetIntValue( "bufnr('{0}', {1})".format(
  70. os.path.realpath( filename ),
  71. int( open_file_if_needed ) ) )
  72. def GetCurrentBufferFilepath():
  73. return GetBufferFilepath( vim.current.buffer )
  74. def BufferIsVisible( buffer_number ):
  75. if buffer_number < 0:
  76. return False
  77. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  78. return window_number != -1
  79. def GetBufferFilepath( buffer_object ):
  80. if buffer_object.name:
  81. return buffer_object.name
  82. # Buffers that have just been created by a command like :enew don't have any
  83. # buffer name so we use the buffer number for that.
  84. return os.path.join( os.getcwd(), str( buffer_object.number ) )
  85. def UnplaceAllSignsInBuffer( buffer_number ):
  86. if buffer_number < 0:
  87. return
  88. vim.command( 'sign unplace * buffer={0}'.format( buffer_number ) )
  89. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  90. sign_name = 'YcmError' if is_error else 'YcmWarning'
  91. vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format(
  92. sign_id, line_num, sign_name, buffer_num ) )
  93. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  94. # When |overwrite| is True, overwrites the existing value in Vim.
  95. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  96. extend_option = '"force"' if overwrite else '"keep"'
  97. # We need to use json.dumps because that won't use the 'u' prefix on strings
  98. # which Vim would bork on.
  99. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  100. extend_option ) )
  101. # Changing the returned dict will NOT change the value in Vim.
  102. def GetReadOnlyVimGlobals( force_python_objects = False ):
  103. if force_python_objects:
  104. return vim.eval( 'g:' )
  105. try:
  106. # vim.vars is fairly new so it might not exist
  107. return vim.vars
  108. except:
  109. return vim.eval( 'g:' )
  110. def VimExpressionToPythonType( vim_expression ):
  111. result = vim.eval( vim_expression )
  112. if not isinstance( result, basestring ):
  113. return result
  114. try:
  115. return int( result )
  116. except ValueError:
  117. return result
  118. # Both |line| and |column| need to be 1-based
  119. def JumpToLocation( filename, line, column ):
  120. # Add an entry to the jumplist
  121. vim.command( "normal! m'" )
  122. if filename != GetCurrentBufferFilepath():
  123. # We prefix the command with 'keepjumps' so that opening the file is not
  124. # recorded in the jumplist. So when we open the file and move the cursor to
  125. # a location in it, the user can use CTRL-O to jump back to the original
  126. # location, not to the start of the newly opened file.
  127. # Sadly this fails on random occasions and the undesired jump remains in the
  128. # jumplist.
  129. vim.command( 'keepjumps edit {0}'.format( filename ) )
  130. vim.current.window.cursor = ( line, column - 1 )
  131. # Center the screen on the jumped-to location
  132. vim.command( 'normal! zz' )
  133. def NumLinesInBuffer( buffer_object ):
  134. # This is actually less than obvious, that's why it's wrapped in a function
  135. return len( buffer_object )
  136. # Calling this function from the non-GUI thread will sometimes crash Vim. At the
  137. # time of writing, YCM only uses the GUI thread inside Vim (this used to not be
  138. # the case).
  139. def PostVimMessage( message ):
  140. vim.command( "echohl WarningMsg | echom '{0}' | echohl None"
  141. .format( EscapeForVim( str( message ) ) ) )
  142. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  143. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  144. # appear in Vim's message log.
  145. def PostMultiLineNotice( message ):
  146. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  147. .format( EscapeForVim( str( message ) ) ) )
  148. def PresentDialog( message, choices, default_choice_index = 0 ):
  149. """Presents the user with a dialog where a choice can be made.
  150. This will be a dialog for gvim users or a question in the message buffer
  151. for vim users or if `set guioptions+=c` was used.
  152. choices is list of alternatives.
  153. default_choice_index is the 0-based index of the default element
  154. that will get choosen if the user hits <CR>. Use -1 for no default.
  155. PresentDialog will return a 0-based index into the list
  156. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  157. See also:
  158. :help confirm() in vim (Note that vim uses 1-based indexes)
  159. Example call:
  160. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  161. Is this a nice example?
  162. [Y]es, (N)o, May(b)e:"""
  163. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  164. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  165. return int( vim.eval( to_eval ) ) - 1
  166. def Confirm( message ):
  167. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  168. def EchoText( text, log_as_message = True ):
  169. def EchoLine( text ):
  170. command = 'echom' if log_as_message else 'echo'
  171. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  172. for line in text.split( '\n' ):
  173. EchoLine( line )
  174. # Echos text but truncates the text so that it all fits on one line
  175. def EchoTextVimWidth( text ):
  176. vim_width = GetIntValue( '&columns' )
  177. truncated_text = text[ : int( vim_width * 0.9 ) ]
  178. truncated_text.replace( '\n', ' ' )
  179. EchoText( truncated_text, False )
  180. def EscapeForVim( text ):
  181. return text.replace( "'", "''" )
  182. def CurrentFiletypes():
  183. return vim.eval( "&filetype" ).split( '.' )
  184. def FiletypesForBuffer( buffer_object ):
  185. # NOTE: Getting &ft for other buffers only works when the buffer has been
  186. # visited by the user at least once, which is true for modified buffers
  187. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  188. def GetVariableValue( variable ):
  189. return vim.eval( variable )
  190. def GetBoolValue( variable ):
  191. return bool( int( vim.eval( variable ) ) )
  192. def GetIntValue( variable ):
  193. return int( vim.eval( variable ) )