youcompleteme.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. # Copyright (C) 2011-2012 Google Inc.
  2. # 2016-2017 YouCompleteMe contributors
  3. #
  4. # This file is part of YouCompleteMe.
  5. #
  6. # YouCompleteMe is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # YouCompleteMe is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  18. from __future__ import unicode_literals
  19. from __future__ import print_function
  20. from __future__ import division
  21. from __future__ import absolute_import
  22. # Not installing aliases from python-future; it's unreliable and slow.
  23. from builtins import * # noqa
  24. from future.utils import iteritems
  25. import base64
  26. import json
  27. import logging
  28. import os
  29. import signal
  30. import vim
  31. from subprocess import PIPE
  32. from tempfile import NamedTemporaryFile
  33. from ycm import base, paths, vimsupport
  34. from ycmd import utils
  35. from ycmd import server_utils
  36. from ycmd.request_wrap import RequestWrap
  37. from ycm.diagnostic_interface import DiagnosticInterface
  38. from ycm.omni_completer import OmniCompleter
  39. from ycm import syntax_parse
  40. from ycm.client.ycmd_keepalive import YcmdKeepalive
  41. from ycm.client.base_request import ( BaseRequest, BuildRequestData,
  42. HandleServerException )
  43. from ycm.client.completer_available_request import SendCompleterAvailableRequest
  44. from ycm.client.command_request import SendCommandRequest
  45. from ycm.client.completion_request import ( CompletionRequest,
  46. ConvertCompletionDataToVimData )
  47. from ycm.client.debug_info_request import ( SendDebugInfoRequest,
  48. FormatDebugInfoResponse )
  49. from ycm.client.omni_completion_request import OmniCompletionRequest
  50. from ycm.client.event_notification import ( SendEventNotificationAsync,
  51. EventNotification )
  52. from ycm.client.shutdown_request import SendShutdownRequest
  53. def PatchNoProxy():
  54. current_value = os.environ.get('no_proxy', '')
  55. additions = '127.0.0.1,localhost'
  56. os.environ['no_proxy'] = ( additions if not current_value
  57. else current_value + ',' + additions )
  58. # We need this so that Requests doesn't end up using the local HTTP proxy when
  59. # talking to ycmd. Users should actually be setting this themselves when
  60. # configuring a proxy server on their machine, but most don't know they need to
  61. # or how to do it, so we do it for them.
  62. # Relevant issues:
  63. # https://github.com/Valloric/YouCompleteMe/issues/641
  64. # https://github.com/kennethreitz/requests/issues/879
  65. PatchNoProxy()
  66. # Force the Python interpreter embedded in Vim (in which we are running) to
  67. # ignore the SIGINT signal. This helps reduce the fallout of a user pressing
  68. # Ctrl-C in Vim.
  69. signal.signal( signal.SIGINT, signal.SIG_IGN )
  70. HMAC_SECRET_LENGTH = 16
  71. SERVER_SHUTDOWN_MESSAGE = (
  72. "The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." )
  73. EXIT_CODE_UNEXPECTED_MESSAGE = (
  74. "Unexpected exit code {code}. "
  75. "Use the ':YcmToggleLogs' command to check the logs." )
  76. CORE_UNEXPECTED_MESSAGE = (
  77. "Unexpected error while loading the YCM core library. "
  78. "Use the ':YcmToggleLogs' command to check the logs." )
  79. CORE_MISSING_MESSAGE = (
  80. 'YCM core library not detected; you need to compile YCM before using it. '
  81. 'Follow the instructions in the documentation.' )
  82. CORE_PYTHON2_MESSAGE = (
  83. "YCM core library compiled for Python 2 but loaded in Python 3. "
  84. "Set the 'g:ycm_server_python_interpreter' option to a Python 2 "
  85. "interpreter path." )
  86. CORE_PYTHON3_MESSAGE = (
  87. "YCM core library compiled for Python 3 but loaded in Python 2. "
  88. "Set the 'g:ycm_server_python_interpreter' option to a Python 3 "
  89. "interpreter path." )
  90. CORE_OUTDATED_MESSAGE = (
  91. 'YCM core library too old; PLEASE RECOMPILE by running the install.py '
  92. 'script. See the documentation for more details.' )
  93. SERVER_IDLE_SUICIDE_SECONDS = 1800 # 30 minutes
  94. DIAGNOSTIC_UI_FILETYPES = set( [ 'cpp', 'cs', 'c', 'objc', 'objcpp',
  95. 'typescript' ] )
  96. CLIENT_LOGFILE_FORMAT = 'ycm_'
  97. SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'
  98. # Flag to set a file handle inheritable by child processes on Windows. See
  99. # https://msdn.microsoft.com/en-us/library/ms724935.aspx
  100. HANDLE_FLAG_INHERIT = 0x00000001
  101. class YouCompleteMe( object ):
  102. def __init__( self, user_options ):
  103. self._available_completers = {}
  104. self._user_options = user_options
  105. self._user_notified_about_crash = False
  106. self._diag_interface = DiagnosticInterface( user_options )
  107. self._omnicomp = OmniCompleter( user_options )
  108. self._latest_file_parse_request = None
  109. self._latest_completion_request = None
  110. self._latest_diagnostics = []
  111. self._logger = logging.getLogger( 'ycm' )
  112. self._client_logfile = None
  113. self._server_stdout = None
  114. self._server_stderr = None
  115. self._server_popen = None
  116. self._filetypes_with_keywords_loaded = set()
  117. self._ycmd_keepalive = YcmdKeepalive()
  118. self._server_is_ready_with_cache = False
  119. self._SetupLogging()
  120. self._SetupServer()
  121. self._ycmd_keepalive.Start()
  122. self._complete_done_hooks = {
  123. 'cs': lambda self: self._OnCompleteDone_Csharp()
  124. }
  125. def _SetupServer( self ):
  126. self._available_completers = {}
  127. self._user_notified_about_crash = False
  128. self._filetypes_with_keywords_loaded = set()
  129. self._server_is_ready_with_cache = False
  130. server_port = utils.GetUnusedLocalhostPort()
  131. # The temp options file is deleted by ycmd during startup
  132. with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
  133. hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
  134. options_dict = dict( self._user_options )
  135. options_dict[ 'hmac_secret' ] = utils.ToUnicode(
  136. base64.b64encode( hmac_secret ) )
  137. options_dict[ 'server_keep_logfiles' ] = self._user_options[
  138. 'keep_logfiles' ]
  139. json.dump( options_dict, options_file )
  140. options_file.flush()
  141. args = [ paths.PathToPythonInterpreter(),
  142. paths.PathToServerScript(),
  143. '--port={0}'.format( server_port ),
  144. '--options_file={0}'.format( options_file.name ),
  145. '--log={0}'.format( self._user_options[ 'log_level' ] ),
  146. '--idle_suicide_seconds={0}'.format(
  147. SERVER_IDLE_SUICIDE_SECONDS ) ]
  148. self._server_stdout = utils.CreateLogfile(
  149. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
  150. self._server_stderr = utils.CreateLogfile(
  151. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
  152. args.append( '--stdout={0}'.format( self._server_stdout ) )
  153. args.append( '--stderr={0}'.format( self._server_stderr ) )
  154. if self._user_options[ 'keep_logfiles' ]:
  155. args.append( '--keep_logfiles' )
  156. self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
  157. stdout = PIPE, stderr = PIPE )
  158. BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
  159. BaseRequest.hmac_secret = hmac_secret
  160. self._NotifyUserIfServerCrashed()
  161. def _SetupLogging( self ):
  162. def FreeFileFromOtherProcesses( file_object ):
  163. if utils.OnWindows():
  164. from ctypes import windll
  165. import msvcrt
  166. file_handle = msvcrt.get_osfhandle( file_object.fileno() )
  167. windll.kernel32.SetHandleInformation( file_handle,
  168. HANDLE_FLAG_INHERIT,
  169. 0 )
  170. self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
  171. log_level = self._user_options[ 'log_level' ]
  172. numeric_level = getattr( logging, log_level.upper(), None )
  173. if not isinstance( numeric_level, int ):
  174. raise ValueError( 'Invalid log level: {0}'.format( log_level ) )
  175. self._logger.setLevel( numeric_level )
  176. handler = logging.FileHandler( self._client_logfile )
  177. # On Windows and Python prior to 3.4, file handles are inherited by child
  178. # processes started with at least one replaced standard stream, which is the
  179. # case when we start the ycmd server (we are redirecting all standard
  180. # outputs into a pipe). These files cannot be removed while the child
  181. # processes are still up. This is not desirable for a logfile because we
  182. # want to remove it at Vim exit without having to wait for the ycmd server
  183. # to be completely shut down. We need to make the logfile handle
  184. # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
  185. # details.
  186. FreeFileFromOtherProcesses( handler.stream )
  187. formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
  188. handler.setFormatter( formatter )
  189. self._logger.addHandler( handler )
  190. def IsServerAlive( self ):
  191. return_code = self._server_popen.poll()
  192. # When the process hasn't finished yet, poll() returns None.
  193. return return_code is None
  194. def IsServerReady( self ):
  195. if not self._server_is_ready_with_cache and self.IsServerAlive():
  196. with HandleServerException( display = False ):
  197. self._server_is_ready_with_cache = BaseRequest.GetDataFromHandler(
  198. 'ready' )
  199. return self._server_is_ready_with_cache
  200. def _NotifyUserIfServerCrashed( self ):
  201. if self._user_notified_about_crash or self.IsServerAlive():
  202. return
  203. self._user_notified_about_crash = True
  204. return_code = self._server_popen.poll()
  205. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  206. error_message = CORE_UNEXPECTED_MESSAGE
  207. elif return_code == server_utils.CORE_MISSING_STATUS:
  208. error_message = CORE_MISSING_MESSAGE
  209. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  210. error_message = CORE_PYTHON2_MESSAGE
  211. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  212. error_message = CORE_PYTHON3_MESSAGE
  213. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  214. error_message = CORE_OUTDATED_MESSAGE
  215. else:
  216. error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format( code = return_code )
  217. server_stderr = '\n'.join(
  218. utils.ToUnicode( self._server_popen.stderr.read() ).splitlines() )
  219. if server_stderr:
  220. self._logger.error( server_stderr )
  221. error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
  222. self._logger.error( error_message )
  223. vimsupport.PostVimMessage( error_message )
  224. def ServerPid( self ):
  225. if not self._server_popen:
  226. return -1
  227. return self._server_popen.pid
  228. def _ShutdownServer( self ):
  229. SendShutdownRequest()
  230. def RestartServer( self ):
  231. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  232. self._ShutdownServer()
  233. self._SetupServer()
  234. def CreateCompletionRequest( self, force_semantic = False ):
  235. request_data = BuildRequestData()
  236. if ( not self.NativeFiletypeCompletionAvailable() and
  237. self.CurrentFiletypeCompletionEnabled() ):
  238. wrapped_request_data = RequestWrap( request_data )
  239. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  240. self._latest_completion_request = OmniCompletionRequest(
  241. self._omnicomp, wrapped_request_data )
  242. return self._latest_completion_request
  243. request_data[ 'working_dir' ] = utils.GetCurrentDirectory()
  244. self._AddExtraConfDataIfNeeded( request_data )
  245. if force_semantic:
  246. request_data[ 'force_semantic' ] = True
  247. self._latest_completion_request = CompletionRequest( request_data )
  248. return self._latest_completion_request
  249. def GetCompletions( self ):
  250. request = self.GetCurrentCompletionRequest()
  251. request.Start()
  252. while not request.Done():
  253. try:
  254. if vimsupport.GetBoolValue( 'complete_check()' ):
  255. return { 'words' : [], 'refresh' : 'always' }
  256. except KeyboardInterrupt:
  257. return { 'words' : [], 'refresh' : 'always' }
  258. results = base.AdjustCandidateInsertionText( request.Response() )
  259. return { 'words' : results, 'refresh' : 'always' }
  260. def SendCommandRequest( self, arguments, completer ):
  261. extra_data = {}
  262. self._AddExtraConfDataIfNeeded( extra_data )
  263. return SendCommandRequest( arguments, completer, extra_data )
  264. def GetDefinedSubcommands( self ):
  265. with HandleServerException():
  266. return BaseRequest.PostDataToHandler( BuildRequestData(),
  267. 'defined_subcommands' )
  268. return []
  269. def GetCurrentCompletionRequest( self ):
  270. return self._latest_completion_request
  271. def GetOmniCompleter( self ):
  272. return self._omnicomp
  273. def FiletypeCompleterExistsForFiletype( self, filetype ):
  274. try:
  275. return self._available_completers[ filetype ]
  276. except KeyError:
  277. pass
  278. exists_completer = SendCompleterAvailableRequest( filetype )
  279. if exists_completer is None:
  280. return False
  281. self._available_completers[ filetype ] = exists_completer
  282. return exists_completer
  283. def NativeFiletypeCompletionAvailable( self ):
  284. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  285. vimsupport.CurrentFiletypes() ] )
  286. def NativeFiletypeCompletionUsable( self ):
  287. return ( self.CurrentFiletypeCompletionEnabled() and
  288. self.NativeFiletypeCompletionAvailable() )
  289. def OnFileReadyToParse( self ):
  290. if not self.IsServerAlive():
  291. self._NotifyUserIfServerCrashed()
  292. return
  293. self._omnicomp.OnFileReadyToParse( None )
  294. extra_data = {}
  295. self._AddTagsFilesIfNeeded( extra_data )
  296. self._AddSyntaxDataIfNeeded( extra_data )
  297. self._AddExtraConfDataIfNeeded( extra_data )
  298. self._latest_file_parse_request = EventNotification(
  299. 'FileReadyToParse', extra_data = extra_data )
  300. self._latest_file_parse_request.Start()
  301. def OnBufferUnload( self, deleted_buffer_file ):
  302. SendEventNotificationAsync( 'BufferUnload', filepath = deleted_buffer_file )
  303. def OnBufferVisit( self ):
  304. extra_data = {}
  305. self._AddUltiSnipsDataIfNeeded( extra_data )
  306. SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
  307. def OnInsertLeave( self ):
  308. SendEventNotificationAsync( 'InsertLeave' )
  309. def OnCursorMoved( self ):
  310. self._diag_interface.OnCursorMoved()
  311. def _CleanLogfile( self ):
  312. logging.shutdown()
  313. if not self._user_options[ 'keep_logfiles' ]:
  314. if self._client_logfile:
  315. utils.RemoveIfExists( self._client_logfile )
  316. def OnVimLeave( self ):
  317. self._ShutdownServer()
  318. self._CleanLogfile()
  319. def OnCurrentIdentifierFinished( self ):
  320. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  321. def OnCompleteDone( self ):
  322. complete_done_actions = self.GetCompleteDoneHooks()
  323. for action in complete_done_actions:
  324. action(self)
  325. def GetCompleteDoneHooks( self ):
  326. filetypes = vimsupport.CurrentFiletypes()
  327. for key, value in iteritems( self._complete_done_hooks ):
  328. if key in filetypes:
  329. yield value
  330. def GetCompletionsUserMayHaveCompleted( self ):
  331. latest_completion_request = self.GetCurrentCompletionRequest()
  332. if not latest_completion_request or not latest_completion_request.Done():
  333. return []
  334. completions = latest_completion_request.RawResponse()
  335. result = self._FilterToMatchingCompletions( completions, True )
  336. result = list( result )
  337. if result:
  338. return result
  339. if self._HasCompletionsThatCouldBeCompletedWithMoreText( completions ):
  340. # Since the way that YCM works leads to CompleteDone called on every
  341. # character, return blank if the completion might not be done. This won't
  342. # match if the completion is ended with typing a non-keyword character.
  343. return []
  344. result = self._FilterToMatchingCompletions( completions, False )
  345. return list( result )
  346. def _FilterToMatchingCompletions( self, completions, full_match_only ):
  347. """Filter to completions matching the item Vim said was completed"""
  348. completed = vimsupport.GetVariableValue( 'v:completed_item' )
  349. for completion in completions:
  350. item = ConvertCompletionDataToVimData( completion )
  351. match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only
  352. else [ 'word' ] )
  353. def matcher( key ):
  354. return ( utils.ToUnicode( completed.get( key, "" ) ) ==
  355. utils.ToUnicode( item.get( key, "" ) ) )
  356. if all( [ matcher( i ) for i in match_keys ] ):
  357. yield completion
  358. def _HasCompletionsThatCouldBeCompletedWithMoreText( self, completions ):
  359. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  360. if not completed_item:
  361. return False
  362. completed_word = utils.ToUnicode( completed_item[ 'word' ] )
  363. if not completed_word:
  364. return False
  365. # Sometimes CompleteDone is called after the next character is inserted.
  366. # If so, use inserted character to filter possible completions further.
  367. text = vimsupport.TextBeforeCursor()
  368. reject_exact_match = True
  369. if text and text[ -1 ] != completed_word[ -1 ]:
  370. reject_exact_match = False
  371. completed_word += text[ -1 ]
  372. for completion in completions:
  373. word = utils.ToUnicode(
  374. ConvertCompletionDataToVimData( completion )[ 'word' ] )
  375. if reject_exact_match and word == completed_word:
  376. continue
  377. if word.startswith( completed_word ):
  378. return True
  379. return False
  380. def _OnCompleteDone_Csharp( self ):
  381. completions = self.GetCompletionsUserMayHaveCompleted()
  382. namespaces = [ self._GetRequiredNamespaceImport( c )
  383. for c in completions ]
  384. namespaces = [ n for n in namespaces if n ]
  385. if not namespaces:
  386. return
  387. if len( namespaces ) > 1:
  388. choices = [ "{0} {1}".format( i + 1, n )
  389. for i, n in enumerate( namespaces ) ]
  390. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  391. if choice < 0:
  392. return
  393. namespace = namespaces[ choice ]
  394. else:
  395. namespace = namespaces[ 0 ]
  396. vimsupport.InsertNamespace( namespace )
  397. def _GetRequiredNamespaceImport( self, completion ):
  398. if ( "extra_data" not in completion
  399. or "required_namespace_import" not in completion[ "extra_data" ] ):
  400. return None
  401. return completion[ "extra_data" ][ "required_namespace_import" ]
  402. def GetErrorCount( self ):
  403. return self._diag_interface.GetErrorCount()
  404. def GetWarningCount( self ):
  405. return self._diag_interface.GetWarningCount()
  406. def DiagnosticUiSupportedForCurrentFiletype( self ):
  407. return any( [ x in DIAGNOSTIC_UI_FILETYPES
  408. for x in vimsupport.CurrentFiletypes() ] )
  409. def ShouldDisplayDiagnostics( self ):
  410. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  411. self.DiagnosticUiSupportedForCurrentFiletype() )
  412. def _PopulateLocationListWithLatestDiagnostics( self ):
  413. # Do nothing if loc list is already populated by diag_interface
  414. if not self._user_options[ 'always_populate_location_list' ]:
  415. self._diag_interface.PopulateLocationList( self._latest_diagnostics )
  416. return bool( self._latest_diagnostics )
  417. def UpdateDiagnosticInterface( self ):
  418. self._diag_interface.UpdateWithNewDiagnostics( self._latest_diagnostics )
  419. def FileParseRequestReady( self, block = False ):
  420. return bool( self._latest_file_parse_request and
  421. ( block or self._latest_file_parse_request.Done() ) )
  422. def HandleFileParseRequest( self, block = False ):
  423. # Order is important here:
  424. # FileParseRequestReady has a low cost, while
  425. # NativeFiletypeCompletionUsable is a blocking server request
  426. if ( self.FileParseRequestReady( block ) and
  427. self.NativeFiletypeCompletionUsable() ):
  428. if self.ShouldDisplayDiagnostics():
  429. self._latest_diagnostics = self._latest_file_parse_request.Response()
  430. self.UpdateDiagnosticInterface()
  431. else:
  432. # YCM client has a hard-coded list of filetypes which are known
  433. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  434. #
  435. # For filetypes which don't support diagnostics, we just want to check
  436. # the _latest_file_parse_request for any exception or UnknownExtraConf
  437. # response, to allow the server to raise configuration warnings, etc.
  438. # to the user. We ignore any other supplied data.
  439. self._latest_file_parse_request.Response()
  440. # We set the file parse request to None because we want to prevent
  441. # repeated issuing of the same warnings/errors/prompts. Setting this to
  442. # None makes FileParseRequestReady return False until the next
  443. # request is created.
  444. #
  445. # Note: it is the server's responsibility to determine the frequency of
  446. # error/warning/prompts when receiving a FileReadyToParse event, but
  447. # it our responsibility to ensure that we only apply the
  448. # warning/error/prompt received once (for each event).
  449. self._latest_file_parse_request = None
  450. def DebugInfo( self ):
  451. debug_info = ''
  452. if self._client_logfile:
  453. debug_info += 'Client logfile: {0}\n'.format( self._client_logfile )
  454. extra_data = {}
  455. self._AddExtraConfDataIfNeeded( extra_data )
  456. debug_info += FormatDebugInfoResponse( SendDebugInfoRequest( extra_data ) )
  457. debug_info += (
  458. 'Server running at: {0}\n'
  459. 'Server process ID: {1}\n'.format( BaseRequest.server_location,
  460. self._server_popen.pid ) )
  461. if self._server_stdout and self._server_stderr:
  462. debug_info += ( 'Server logfiles:\n'
  463. ' {0}\n'
  464. ' {1}'.format( self._server_stdout,
  465. self._server_stderr ) )
  466. return debug_info
  467. def GetLogfiles( self ):
  468. logfiles_list = [ self._client_logfile,
  469. self._server_stdout,
  470. self._server_stderr ]
  471. debug_info = SendDebugInfoRequest()
  472. if debug_info:
  473. completer = debug_info[ 'completer' ]
  474. if completer:
  475. for server in completer[ 'servers' ]:
  476. logfiles_list.extend( server[ 'logfiles' ] )
  477. logfiles = {}
  478. for logfile in logfiles_list:
  479. logfiles[ os.path.basename( logfile ) ] = logfile
  480. return logfiles
  481. def _OpenLogfile( self, logfile ):
  482. # Open log files in a horizontal window with the same behavior as the
  483. # preview window (same height and winfixheight enabled). Automatically
  484. # watch for changes. Set the cursor position at the end of the file.
  485. options = {
  486. 'size': vimsupport.GetIntValue( '&previewheight' ),
  487. 'fix': True,
  488. 'focus': False,
  489. 'watch': True,
  490. 'position': 'end'
  491. }
  492. vimsupport.OpenFilename( logfile, options )
  493. def _CloseLogfile( self, logfile ):
  494. vimsupport.CloseBuffersForFilename( logfile )
  495. def ToggleLogs( self, *filenames ):
  496. logfiles = self.GetLogfiles()
  497. if not filenames:
  498. vimsupport.PostVimMessage(
  499. 'Available logfiles are:\n'
  500. '{0}'.format( '\n'.join( sorted( list( logfiles ) ) ) ) )
  501. return
  502. for filename in set( filenames ):
  503. if filename not in logfiles:
  504. continue
  505. logfile = logfiles[ filename ]
  506. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  507. self._OpenLogfile( logfile )
  508. continue
  509. self._CloseLogfile( logfile )
  510. def CurrentFiletypeCompletionEnabled( self ):
  511. filetypes = vimsupport.CurrentFiletypes()
  512. filetype_to_disable = self._user_options[
  513. 'filetype_specific_completion_to_disable' ]
  514. if '*' in filetype_to_disable:
  515. return False
  516. else:
  517. return not any([ x in filetype_to_disable for x in filetypes ])
  518. def ShowDetailedDiagnostic( self ):
  519. with HandleServerException():
  520. detailed_diagnostic = BaseRequest.PostDataToHandler(
  521. BuildRequestData(), 'detailed_diagnostic' )
  522. if 'message' in detailed_diagnostic:
  523. vimsupport.PostVimMessage( detailed_diagnostic[ 'message' ],
  524. warning = False )
  525. def ForceCompileAndDiagnostics( self ):
  526. if not self.NativeFiletypeCompletionUsable():
  527. vimsupport.PostVimMessage(
  528. 'Native filetype completion not supported for current file, '
  529. 'cannot force recompilation.', warning = False )
  530. return False
  531. vimsupport.PostVimMessage(
  532. 'Forcing compilation, this will block Vim until done.',
  533. warning = False )
  534. self.OnFileReadyToParse()
  535. self.HandleFileParseRequest( block = True )
  536. vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
  537. return True
  538. def ShowDiagnostics( self ):
  539. if not self.ForceCompileAndDiagnostics():
  540. return
  541. if not self._PopulateLocationListWithLatestDiagnostics():
  542. vimsupport.PostVimMessage( 'No warnings or errors detected.',
  543. warning = False )
  544. return
  545. if self._user_options[ 'open_loclist_on_ycm_diags' ]:
  546. vimsupport.OpenLocationList( focus = True )
  547. def _AddSyntaxDataIfNeeded( self, extra_data ):
  548. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  549. return
  550. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  551. if filetype in self._filetypes_with_keywords_loaded:
  552. return
  553. if self.IsServerReady():
  554. self._filetypes_with_keywords_loaded.add( filetype )
  555. extra_data[ 'syntax_keywords' ] = list(
  556. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  557. def _AddTagsFilesIfNeeded( self, extra_data ):
  558. def GetTagFiles():
  559. tag_files = vim.eval( 'tagfiles()' )
  560. return [ os.path.join( utils.GetCurrentDirectory(), tag_file )
  561. for tag_file in tag_files ]
  562. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  563. return
  564. extra_data[ 'tag_files' ] = GetTagFiles()
  565. def _AddExtraConfDataIfNeeded( self, extra_data ):
  566. def BuildExtraConfData( extra_conf_vim_data ):
  567. return dict( ( expr, vimsupport.VimExpressionToPythonType( expr ) )
  568. for expr in extra_conf_vim_data )
  569. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  570. if extra_conf_vim_data:
  571. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  572. extra_conf_vim_data )
  573. def _AddUltiSnipsDataIfNeeded( self, extra_data ):
  574. # See :h UltiSnips#SnippetsInCurrentScope.
  575. try:
  576. vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
  577. except vim.error:
  578. return
  579. snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
  580. extra_data[ 'ultisnips_snippets' ] = [
  581. { 'trigger': trigger,
  582. 'description': snippet[ 'description' ] }
  583. for trigger, snippet in iteritems( snippets )
  584. ]