youcompleteme.py 29 KB

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