omni_completer.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright (C) 2011-2019 ycmd contributors
  2. #
  3. # This file is part of YouCompleteMe.
  4. #
  5. # YouCompleteMe is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # YouCompleteMe is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  17. from __future__ import unicode_literals
  18. from __future__ import print_function
  19. from __future__ import division
  20. from __future__ import absolute_import
  21. # Not installing aliases from python-future; it's unreliable and slow.
  22. from builtins import * # noqa
  23. import vim
  24. from ycm import vimsupport
  25. from ycmd import utils
  26. from ycmd.completers.completer import Completer
  27. from ycm.client.base_request import BaseRequest
  28. OMNIFUNC_RETURNED_BAD_VALUE = 'Omnifunc returned bad value to YCM!'
  29. OMNIFUNC_NOT_LIST = ( 'Omnifunc did not return a list or a dict with a "words" '
  30. ' list when expected.' )
  31. class OmniCompleter( Completer ):
  32. def __init__( self, user_options ):
  33. super( OmniCompleter, self ).__init__( user_options )
  34. self._omnifunc = None
  35. def SupportedFiletypes( self ):
  36. return []
  37. def ShouldUseCache( self ):
  38. return bool( self.user_options[ 'cache_omnifunc' ] )
  39. def ShouldUseNow( self, request_data ):
  40. self._omnifunc = utils.ToUnicode( vim.eval( '&omnifunc' ) )
  41. if not self._omnifunc:
  42. return False
  43. if self.ShouldUseCache():
  44. return super( OmniCompleter, self ).ShouldUseNow( request_data )
  45. return self.ShouldUseNowInner( request_data )
  46. def ShouldUseNowInner( self, request_data ):
  47. if request_data[ 'force_semantic' ]:
  48. return True
  49. disabled_filetypes = self.user_options[
  50. 'filetype_specific_completion_to_disable' ]
  51. if not vimsupport.CurrentFiletypesEnabled( disabled_filetypes ):
  52. return False
  53. return super( OmniCompleter, self ).ShouldUseNowInner( request_data )
  54. def ComputeCandidates( self, request_data ):
  55. if self.ShouldUseCache():
  56. return super( OmniCompleter, self ).ComputeCandidates( request_data )
  57. if self.ShouldUseNowInner( request_data ):
  58. return self.ComputeCandidatesInner( request_data )
  59. return []
  60. def ComputeCandidatesInner( self, request_data ):
  61. if not self._omnifunc:
  62. return []
  63. # Calling directly the omnifunc may move the cursor position. This is the
  64. # case with the default Vim omnifunc for C-family languages
  65. # (ccomplete#Complete) which calls searchdecl to find a declaration. This
  66. # function is supposed to move the cursor to the found declaration but it
  67. # doesn't when called through the omni completion mapping (CTRL-X CTRL-O).
  68. # So, we restore the cursor position after the omnifunc calls.
  69. line, column = vimsupport.CurrentLineAndColumn()
  70. try:
  71. start_column = vimsupport.GetIntValue( self._omnifunc + '(1,"")' )
  72. # Vim only stops completion if the value returned by the omnifunc is -3 or
  73. # -2. In other cases, if the value is negative or greater than the current
  74. # column, the start column is set to the current column; otherwise, the
  75. # value is used as the start column.
  76. if start_column in ( -3, -2 ):
  77. return []
  78. if start_column < 0 or start_column > column:
  79. start_column = column
  80. # Use the start column calculated by the omnifunc, rather than our own
  81. # interpretation. This is important for certain languages where our
  82. # identifier detection is either incorrect or not compatible with the
  83. # behaviour of the omnifunc. Note: do this before calling the omnifunc
  84. # because it affects the value returned by 'query'.
  85. request_data[ 'start_column' ] = start_column + 1
  86. # Vim internally moves the cursor to the start column before calling again
  87. # the omnifunc. Some omnifuncs like the one defined by the
  88. # LanguageClient-neovim plugin depend on this behavior to compute the list
  89. # of candidates.
  90. vimsupport.SetCurrentLineAndColumn( line, start_column )
  91. omnifunc_call = [ self._omnifunc,
  92. "(0,'",
  93. vimsupport.EscapeForVim( request_data[ 'query' ] ),
  94. "')" ]
  95. items = vim.eval( ''.join( omnifunc_call ) )
  96. if isinstance( items, dict ) and 'words' in items:
  97. items = items[ 'words' ]
  98. if not hasattr( items, '__iter__' ):
  99. raise TypeError( OMNIFUNC_NOT_LIST )
  100. # Vim allows each item of the list to be either a string or a dictionary
  101. # but ycmd only supports lists where items are all strings or all
  102. # dictionaries. Convert all strings into dictionaries.
  103. for index, item in enumerate( items ):
  104. # Set the 'equal' field to 1 to disable Vim filtering.
  105. if not isinstance( item, dict ):
  106. items[ index ] = {
  107. 'word': item,
  108. 'equal': 1
  109. }
  110. else:
  111. item[ 'equal' ] = 1
  112. return items
  113. except ( TypeError, ValueError, vim.error ) as error:
  114. vimsupport.PostVimMessage(
  115. OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) )
  116. return []
  117. finally:
  118. vimsupport.SetCurrentLineAndColumn( line, column )
  119. def FilterAndSortCandidatesInner( self, candidates, sort_property, query ):
  120. request_data = {
  121. 'candidates': candidates,
  122. 'sort_property': sort_property,
  123. 'query': query
  124. }
  125. response = BaseRequest().PostDataToHandler( request_data,
  126. 'filter_and_sort_candidates' )
  127. return response if response is not None else []