completion_request.py 7.8 KB

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