vimsupport.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. # TODO: only unplace our signs, not all signs
  86. def UnplaceAllSignsInBuffer( buffer_number ):
  87. if buffer_number < 0:
  88. return
  89. vim.command( 'sign unplace * buffer={0}'.format( buffer_number ) )
  90. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  91. sign_name = 'YcmError' if is_error else 'YcmWarning'
  92. vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format(
  93. sign_id, line_num, sign_name, buffer_num ) )
  94. def ClearYcmSyntaxMatches():
  95. matches = VimExpressionToPythonType( 'getmatches()' )
  96. for match in matches:
  97. if match[ 'group' ].startswith( 'Ycm' ):
  98. vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
  99. # Returns the ID of the newly added match
  100. def AddDiagnosticSyntaxMatch( line_num,
  101. column_num,
  102. line_end_num = None,
  103. column_end_num = None,
  104. is_error = True ):
  105. group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
  106. if not line_end_num:
  107. line_end_num = line_num
  108. if not column_end_num:
  109. return GetIntValue(
  110. "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
  111. else:
  112. return GetIntValue(
  113. "matchadd('{0}', '\%{1}l\%{2}c\_.*\%{3}l\%{4}c')".format(
  114. group, line_num, column_num, line_end_num, column_end_num ) )
  115. def SetLocationList( diagnostics ):
  116. """Diagnostics should be in qflist format; see ":h setqflist" for details."""
  117. vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
  118. def ConvertDiagnosticsToQfList( diagnostics ):
  119. def ConvertDiagnosticToQfFormat( diagnostic ):
  120. # see :h getqflist for a description of the dictionary fields
  121. # Note that, as usual, Vim is completely inconsistent about whether
  122. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  123. # them to be 1-based.
  124. location = diagnostic[ 'location' ]
  125. return {
  126. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  127. 'lnum' : location[ 'line_num' ] + 1,
  128. 'col' : location[ 'column_num' ] + 1,
  129. 'text' : diagnostic[ 'text' ],
  130. 'type' : diagnostic[ 'kind' ],
  131. 'valid' : 1
  132. }
  133. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  134. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  135. # When |overwrite| is True, overwrites the existing value in Vim.
  136. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  137. extend_option = '"force"' if overwrite else '"keep"'
  138. # We need to use json.dumps because that won't use the 'u' prefix on strings
  139. # which Vim would bork on.
  140. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  141. extend_option ) )
  142. # Changing the returned dict will NOT change the value in Vim.
  143. def GetReadOnlyVimGlobals( force_python_objects = False ):
  144. if force_python_objects:
  145. return vim.eval( 'g:' )
  146. try:
  147. # vim.vars is fairly new so it might not exist
  148. return vim.vars
  149. except:
  150. return vim.eval( 'g:' )
  151. def VimExpressionToPythonType( vim_expression ):
  152. result = vim.eval( vim_expression )
  153. if not isinstance( result, basestring ):
  154. return result
  155. try:
  156. return int( result )
  157. except ValueError:
  158. return result
  159. # Both |line| and |column| need to be 1-based
  160. def JumpToLocation( filename, line, column ):
  161. # Add an entry to the jumplist
  162. vim.command( "normal! m'" )
  163. if filename != GetCurrentBufferFilepath():
  164. # We prefix the command with 'keepjumps' so that opening the file is not
  165. # recorded in the jumplist. So when we open the file and move the cursor to
  166. # a location in it, the user can use CTRL-O to jump back to the original
  167. # location, not to the start of the newly opened file.
  168. # Sadly this fails on random occasions and the undesired jump remains in the
  169. # jumplist.
  170. vim.command( 'keepjumps edit {0}'.format( filename ) )
  171. vim.current.window.cursor = ( line, column - 1 )
  172. # Center the screen on the jumped-to location
  173. vim.command( 'normal! zz' )
  174. def NumLinesInBuffer( buffer_object ):
  175. # This is actually less than obvious, that's why it's wrapped in a function
  176. return len( buffer_object )
  177. # Calling this function from the non-GUI thread will sometimes crash Vim. At the
  178. # time of writing, YCM only uses the GUI thread inside Vim (this used to not be
  179. # the case).
  180. def PostVimMessage( message ):
  181. vim.command( "echohl WarningMsg | echom '{0}' | echohl None"
  182. .format( EscapeForVim( str( message ) ) ) )
  183. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  184. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  185. # appear in Vim's message log.
  186. def PostMultiLineNotice( message ):
  187. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  188. .format( EscapeForVim( str( message ) ) ) )
  189. def PresentDialog( message, choices, default_choice_index = 0 ):
  190. """Presents the user with a dialog where a choice can be made.
  191. This will be a dialog for gvim users or a question in the message buffer
  192. for vim users or if `set guioptions+=c` was used.
  193. choices is list of alternatives.
  194. default_choice_index is the 0-based index of the default element
  195. that will get choosen if the user hits <CR>. Use -1 for no default.
  196. PresentDialog will return a 0-based index into the list
  197. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  198. See also:
  199. :help confirm() in vim (Note that vim uses 1-based indexes)
  200. Example call:
  201. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  202. Is this a nice example?
  203. [Y]es, (N)o, May(b)e:"""
  204. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  205. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  206. return int( vim.eval( to_eval ) ) - 1
  207. def Confirm( message ):
  208. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  209. def EchoText( text, log_as_message = True ):
  210. def EchoLine( text ):
  211. command = 'echom' if log_as_message else 'echo'
  212. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  213. for line in str( text ).split( '\n' ):
  214. EchoLine( line )
  215. # Echos text but truncates the text so that it all fits on one line
  216. def EchoTextVimWidth( text ):
  217. vim_width = GetIntValue( '&columns' )
  218. truncated_text = str( text )[ : int( vim_width * 0.9 ) ]
  219. truncated_text.replace( '\n', ' ' )
  220. old_ruler = GetIntValue( '&ruler' )
  221. old_showcmd = GetIntValue( '&showcmd' )
  222. vim.command( 'set noruler noshowcmd' )
  223. EchoText( truncated_text, False )
  224. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  225. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  226. def EscapeForVim( text ):
  227. return text.replace( "'", "''" )
  228. def CurrentFiletypes():
  229. return vim.eval( "&filetype" ).split( '.' )
  230. def FiletypesForBuffer( buffer_object ):
  231. # NOTE: Getting &ft for other buffers only works when the buffer has been
  232. # visited by the user at least once, which is true for modified buffers
  233. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  234. def GetVariableValue( variable ):
  235. return vim.eval( variable )
  236. def GetBoolValue( variable ):
  237. return bool( int( vim.eval( variable ) ) )
  238. def GetIntValue( variable ):
  239. return int( vim.eval( variable ) )