youcompleteme.py 33 KB

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