youcompleteme.py 33 KB

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