completion_request.py 8.0 KB

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