vimsupport.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. def CurrentLineAndColumn():
  21. """Returns the 0-based current line and 0-based current column."""
  22. # See the comment in CurrentColumn about the calculation for the line and
  23. # column number
  24. line, column = vim.current.window.cursor
  25. line -= 1
  26. return line, column
  27. def CurrentColumn():
  28. """Returns the 0-based current column. Do NOT access the CurrentColumn in
  29. vim.current.line. It doesn't exist yet when the cursor is at the end of the
  30. line. Only the chars before the current column exist in vim.current.line."""
  31. # vim's columns are 1-based while vim.current.line columns are 0-based
  32. # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  33. # columns are 0-based, while the line from that same tuple is 1-based.
  34. # vim.buffers buffer objects OTOH have 0-based lines and columns.
  35. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  36. return vim.current.window.cursor[ 1 ]
  37. def TextAfterCursor():
  38. """Returns the text after CurrentColumn."""
  39. return vim.current.line[ CurrentColumn(): ]
  40. # Note the difference between buffer OPTIONS and VARIABLES; the two are not
  41. # the same.
  42. def GetBufferOption( buffer_object, option ):
  43. # The 'options' property is only available in recent (7.4+) Vim builds
  44. if hasattr( buffer_object, 'options' ):
  45. return buffer_object.options[ option ]
  46. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
  47. return GetVariableValue( to_eval )
  48. def GetUnsavedAndCurrentBufferData():
  49. def BufferModified( buffer_object ):
  50. return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
  51. buffers_data = {}
  52. for buffer_object in vim.buffers:
  53. if not ( BufferModified( buffer_object ) or
  54. buffer_object == vim.current.buffer ):
  55. continue
  56. buffers_data[ buffer_object.name ] = {
  57. 'contents': '\n'.join( buffer_object ),
  58. 'filetypes': FiletypesForBuffer( buffer_object )
  59. }
  60. return buffers_data
  61. # Both |line| and |column| need to be 1-based
  62. def JumpToLocation( filename, line, column ):
  63. # Add an entry to the jumplist
  64. vim.command( "normal! m'" )
  65. if filename != vim.current.buffer.name:
  66. # We prefix the command with 'keepjumps' so that opening the file is not
  67. # recorded in the jumplist. So when we open the file and move the cursor to
  68. # a location in it, the user can use CTRL-O to jump back to the original
  69. # location, not to the start of the newly opened file.
  70. # Sadly this fails on random occasions and the undesired jump remains in the
  71. # jumplist.
  72. vim.command( 'keepjumps edit {0}'.format( filename ) )
  73. vim.current.window.cursor = ( line, column - 1 )
  74. # Center the screen on the jumped-to location
  75. vim.command( 'normal! zz' )
  76. def NumLinesInBuffer( buffer_object ):
  77. # This is actually less than obvious, that's why it's wrapped in a function
  78. return len( buffer_object )
  79. # Calling this function from the non-GUI thread will sometimes crash Vim. At the
  80. # time of writing, YCM only uses the GUI thread inside Vim (this used to not be
  81. # the case).
  82. def PostVimMessage( message ):
  83. vim.command( "echohl WarningMsg | echomsg '{0}' | echohl None"
  84. .format( EscapeForVim( str( message ) ) ) )
  85. def PresentDialog( message, choices, default_choice_index = 0 ):
  86. """Presents the user with a dialog where a choice can be made.
  87. This will be a dialog for gvim users or a question in the message buffer
  88. for vim users or if `set guioptions+=c` was used.
  89. choices is list of alternatives.
  90. default_choice_index is the 0-based index of the default element
  91. that will get choosen if the user hits <CR>. Use -1 for no default.
  92. PresentDialog will return a 0-based index into the list
  93. or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
  94. See also:
  95. :help confirm() in vim (Note that vim uses 1-based indexes)
  96. Example call:
  97. PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
  98. Is this a nice example?
  99. [Y]es, (N)o, May(b)e:"""
  100. to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( message ),
  101. EscapeForVim( "\n" .join( choices ) ), default_choice_index + 1 )
  102. return int( vim.eval( to_eval ) ) - 1
  103. def Confirm( message ):
  104. return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
  105. def EchoText( text ):
  106. def EchoLine( text ):
  107. vim.command( "echom '{0}'".format( EscapeForVim( text ) ) )
  108. for line in text.split( '\n' ):
  109. EchoLine( line )
  110. def EscapeForVim( text ):
  111. return text.replace( "'", "''" )
  112. def CurrentFiletypes():
  113. return vim.eval( "&filetype" ).split( '.' )
  114. def FiletypesForBuffer( buffer_object ):
  115. # NOTE: Getting &ft for other buffers only works when the buffer has been
  116. # visited by the user at least once, which is true for modified buffers
  117. return GetBufferOption( buffer_object, 'ft' ).split( '.' )
  118. def GetVariableValue( variable ):
  119. return vim.eval( variable )
  120. def GetBoolValue( variable ):
  121. return bool( int( vim.eval( variable ) ) )
  122. def GetIntValue( variable ):
  123. return int( vim.eval( variable ) )