youcompleteme.py 29 KB

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