completion_request.py 8.3 KB

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