youcompleteme.py 29 KB

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