youcompleteme.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. # Copyright (C) 2011-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. from future.utils import iteritems
  24. import base64
  25. import json
  26. import logging
  27. import os
  28. import signal
  29. import vim
  30. from subprocess import PIPE
  31. from tempfile import NamedTemporaryFile
  32. from ycm import base, paths, vimsupport
  33. from ycm.buffer import ( BufferDict,
  34. DIAGNOSTIC_UI_FILETYPES,
  35. DIAGNOSTIC_UI_ASYNC_FILETYPES )
  36. from ycmd import utils
  37. from ycmd import server_utils
  38. from ycmd.request_wrap import RequestWrap
  39. from ycm.omni_completer import OmniCompleter
  40. from ycm import syntax_parse
  41. from ycm.client.ycmd_keepalive import YcmdKeepalive
  42. from ycm.client.base_request import ( BaseRequest, BuildRequestData,
  43. HandleServerException )
  44. from ycm.client.completer_available_request import SendCompleterAvailableRequest
  45. from ycm.client.command_request import SendCommandRequest
  46. from ycm.client.completion_request import ( CompletionRequest,
  47. ConvertCompletionDataToVimData )
  48. from ycm.client.debug_info_request import ( SendDebugInfoRequest,
  49. FormatDebugInfoResponse )
  50. from ycm.client.omni_completion_request import OmniCompletionRequest
  51. from ycm.client.event_notification import SendEventNotificationAsync
  52. from ycm.client.shutdown_request import SendShutdownRequest
  53. from ycm.client.messages_request import MessagesPoll
  54. def PatchNoProxy():
  55. current_value = os.environ.get('no_proxy', '')
  56. additions = '127.0.0.1,localhost'
  57. os.environ['no_proxy'] = ( additions if not current_value
  58. else current_value + ',' + additions )
  59. # We need this so that Requests doesn't end up using the local HTTP proxy when
  60. # talking to ycmd. Users should actually be setting this themselves when
  61. # configuring a proxy server on their machine, but most don't know they need to
  62. # or how to do it, so we do it for them.
  63. # Relevant issues:
  64. # https://github.com/Valloric/YouCompleteMe/issues/641
  65. # https://github.com/kennethreitz/requests/issues/879
  66. PatchNoProxy()
  67. # Force the Python interpreter embedded in Vim (in which we are running) to
  68. # ignore the SIGINT signal. This helps reduce the fallout of a user pressing
  69. # Ctrl-C in Vim.
  70. signal.signal( signal.SIGINT, signal.SIG_IGN )
  71. HMAC_SECRET_LENGTH = 16
  72. SERVER_SHUTDOWN_MESSAGE = (
  73. "The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." )
  74. EXIT_CODE_UNEXPECTED_MESSAGE = (
  75. "Unexpected exit code {code}. "
  76. "Type ':YcmToggleLogs {logfile}' to check the logs." )
  77. CORE_UNEXPECTED_MESSAGE = (
  78. "Unexpected error while loading the YCM core library. "
  79. "Type ':YcmToggleLogs {logfile}' to check the logs." )
  80. CORE_MISSING_MESSAGE = (
  81. 'YCM core library not detected; you need to compile YCM before using it. '
  82. 'Follow the instructions in the documentation.' )
  83. CORE_PYTHON2_MESSAGE = (
  84. "YCM core library compiled for Python 2 but loaded in Python 3. "
  85. "Set the 'g:ycm_server_python_interpreter' option to a Python 2 "
  86. "interpreter path." )
  87. CORE_PYTHON3_MESSAGE = (
  88. "YCM core library compiled for Python 3 but loaded in Python 2. "
  89. "Set the 'g:ycm_server_python_interpreter' option to a Python 3 "
  90. "interpreter path." )
  91. CORE_OUTDATED_MESSAGE = (
  92. 'YCM core library too old; PLEASE RECOMPILE by running the install.py '
  93. 'script. See the documentation for more details.' )
  94. SERVER_IDLE_SUICIDE_SECONDS = 1800 # 30 minutes
  95. CLIENT_LOGFILE_FORMAT = 'ycm_'
  96. SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'
  97. # Flag to set a file handle inheritable by child processes on Windows. See
  98. # https://msdn.microsoft.com/en-us/library/ms724935.aspx
  99. HANDLE_FLAG_INHERIT = 0x00000001
  100. # The following two methods exist for testability only
  101. def _CompleteDoneHook_CSharp( ycm ):
  102. ycm._OnCompleteDone_Csharp()
  103. def _CompleteDoneHook_Java( ycm ):
  104. ycm._OnCompleteDone_Java()
  105. class YouCompleteMe( object ):
  106. def __init__( self, user_options ):
  107. self._available_completers = {}
  108. self._user_options = user_options
  109. self._user_notified_about_crash = False
  110. self._omnicomp = OmniCompleter( user_options )
  111. self._buffers = BufferDict( user_options )
  112. self._latest_completion_request = None
  113. self._logger = logging.getLogger( 'ycm' )
  114. self._client_logfile = None
  115. self._server_stdout = None
  116. self._server_stderr = None
  117. self._server_popen = None
  118. self._filetypes_with_keywords_loaded = set()
  119. self._ycmd_keepalive = YcmdKeepalive()
  120. self._server_is_ready_with_cache = False
  121. self._SetUpLogging()
  122. self._SetUpServer()
  123. self._ycmd_keepalive.Start()
  124. self._complete_done_hooks = {
  125. 'cs': _CompleteDoneHook_CSharp,
  126. 'java': _CompleteDoneHook_Java,
  127. }
  128. def _SetUpServer( self ):
  129. self._available_completers = {}
  130. self._user_notified_about_crash = False
  131. self._filetypes_with_keywords_loaded = set()
  132. self._server_is_ready_with_cache = False
  133. self._message_poll_request = None
  134. hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
  135. options_dict = dict( self._user_options )
  136. options_dict[ 'hmac_secret' ] = utils.ToUnicode(
  137. base64.b64encode( hmac_secret ) )
  138. options_dict[ 'server_keep_logfiles' ] = self._user_options[
  139. 'keep_logfiles' ]
  140. # The temp options file is deleted by ycmd during startup.
  141. with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
  142. json.dump( options_dict, options_file )
  143. server_port = utils.GetUnusedLocalhostPort()
  144. BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
  145. BaseRequest.hmac_secret = hmac_secret
  146. try:
  147. python_interpreter = paths.PathToPythonInterpreter()
  148. except RuntimeError as error:
  149. error_message = (
  150. "Unable to start the ycmd server. {0}. "
  151. "Correct the error then restart the server "
  152. "with ':YcmRestartServer'.".format( str( error ).rstrip( '.' ) ) )
  153. self._logger.exception( error_message )
  154. vimsupport.PostVimMessage( error_message )
  155. return
  156. args = [ python_interpreter,
  157. paths.PathToServerScript(),
  158. '--port={0}'.format( server_port ),
  159. '--options_file={0}'.format( options_file.name ),
  160. '--log={0}'.format( self._user_options[ 'log_level' ] ),
  161. '--idle_suicide_seconds={0}'.format(
  162. SERVER_IDLE_SUICIDE_SECONDS ) ]
  163. self._server_stdout = utils.CreateLogfile(
  164. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
  165. self._server_stderr = utils.CreateLogfile(
  166. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
  167. args.append( '--stdout={0}'.format( self._server_stdout ) )
  168. args.append( '--stderr={0}'.format( self._server_stderr ) )
  169. if self._user_options[ 'keep_logfiles' ]:
  170. args.append( '--keep_logfiles' )
  171. self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
  172. stdout = PIPE, stderr = PIPE )
  173. def _SetUpLogging( self ):
  174. def FreeFileFromOtherProcesses( file_object ):
  175. if utils.OnWindows():
  176. from ctypes import windll
  177. import msvcrt
  178. file_handle = msvcrt.get_osfhandle( file_object.fileno() )
  179. windll.kernel32.SetHandleInformation( file_handle,
  180. HANDLE_FLAG_INHERIT,
  181. 0 )
  182. self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
  183. log_level = self._user_options[ 'log_level' ]
  184. numeric_level = getattr( logging, log_level.upper(), None )
  185. if not isinstance( numeric_level, int ):
  186. raise ValueError( 'Invalid log level: {0}'.format( log_level ) )
  187. self._logger.setLevel( numeric_level )
  188. handler = logging.FileHandler( self._client_logfile )
  189. # On Windows and Python prior to 3.4, file handles are inherited by child
  190. # processes started with at least one replaced standard stream, which is the
  191. # case when we start the ycmd server (we are redirecting all standard
  192. # outputs into a pipe). These files cannot be removed while the child
  193. # processes are still up. This is not desirable for a logfile because we
  194. # want to remove it at Vim exit without having to wait for the ycmd server
  195. # to be completely shut down. We need to make the logfile handle
  196. # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
  197. # details.
  198. FreeFileFromOtherProcesses( handler.stream )
  199. formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
  200. handler.setFormatter( formatter )
  201. self._logger.addHandler( handler )
  202. def IsServerAlive( self ):
  203. # When the process hasn't finished yet, poll() returns None.
  204. return bool( self._server_popen ) and self._server_popen.poll() is None
  205. def CheckIfServerIsReady( self ):
  206. if not self._server_is_ready_with_cache:
  207. with HandleServerException( display = False ):
  208. self._server_is_ready_with_cache = BaseRequest.GetDataFromHandler(
  209. 'ready' )
  210. return self._server_is_ready_with_cache
  211. def IsServerReady( self ):
  212. return self._server_is_ready_with_cache
  213. def NotifyUserIfServerCrashed( self ):
  214. if ( not self._server_popen or self._user_notified_about_crash or
  215. self.IsServerAlive() ):
  216. return
  217. self._user_notified_about_crash = True
  218. return_code = self._server_popen.poll()
  219. logfile = os.path.basename( self._server_stderr )
  220. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  221. error_message = CORE_UNEXPECTED_MESSAGE.format(
  222. logfile = logfile )
  223. elif return_code == server_utils.CORE_MISSING_STATUS:
  224. error_message = CORE_MISSING_MESSAGE
  225. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  226. error_message = CORE_PYTHON2_MESSAGE
  227. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  228. error_message = CORE_PYTHON3_MESSAGE
  229. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  230. error_message = CORE_OUTDATED_MESSAGE
  231. else:
  232. error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format(
  233. code = return_code,
  234. logfile = logfile )
  235. error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
  236. self._logger.error( error_message )
  237. vimsupport.PostVimMessage( error_message )
  238. def ServerPid( self ):
  239. if not self._server_popen:
  240. return -1
  241. return self._server_popen.pid
  242. def _ShutdownServer( self ):
  243. SendShutdownRequest()
  244. def RestartServer( self ):
  245. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  246. self._ShutdownServer()
  247. self._SetUpServer()
  248. def SendCompletionRequest( self, force_semantic = False ):
  249. request_data = BuildRequestData()
  250. request_data[ 'force_semantic' ] = force_semantic
  251. if not self.NativeFiletypeCompletionUsable():
  252. wrapped_request_data = RequestWrap( request_data )
  253. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  254. self._latest_completion_request = OmniCompletionRequest(
  255. self._omnicomp, wrapped_request_data )
  256. self._latest_completion_request.Start()
  257. return
  258. self._AddExtraConfDataIfNeeded( request_data )
  259. self._latest_completion_request = CompletionRequest( request_data )
  260. self._latest_completion_request.Start()
  261. def CompletionRequestReady( self ):
  262. return bool( self._latest_completion_request and
  263. self._latest_completion_request.Done() )
  264. def GetCompletionResponse( self ):
  265. response = self._latest_completion_request.Response()
  266. response[ 'completions' ] = base.AdjustCandidateInsertionText(
  267. response[ 'completions' ] )
  268. return response
  269. def SendCommandRequest( self,
  270. arguments,
  271. completer,
  272. has_range,
  273. start_line,
  274. end_line ):
  275. extra_data = {
  276. 'options': {
  277. 'tab_size': vimsupport.GetIntValue( 'shiftwidth()' ),
  278. 'insert_spaces': vimsupport.GetBoolValue( '&expandtab' )
  279. }
  280. }
  281. if has_range:
  282. extra_data.update( vimsupport.BuildRange( start_line, end_line ) )
  283. self._AddExtraConfDataIfNeeded( extra_data )
  284. return SendCommandRequest( arguments, completer, extra_data )
  285. def GetDefinedSubcommands( self ):
  286. with HandleServerException():
  287. return BaseRequest.PostDataToHandler( BuildRequestData(),
  288. 'defined_subcommands' )
  289. return []
  290. def GetCurrentCompletionRequest( self ):
  291. return self._latest_completion_request
  292. def GetOmniCompleter( self ):
  293. return self._omnicomp
  294. def FiletypeCompleterExistsForFiletype( self, filetype ):
  295. try:
  296. return self._available_completers[ filetype ]
  297. except KeyError:
  298. pass
  299. exists_completer = SendCompleterAvailableRequest( filetype )
  300. if exists_completer is None:
  301. return False
  302. self._available_completers[ filetype ] = exists_completer
  303. return exists_completer
  304. def NativeFiletypeCompletionAvailable( self ):
  305. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  306. vimsupport.CurrentFiletypes() ] )
  307. def NativeFiletypeCompletionUsable( self ):
  308. disabled_filetypes = self._user_options[
  309. 'filetype_specific_completion_to_disable' ]
  310. return ( vimsupport.CurrentFiletypesEnabled( disabled_filetypes ) and
  311. self.NativeFiletypeCompletionAvailable() )
  312. def NeedsReparse( self ):
  313. return self.CurrentBuffer().NeedsReparse()
  314. def UpdateWithNewDiagnosticsForFile( self, filepath, diagnostics ):
  315. bufnr = vimsupport.GetBufferNumberForFilename( filepath )
  316. if bufnr in self._buffers and vimsupport.BufferIsVisible( bufnr ):
  317. # Note: We only update location lists, etc. for visible buffers, because
  318. # otherwise we defualt to using the curren location list and the results
  319. # are that non-visible buffer errors clobber visible ones.
  320. self._buffers[ bufnr ].UpdateWithNewDiagnostics( diagnostics )
  321. else:
  322. # The project contains errors in file "filepath", but that file is not
  323. # open in any buffer. This happens for Language Server Protocol-based
  324. # completers, as they return diagnostics for the entire "project"
  325. # asynchronously (rather than per-file in the response to the parse
  326. # request).
  327. #
  328. # There are a number of possible approaches for
  329. # this, but for now we simply ignore them. Other options include:
  330. # - Use the QuickFix list to report project errors?
  331. # - Use a special buffer for project errors
  332. # - Put them in the location list of whatever the "current" buffer is
  333. # - Store them in case the buffer is opened later
  334. # - add a :YcmProjectDiags command
  335. # - Add them to errror/warning _counts_ but not any actual location list
  336. # or other
  337. # - etc.
  338. #
  339. # However, none of those options are great, and lead to their own
  340. # complexities. So for now, we just ignore these diagnostics for files not
  341. # open in any buffer.
  342. pass
  343. def OnPeriodicTick( self ):
  344. if not self.IsServerAlive():
  345. # Server has died. We'll reset when the server is started again.
  346. return False
  347. elif not self.IsServerReady():
  348. # Try again in a jiffy
  349. return True
  350. if not self._message_poll_request:
  351. self._message_poll_request = MessagesPoll()
  352. if not self._message_poll_request.Poll( self ):
  353. # Don't poll again until some event which might change the server's mind
  354. # about whether to provide messages for the current buffer (e.g. buffer
  355. # visit, file ready to parse, etc.)
  356. self._message_poll_request = None
  357. return False
  358. # Poll again in a jiffy
  359. return True
  360. def OnFileReadyToParse( self ):
  361. if not self.IsServerAlive():
  362. self.NotifyUserIfServerCrashed()
  363. return
  364. if not self.IsServerReady():
  365. return
  366. extra_data = {}
  367. self._AddTagsFilesIfNeeded( extra_data )
  368. self._AddSyntaxDataIfNeeded( extra_data )
  369. self._AddExtraConfDataIfNeeded( extra_data )
  370. self.CurrentBuffer().SendParseRequest( extra_data )
  371. def OnBufferUnload( self, deleted_buffer_number ):
  372. SendEventNotificationAsync( 'BufferUnload', deleted_buffer_number )
  373. def UpdateMatches( self ):
  374. self.CurrentBuffer().UpdateMatches()
  375. def OnBufferVisit( self ):
  376. extra_data = {}
  377. self._AddUltiSnipsDataIfNeeded( extra_data )
  378. SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
  379. def CurrentBuffer( self ):
  380. return self._buffers[ vimsupport.GetCurrentBufferNumber() ]
  381. def OnInsertLeave( self ):
  382. SendEventNotificationAsync( 'InsertLeave' )
  383. def OnCursorMoved( self ):
  384. self.CurrentBuffer().OnCursorMoved()
  385. def _CleanLogfile( self ):
  386. logging.shutdown()
  387. if not self._user_options[ 'keep_logfiles' ]:
  388. if self._client_logfile:
  389. utils.RemoveIfExists( self._client_logfile )
  390. def OnVimLeave( self ):
  391. self._ShutdownServer()
  392. self._CleanLogfile()
  393. def OnCurrentIdentifierFinished( self ):
  394. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  395. def OnCompleteDone( self ):
  396. complete_done_actions = self.GetCompleteDoneHooks()
  397. for action in complete_done_actions:
  398. action(self)
  399. def GetCompleteDoneHooks( self ):
  400. filetypes = vimsupport.CurrentFiletypes()
  401. for key, value in iteritems( self._complete_done_hooks ):
  402. if key in filetypes:
  403. yield value
  404. def GetCompletionsUserMayHaveCompleted( self ):
  405. latest_completion_request = self.GetCurrentCompletionRequest()
  406. if not latest_completion_request or not latest_completion_request.Done():
  407. return []
  408. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  409. completions = latest_completion_request.RawResponse()[ 'completions' ]
  410. if 'user_data' in completed_item and completed_item[ 'user_data' ] != '':
  411. # Vim supports user_data (8.0.1493) or later, so we actually know the
  412. # _exact_ element that was selected, having put its index in the user_data
  413. # field.
  414. return [ completions[ int( completed_item[ 'user_data' ] ) ] ]
  415. # Otherwise, we have to guess by matching the values in the completed item
  416. # and the list of completions. Sometimes this returns multiple
  417. # possibilities, which is essentially unresolvable.
  418. result = self._FilterToMatchingCompletions( completed_item,
  419. completions,
  420. True )
  421. result = list( result )
  422. if result:
  423. return result
  424. if self._HasCompletionsThatCouldBeCompletedWithMoreText( completed_item,
  425. completions ):
  426. # Since the way that YCM works leads to CompleteDone called on every
  427. # character, return blank if the completion might not be done. This won't
  428. # match if the completion is ended with typing a non-keyword character.
  429. return []
  430. result = self._FilterToMatchingCompletions( completed_item,
  431. completions,
  432. False )
  433. return list( result )
  434. def _FilterToMatchingCompletions( self,
  435. completed_item,
  436. completions,
  437. full_match_only ):
  438. """Filter to completions matching the item Vim said was completed"""
  439. match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only
  440. else [ 'word' ] )
  441. for index, completion in enumerate( completions ):
  442. item = ConvertCompletionDataToVimData( index, completion )
  443. def matcher( key ):
  444. return ( utils.ToUnicode( completed_item.get( key, "" ) ) ==
  445. utils.ToUnicode( item.get( key, "" ) ) )
  446. if all( [ matcher( i ) for i in match_keys ] ):
  447. yield completion
  448. def _HasCompletionsThatCouldBeCompletedWithMoreText( self,
  449. completed_item,
  450. completions ):
  451. if not completed_item:
  452. return False
  453. completed_word = utils.ToUnicode( completed_item[ 'word' ] )
  454. if not completed_word:
  455. return False
  456. # Sometimes CompleteDone is called after the next character is inserted.
  457. # If so, use inserted character to filter possible completions further.
  458. text = vimsupport.TextBeforeCursor()
  459. reject_exact_match = True
  460. if text and text[ -1 ] != completed_word[ -1 ]:
  461. reject_exact_match = False
  462. completed_word += text[ -1 ]
  463. for index, completion in enumerate( completions ):
  464. word = utils.ToUnicode(
  465. ConvertCompletionDataToVimData( index, completion )[ 'word' ] )
  466. if reject_exact_match and word == completed_word:
  467. continue
  468. if word.startswith( completed_word ):
  469. return True
  470. return False
  471. def _OnCompleteDone_Csharp( self ):
  472. completions = self.GetCompletionsUserMayHaveCompleted()
  473. namespaces = [ self._GetRequiredNamespaceImport( c )
  474. for c in completions ]
  475. namespaces = [ n for n in namespaces if n ]
  476. if not namespaces:
  477. return
  478. if len( namespaces ) > 1:
  479. choices = [ "{0} {1}".format( i + 1, n )
  480. for i, n in enumerate( namespaces ) ]
  481. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  482. if choice < 0:
  483. return
  484. namespace = namespaces[ choice ]
  485. else:
  486. namespace = namespaces[ 0 ]
  487. vimsupport.InsertNamespace( namespace )
  488. def _GetRequiredNamespaceImport( self, completion ):
  489. if ( "extra_data" not in completion
  490. or "required_namespace_import" not in completion[ "extra_data" ] ):
  491. return None
  492. return completion[ "extra_data" ][ "required_namespace_import" ]
  493. def _OnCompleteDone_Java( self ):
  494. completions = self.GetCompletionsUserMayHaveCompleted()
  495. fixit_completions = [ self._GetFixItCompletion( c ) for c in completions ]
  496. fixit_completions = [ f for f in fixit_completions if f ]
  497. if not fixit_completions:
  498. return
  499. # If we have user_data in completions (8.0.1493 or later), then we would
  500. # only ever return max. 1 completion here. However, if we had to guess, it
  501. # is possible that we matched multiple completion items (e.g. for overloads,
  502. # or similar classes in multiple packages). In any case, rather than
  503. # prompting the user and disturbing her workflow, we just apply the first
  504. # one. This might be wrong, but the solution is to use a (very) new version
  505. # of Vim which supports user_data on completion items
  506. fixit_completion = fixit_completions[ 0 ]
  507. for fixit in fixit_completion:
  508. vimsupport.ReplaceChunks( fixit[ 'chunks' ], silent=True )
  509. def _GetFixItCompletion( self, completion ):
  510. if ( "extra_data" not in completion
  511. or "fixits" not in completion[ "extra_data" ] ):
  512. return None
  513. return completion[ "extra_data" ][ "fixits" ]
  514. def GetErrorCount( self ):
  515. return self.CurrentBuffer().GetErrorCount()
  516. def GetWarningCount( self ):
  517. return self.CurrentBuffer().GetWarningCount()
  518. def DiagnosticUiSupportedForCurrentFiletype( self ):
  519. return any( [ x in DIAGNOSTIC_UI_FILETYPES or
  520. x in DIAGNOSTIC_UI_ASYNC_FILETYPES
  521. for x in vimsupport.CurrentFiletypes() ] )
  522. def ShouldDisplayDiagnostics( self ):
  523. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  524. self.DiagnosticUiSupportedForCurrentFiletype() )
  525. def _PopulateLocationListWithLatestDiagnostics( self ):
  526. return self.CurrentBuffer().PopulateLocationList()
  527. def FileParseRequestReady( self ):
  528. # Return True if server is not ready yet, to stop repeating check timer.
  529. return ( not self.IsServerReady() or
  530. self.CurrentBuffer().FileParseRequestReady() )
  531. def HandleFileParseRequest( self, block = False ):
  532. if not self.IsServerReady():
  533. return
  534. current_buffer = self.CurrentBuffer()
  535. # Order is important here:
  536. # FileParseRequestReady has a low cost, while
  537. # NativeFiletypeCompletionUsable is a blocking server request
  538. if ( not current_buffer.IsResponseHandled() and
  539. current_buffer.FileParseRequestReady( block ) and
  540. self.NativeFiletypeCompletionUsable() ):
  541. if self.ShouldDisplayDiagnostics():
  542. # Forcefuly update the location list, etc. from the parse request when
  543. # doing something like :YcmDiags
  544. current_buffer.UpdateDiagnostics( block is True )
  545. else:
  546. # YCM client has a hard-coded list of filetypes which are known
  547. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  548. #
  549. # For filetypes which don't support diagnostics, we just want to check
  550. # the _latest_file_parse_request for any exception or UnknownExtraConf
  551. # response, to allow the server to raise configuration warnings, etc.
  552. # to the user. We ignore any other supplied data.
  553. current_buffer.GetResponse()
  554. # We set the file parse request as handled because we want to prevent
  555. # repeated issuing of the same warnings/errors/prompts. Setting this
  556. # makes IsRequestHandled return True until the next request is created.
  557. #
  558. # Note: it is the server's responsibility to determine the frequency of
  559. # error/warning/prompts when receiving a FileReadyToParse event, but
  560. # it is our responsibility to ensure that we only apply the
  561. # warning/error/prompt received once (for each event).
  562. current_buffer.MarkResponseHandled()
  563. def DebugInfo( self ):
  564. debug_info = ''
  565. if self._client_logfile:
  566. debug_info += 'Client logfile: {0}\n'.format( self._client_logfile )
  567. extra_data = {}
  568. self._AddExtraConfDataIfNeeded( extra_data )
  569. debug_info += FormatDebugInfoResponse( SendDebugInfoRequest( extra_data ) )
  570. debug_info += 'Server running at: {0}\n'.format(
  571. BaseRequest.server_location )
  572. if self._server_popen:
  573. debug_info += 'Server process ID: {0}\n'.format( self._server_popen.pid )
  574. if self._server_stdout and self._server_stderr:
  575. debug_info += ( 'Server logfiles:\n'
  576. ' {0}\n'
  577. ' {1}'.format( self._server_stdout,
  578. self._server_stderr ) )
  579. return debug_info
  580. def GetLogfiles( self ):
  581. logfiles_list = [ self._client_logfile,
  582. self._server_stdout,
  583. self._server_stderr ]
  584. debug_info = SendDebugInfoRequest()
  585. if debug_info:
  586. completer = debug_info[ 'completer' ]
  587. if completer:
  588. for server in completer[ 'servers' ]:
  589. logfiles_list.extend( server[ 'logfiles' ] )
  590. logfiles = {}
  591. for logfile in logfiles_list:
  592. logfiles[ os.path.basename( logfile ) ] = logfile
  593. return logfiles
  594. def _OpenLogfile( self, logfile ):
  595. # Open log files in a horizontal window with the same behavior as the
  596. # preview window (same height and winfixheight enabled). Automatically
  597. # watch for changes. Set the cursor position at the end of the file.
  598. options = {
  599. 'size': vimsupport.GetIntValue( '&previewheight' ),
  600. 'fix': True,
  601. 'focus': False,
  602. 'watch': True,
  603. 'position': 'end'
  604. }
  605. vimsupport.OpenFilename( logfile, options )
  606. def _CloseLogfile( self, logfile ):
  607. vimsupport.CloseBuffersForFilename( logfile )
  608. def ToggleLogs( self, *filenames ):
  609. logfiles = self.GetLogfiles()
  610. if not filenames:
  611. sorted_logfiles = sorted( list( logfiles ) )
  612. try:
  613. logfile_index = vimsupport.SelectFromList(
  614. 'Which logfile do you wish to open (or close if already open)?',
  615. sorted_logfiles )
  616. except RuntimeError as e:
  617. vimsupport.PostVimMessage( str( e ) )
  618. return
  619. logfile = logfiles[ sorted_logfiles[ logfile_index ] ]
  620. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  621. self._OpenLogfile( logfile )
  622. else:
  623. self._CloseLogfile( logfile )
  624. return
  625. for filename in set( filenames ):
  626. if filename not in logfiles:
  627. continue
  628. logfile = logfiles[ filename ]
  629. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  630. self._OpenLogfile( logfile )
  631. continue
  632. self._CloseLogfile( logfile )
  633. def ShowDetailedDiagnostic( self ):
  634. with HandleServerException():
  635. detailed_diagnostic = BaseRequest.PostDataToHandler(
  636. BuildRequestData(), 'detailed_diagnostic' )
  637. if 'message' in detailed_diagnostic:
  638. vimsupport.PostVimMessage( detailed_diagnostic[ 'message' ],
  639. warning = False )
  640. def ForceCompileAndDiagnostics( self ):
  641. if not self.NativeFiletypeCompletionUsable():
  642. vimsupport.PostVimMessage(
  643. 'Native filetype completion not supported for current file, '
  644. 'cannot force recompilation.', warning = False )
  645. return False
  646. vimsupport.PostVimMessage(
  647. 'Forcing compilation, this will block Vim until done.',
  648. warning = False )
  649. self.OnFileReadyToParse()
  650. self.HandleFileParseRequest( block = True )
  651. vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
  652. return True
  653. def ShowDiagnostics( self ):
  654. if not self.ForceCompileAndDiagnostics():
  655. return
  656. if not self._PopulateLocationListWithLatestDiagnostics():
  657. vimsupport.PostVimMessage( 'No warnings or errors detected.',
  658. warning = False )
  659. return
  660. if self._user_options[ 'open_loclist_on_ycm_diags' ]:
  661. vimsupport.OpenLocationList( focus = True )
  662. def _AddSyntaxDataIfNeeded( self, extra_data ):
  663. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  664. return
  665. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  666. if filetype in self._filetypes_with_keywords_loaded:
  667. return
  668. if self.IsServerReady():
  669. self._filetypes_with_keywords_loaded.add( filetype )
  670. extra_data[ 'syntax_keywords' ] = list(
  671. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  672. def _AddTagsFilesIfNeeded( self, extra_data ):
  673. def GetTagFiles():
  674. tag_files = vim.eval( 'tagfiles()' )
  675. return [ os.path.join( utils.GetCurrentDirectory(), tag_file )
  676. for tag_file in tag_files ]
  677. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  678. return
  679. extra_data[ 'tag_files' ] = GetTagFiles()
  680. def _AddExtraConfDataIfNeeded( self, extra_data ):
  681. def BuildExtraConfData( extra_conf_vim_data ):
  682. extra_conf_data = {}
  683. for expr in extra_conf_vim_data:
  684. try:
  685. extra_conf_data[ expr ] = vimsupport.VimExpressionToPythonType( expr )
  686. except vim.error:
  687. message = (
  688. "Error evaluating '{expr}' in the 'g:ycm_extra_conf_vim_data' "
  689. "option.".format( expr = expr ) )
  690. vimsupport.PostVimMessage( message, truncate = True )
  691. self._logger.exception( message )
  692. return extra_conf_data
  693. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  694. if extra_conf_vim_data:
  695. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  696. extra_conf_vim_data )
  697. def _AddUltiSnipsDataIfNeeded( self, extra_data ):
  698. # See :h UltiSnips#SnippetsInCurrentScope.
  699. try:
  700. vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
  701. except vim.error:
  702. return
  703. snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
  704. extra_data[ 'ultisnips_snippets' ] = [
  705. { 'trigger': trigger,
  706. 'description': snippet[ 'description' ] }
  707. for trigger, snippet in iteritems( snippets )
  708. ]