vimsupport.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 json
  22. from ycm.utils import ToUtf8IfNeeded
  23. from ycm import user_options_store
  24. BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
  25. 'horizontal-split' : 'split',
  26. 'vertical-split' : 'vsplit',
  27. 'new-tab' : 'tabedit' }
  28. def CurrentLineAndColumn():
  29. """Returns the 0-based current line and 0-based current column."""
  30. # See the comment in CurrentColumn about the calculation for the line and
  31. # column number
  32. line, column = vim.current.window.cursor
  33. line -= 1
  34. return line, column
  35. def CurrentColumn():
  36. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  37. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  38. line. Only the chars before the current column exist in vim.current.line."""
  39. # vim's columns are 1-based while vim.current.line columns are 0-based
  40. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  41. # columns are 0-based, while the line from that same tuple is 1-based.
  42. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  43. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  44. return vim.current.window.cursor[ 1 ]
  45. def TextAfterCursor():
  46. """Returns the text after CurrentColumn."""
  47. return vim.current.line[ CurrentColumn(): ]
  48. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  49. # the same.
  50. def GetBufferOption( buffer_object, option ):
  51. # NOTE: We used to check for the 'options' property on the buffer_object which
  52. # is available in recent versions of Vim and would then use:
  53. #
  54. # buffer_object.options[ option ]
  55. #
  56. # to read the value, BUT this caused annoying flickering when the
  57. # buffer_object was a hidden buffer (with option = 'ft'). This was all due to
  58. # a Vim bug. Until this is fixed, we won't use it.
  59. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  60. return GetVariableValue( to_eval )
  61. def BufferModified( buffer_object ):
  62. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  63. def GetUnsavedAndCurrentBufferData():
  64. buffers_data = {}
  65. for buffer_object in vim.buffers:
  66. if not ( BufferModified( buffer_object ) or
  67. buffer_object == vim.current.buffer ):
  68. continue
  69. buffers_data[ GetBufferFilepath( buffer_object ) ] = {
  70. 'contents': '\n'.join( buffer_object ),
  71. 'filetypes': FiletypesForBuffer( buffer_object )
  72. }
  73. return buffers_data
  74. def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
  75. return GetIntValue( "bufnr('{0}', {1})".format(
  76. os.path.realpath( filename ),
  77. int( open_file_if_needed ) ) )
  78. def GetCurrentBufferFilepath():
  79. return GetBufferFilepath( vim.current.buffer )
  80. def BufferIsVisible( buffer_number ):
  81. if buffer_number < 0:
  82. return False
  83. window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
  84. return window_number != -1
  85. def GetBufferFilepath( buffer_object ):
  86. if buffer_object.name:
  87. return buffer_object.name
  88. # Buffers that have just been created by a command like :enew don't have any
  89. # buffer name so we use the buffer number for that.
  90. return os.path.join( os.getcwd(), str( buffer_object.number ) )
  91. # NOTE: This unplaces *all* signs in a buffer, not just the ones we placed. We
  92. # used to track which signs we ended up placing and would then only unplace
  93. # ours, but that causes flickering Vim since we have to call
  94. # sign unplace <id> buffer=<buffer-num>
  95. # in a loop. So we're forced to unplace all signs, which might conflict with
  96. # other Vim plugins.
  97. def UnplaceAllSignsInBuffer( buffer_number ):
  98. if buffer_number < 0:
  99. return
  100. vim.command( 'sign unplace * buffer={0}'.format( buffer_number ) )
  101. def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
  102. sign_name = 'YcmError' if is_error else 'YcmWarning'
  103. vim.command( 'sign place {0} line={1} name={2} buffer={3}'.format(
  104. sign_id, line_num, sign_name, buffer_num ) )
  105. def ClearYcmSyntaxMatches():
  106. matches = VimExpressionToPythonType( 'getmatches()' )
  107. for match in matches:
  108. if match[ 'group' ].startswith( 'Ycm' ):
  109. vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
  110. # Returns the ID of the newly added match
  111. # Both line and column numbers are 1-based
  112. def AddDiagnosticSyntaxMatch( line_num,
  113. column_num,
  114. line_end_num = None,
  115. column_end_num = None,
  116. is_error = True ):
  117. group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
  118. if not line_end_num:
  119. line_end_num = line_num
  120. line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
  121. line_end_num, column_end_num = LineAndColumnNumbersClamped( line_end_num,
  122. column_end_num )
  123. if not column_end_num:
  124. return GetIntValue(
  125. "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
  126. else:
  127. return GetIntValue(
  128. "matchadd('{0}', '\%{1}l\%{2}c\_.*\%{3}l\%{4}c')".format(
  129. group, line_num, column_num, line_end_num, column_end_num ) )
  130. # Clamps the line and column numbers so that they are not past the contents of
  131. # the buffer. Numbers are 1-based.
  132. def LineAndColumnNumbersClamped( line_num, column_num ):
  133. new_line_num = line_num
  134. new_column_num = column_num
  135. max_line = len( vim.current.buffer )
  136. if line_num and line_num > max_line:
  137. new_line_num = max_line
  138. max_column = len( vim.current.buffer[ new_line_num - 1 ] )
  139. if column_num and column_num > max_column:
  140. new_column_num = max_column
  141. return new_line_num, new_column_num
  142. def SetLocationList( diagnostics ):
  143. """Diagnostics should be in qflist format; see ":h setqflist" for details."""
  144. vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
  145. def ConvertDiagnosticsToQfList( diagnostics ):
  146. def ConvertDiagnosticToQfFormat( diagnostic ):
  147. # see :h getqflist for a description of the dictionary fields
  148. # Note that, as usual, Vim is completely inconsistent about whether
  149. # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
  150. # them to be 1-based.
  151. location = diagnostic[ 'location' ]
  152. return {
  153. 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
  154. 'lnum' : location[ 'line_num' ] + 1,
  155. 'col' : location[ 'column_num' ] + 1,
  156. 'text' : ToUtf8IfNeeded( diagnostic[ 'text' ] ),
  157. 'type' : diagnostic[ 'kind' ],
  158. 'valid' : 1
  159. }
  160. return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
  161. # Given a dict like {'a': 1}, loads it into Vim as if you ran 'let g:a = 1'
  162. # When |overwrite| is True, overwrites the existing value in Vim.
  163. def LoadDictIntoVimGlobals( new_globals, overwrite = True ):
  164. extend_option = '"force"' if overwrite else '"keep"'
  165. # We need to use json.dumps because that won't use the 'u' prefix on strings
  166. # which Vim would bork on.
  167. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ),
  168. extend_option ) )
  169. # Changing the returned dict will NOT change the value in Vim.
  170. def GetReadOnlyVimGlobals( force_python_objects = False ):
  171. if force_python_objects:
  172. return vim.eval( 'g:' )
  173. try:
  174. # vim.vars is fairly new so it might not exist
  175. return vim.vars
  176. except:
  177. return vim.eval( 'g:' )
  178. def VimExpressionToPythonType( vim_expression ):
  179. result = vim.eval( vim_expression )
  180. if not isinstance( result, basestring ):
  181. return result
  182. try:
  183. return int( result )
  184. except ValueError:
  185. return result
  186. # Both |line| and |column| need to be 1-based
  187. def JumpToLocation( filename, line, column ):
  188. # Add an entry to the jumplist
  189. vim.command( "normal! m'" )
  190. if filename != GetCurrentBufferFilepath():
  191. # We prefix the command with 'keepjumps' so that opening the file is not
  192. # recorded in the jumplist. So when we open the file and move the cursor to
  193. # a location in it, the user can use CTRL-O to jump back to the original
  194. # location, not to the start of the newly opened file.
  195. # Sadly this fails on random occasions and the undesired jump remains in the
  196. # jumplist.
  197. user_command = user_options_store.Value( 'goto_buffer_command' )
  198. command = BUFFER_COMMAND_MAP.get( user_command, 'edit' )
  199. if command == 'edit' and BufferModified( vim.current.buffer ):
  200. command = 'split'
  201. vim.command( 'keepjumps {0} {1}'.format( command, filename ) )
  202. vim.current.window.cursor = ( line, column - 1 )
  203. # Center the screen on the jumped-to location
  204. vim.command( 'normal! zz' )
  205. def NumLinesInBuffer( buffer_object ):
  206. # This is actually less than obvious, that's why it's wrapped in a function
  207. return len( buffer_object )
  208. # Calling this function from the non-GUI thread will sometimes crash Vim. At the
  209. # time of writing, YCM only uses the GUI thread inside Vim (this used to not be
  210. # the case).
  211. def PostVimMessage( message ):
  212. vim.command( "echohl WarningMsg | echom '{0}' | echohl None"
  213. .format( EscapeForVim( str( message ) ) ) )
  214. # Unlike PostVimMesasge, this supports messages with newlines in them because it
  215. # uses 'echo' instead of 'echomsg'. This also means that the message will NOT
  216. # appear in Vim's message log.
  217. def PostMultiLineNotice( message ):
  218. vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
  219. .format( EscapeForVim( str( message ) ) ) )
  220. def PresentDialog( message, choices, default_choice_index = 0 ):
  221. """Presents the user with a dialog where a choice can be made.
  222. This will be a dialog for gvim users or a question in the message buffer
  223. for vim users or if `set guioptions+=c` was used.
  224. choices is list of alternatives.
  225. default_choice_index is the 0-based index of the default element
  226. that will get choosen if the user hits <CR>. Use -1 for no default.
  227. PresentDialog will return a 0-based index into the list
  228. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  229. See also:
  230. :help confirm() in vim (Note that vim uses 1-based indexes)
  231. Example call:
  232. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  233. Is this a nice example?
  234. [Y]es, (N)o, May(b)e:"""
  235. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  236. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  237. return int( vim.eval( to_eval ) ) - 1
  238. def Confirm( message ):
  239. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  240. def EchoText( text, log_as_message = True ):
  241. def EchoLine( text ):
  242. command = 'echom' if log_as_message else 'echo'
  243. vim.command( "{0} '{1}'".format( command, EscapeForVim( text ) ) )
  244. for line in str( text ).split( '\n' ):
  245. EchoLine( line )
  246. # Echos text but truncates it so that it all fits on one line
  247. def EchoTextVimWidth( text ):
  248. vim_width = GetIntValue( '&columns' )
  249. truncated_text = ToUtf8IfNeeded( text )[ : int( vim_width * 0.9 ) ]
  250. truncated_text.replace( '\n', ' ' )
  251. old_ruler = GetIntValue( '&ruler' )
  252. old_showcmd = GetIntValue( '&showcmd' )
  253. vim.command( 'set noruler noshowcmd' )
  254. EchoText( truncated_text, False )
  255. vim.command( 'let &ruler = {0}'.format( old_ruler ) )
  256. vim.command( 'let &showcmd = {0}'.format( old_showcmd ) )
  257. def EscapeForVim( text ):
  258. return text.replace( "'", "''" )
  259. def CurrentFiletypes():
  260. return vim.eval( "&filetype" ).split( '.' )
  261. def FiletypesForBuffer( buffer_object ):
  262. # NOTE: Getting &ft for other buffers only works when the buffer has been
  263. # visited by the user at least once, which is true for modified buffers
  264. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  265. def GetVariableValue( variable ):
  266. return vim.eval( variable )
  267. def GetBoolValue( variable ):
  268. return bool( int( vim.eval( variable ) ) )
  269. def GetIntValue( variable ):
  270. return int( vim.eval( variable ) )