completion_request.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # Copyright (C) 2013-2018 YouCompleteMe 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 logging
  24. from future.utils import iteritems
  25. from ycmd.utils import ToUnicode
  26. from ycm.client.base_request import ( BaseRequest, DisplayServerException,
  27. MakeServerException )
  28. from ycm import vimsupport
  29. from ycm.vimsupport import NO_COMPLETIONS
  30. _logger = logging.getLogger( __name__ )
  31. class CompletionRequest( BaseRequest ):
  32. def __init__( self, request_data ):
  33. super( CompletionRequest, self ).__init__()
  34. self.request_data = request_data
  35. self._response_future = None
  36. self._complete_done_hooks = {
  37. 'cs': self._OnCompleteDone_Csharp,
  38. 'java': self._OnCompleteDone_FixIt,
  39. 'javascript': self._OnCompleteDone_FixIt,
  40. 'typescript': self._OnCompleteDone_FixIt,
  41. }
  42. def Start( self ):
  43. self._response_future = self.PostDataToHandlerAsync( self.request_data,
  44. 'completions' )
  45. def Done( self ):
  46. return bool( self._response_future ) and self._response_future.done()
  47. def RawResponse( self ):
  48. if not self._response_future:
  49. return NO_COMPLETIONS
  50. response = self.HandleFuture( self._response_future,
  51. truncate_message = True )
  52. if not response:
  53. return NO_COMPLETIONS
  54. # Vim may not be able to convert the 'errors' entry to its internal format
  55. # so we remove it from the response.
  56. errors = response.pop( 'errors', [] )
  57. for e in errors:
  58. exception = MakeServerException( e )
  59. _logger.error( exception )
  60. DisplayServerException( exception, truncate_message = True )
  61. response[ 'line' ] = self.request_data[ 'line_num' ]
  62. response[ 'column' ] = self.request_data[ 'column_num' ]
  63. return response
  64. def Response( self ):
  65. response = self.RawResponse()
  66. response[ 'completions' ] = _ConvertCompletionDatasToVimDatas(
  67. response[ 'completions' ] )
  68. return response
  69. def OnCompleteDone( self ):
  70. if not self.Done():
  71. return
  72. complete_done_actions = self._GetCompleteDoneHooks()
  73. for action in complete_done_actions:
  74. action()
  75. def _GetCompleteDoneHooks( self ):
  76. filetypes = vimsupport.CurrentFiletypes()
  77. for key, value in iteritems( self._complete_done_hooks ):
  78. if key in filetypes:
  79. yield value
  80. def _GetCompletionsUserMayHaveCompleted( self ):
  81. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  82. # If Vim supports user_data (8.0.1493 or later), we actually know the
  83. # _exact_ element that was selected, having put its index in the
  84. # user_data field. Otherwise, we have to guess by matching the values in the
  85. # completed item and the list of completions. Sometimes this returns
  86. # multiple possibilities, which is essentially unresolvable.
  87. if 'user_data' not in completed_item:
  88. completions = self.RawResponse()[ 'completions' ]
  89. return _FilterToMatchingCompletions( completed_item, completions )
  90. if completed_item[ 'user_data' ]:
  91. completions = self.RawResponse()[ 'completions' ]
  92. return [ completions[ int( completed_item[ 'user_data' ] ) ] ]
  93. return []
  94. def _OnCompleteDone_Csharp( self ):
  95. completions = self._GetCompletionsUserMayHaveCompleted()
  96. namespaces = [ _GetRequiredNamespaceImport( c ) for c in completions ]
  97. namespaces = [ n for n in namespaces if n ]
  98. if not namespaces:
  99. return
  100. if len( namespaces ) > 1:
  101. choices = [ "{0} {1}".format( i + 1, n )
  102. for i, n in enumerate( namespaces ) ]
  103. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  104. if choice < 0:
  105. return
  106. namespace = namespaces[ choice ]
  107. else:
  108. namespace = namespaces[ 0 ]
  109. vimsupport.InsertNamespace( namespace )
  110. def _OnCompleteDone_FixIt( self ):
  111. completions = self._GetCompletionsUserMayHaveCompleted()
  112. fixit_completions = [ _GetFixItCompletion( c ) for c in completions ]
  113. fixit_completions = [ f for f in fixit_completions if f ]
  114. if not fixit_completions:
  115. return
  116. # If we have user_data in completions (8.0.1493 or later), then we would
  117. # only ever return max. 1 completion here. However, if we had to guess, it
  118. # is possible that we matched multiple completion items (e.g. for overloads,
  119. # or similar classes in multiple packages). In any case, rather than
  120. # prompting the user and disturbing her workflow, we just apply the first
  121. # one. This might be wrong, but the solution is to use a (very) new version
  122. # of Vim which supports user_data on completion items
  123. fixit_completion = fixit_completions[ 0 ]
  124. for fixit in fixit_completion:
  125. vimsupport.ReplaceChunks( fixit[ 'chunks' ], silent=True )
  126. def _GetRequiredNamespaceImport( completion ):
  127. if ( 'extra_data' not in completion
  128. or 'required_namespace_import' not in completion[ 'extra_data' ] ):
  129. return None
  130. return completion[ 'extra_data' ][ 'required_namespace_import' ]
  131. def _GetFixItCompletion( completion ):
  132. if ( 'extra_data' not in completion
  133. or 'fixits' not in completion[ 'extra_data' ] ):
  134. return None
  135. return completion[ 'extra_data' ][ 'fixits' ]
  136. def _FilterToMatchingCompletions( completed_item, completions ):
  137. """Filter to completions matching the item Vim said was completed"""
  138. match_keys = [ 'word', 'abbr', 'menu', 'info' ]
  139. matched_completions = []
  140. for index, completion in enumerate( completions ):
  141. item = _ConvertCompletionDataToVimData( index, completion )
  142. def matcher( key ):
  143. return ( ToUnicode( completed_item.get( key, "" ) ) ==
  144. ToUnicode( item.get( key, "" ) ) )
  145. if all( matcher( i ) for i in match_keys ):
  146. matched_completions.append( completion )
  147. return matched_completions
  148. def _ConvertCompletionDataToVimData( completion_identifier, completion_data ):
  149. # see :h complete-items for a description of the dictionary fields
  150. vim_data = {
  151. 'word' : '',
  152. 'dup' : 1,
  153. 'empty' : 1,
  154. }
  155. if ( 'extra_data' in completion_data and
  156. 'doc_string' in completion_data[ 'extra_data' ] ):
  157. doc_string = completion_data[ 'extra_data' ][ 'doc_string' ]
  158. else:
  159. doc_string = ""
  160. if 'insertion_text' in completion_data:
  161. vim_data[ 'word' ] = completion_data[ 'insertion_text' ]
  162. if 'menu_text' in completion_data:
  163. vim_data[ 'abbr' ] = completion_data[ 'menu_text' ]
  164. if 'extra_menu_info' in completion_data:
  165. vim_data[ 'menu' ] = completion_data[ 'extra_menu_info' ]
  166. if 'kind' in completion_data:
  167. kind = ToUnicode( completion_data[ 'kind' ] )
  168. if kind:
  169. vim_data[ 'kind' ] = kind[ 0 ].lower()
  170. if 'detailed_info' in completion_data:
  171. vim_data[ 'info' ] = completion_data[ 'detailed_info' ]
  172. if doc_string:
  173. vim_data[ 'info' ] += '\n' + doc_string
  174. elif doc_string:
  175. vim_data[ 'info' ] = doc_string
  176. # We store the completion item index as a string in the completion user_data.
  177. # This allows us to identify the _exact_ item that was completed in the
  178. # CompleteDone handler, by inspecting this item from v:completed_item
  179. #
  180. # We convert to string because completion user data items must be strings.
  181. #
  182. # Note: Not all versions of Vim support this (added in 8.0.1483), but adding
  183. # the item to the dictionary is harmless in earlier Vims.
  184. vim_data[ 'user_data' ] = str( completion_identifier )
  185. return vim_data
  186. def _ConvertCompletionDatasToVimDatas( response_data ):
  187. return [ _ConvertCompletionDataToVimData( i, x )
  188. for i, x in enumerate( response_data ) ]