vimsupport.py 12 KB

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