youcompleteme.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. # Copyright (C) 2011-2012 Google Inc.
  2. # 2016 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. from future import standard_library
  23. standard_library.install_aliases()
  24. from builtins import * # noqa
  25. from future.utils import iteritems
  26. import base64
  27. import json
  28. import logging
  29. import os
  30. import re
  31. import signal
  32. import vim
  33. from subprocess import PIPE
  34. from tempfile import NamedTemporaryFile
  35. from ycm import base, paths, vimsupport
  36. from ycmd import utils
  37. from ycmd import server_utils
  38. from ycmd.request_wrap import RequestWrap
  39. from ycmd.responses import ServerError
  40. from ycm.diagnostic_interface import DiagnosticInterface
  41. from ycm.omni_completer import OmniCompleter
  42. from ycm import syntax_parse
  43. from ycm.client.ycmd_keepalive import YcmdKeepalive
  44. from ycm.client.base_request import BaseRequest, BuildRequestData
  45. from ycm.client.completer_available_request import SendCompleterAvailableRequest
  46. from ycm.client.command_request import SendCommandRequest
  47. from ycm.client.completion_request import ( CompletionRequest,
  48. ConvertCompletionDataToVimData )
  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 = 10800 # 3 hours
  94. DIAGNOSTIC_UI_FILETYPES = set( [ 'cpp', 'cs', 'c', 'objc', 'objcpp' ] )
  95. CLIENT_LOGFILE_FORMAT = 'ycm_'
  96. SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'
  97. # Flag to set a file handle inheritable by child processes on Windows. See
  98. # https://msdn.microsoft.com/en-us/library/ms724935.aspx
  99. HANDLE_FLAG_INHERIT = 0x00000001
  100. class YouCompleteMe( object ):
  101. def __init__( self, user_options ):
  102. self._available_completers = {}
  103. self._user_options = user_options
  104. self._user_notified_about_crash = False
  105. self._diag_interface = DiagnosticInterface( user_options )
  106. self._omnicomp = OmniCompleter( user_options )
  107. self._latest_file_parse_request = None
  108. self._latest_completion_request = None
  109. self._latest_diagnostics = []
  110. self._logger = logging.getLogger( 'ycm' )
  111. self._client_logfile = None
  112. self._server_stdout = None
  113. self._server_stderr = None
  114. self._server_popen = None
  115. self._filetypes_with_keywords_loaded = set()
  116. self._ycmd_keepalive = YcmdKeepalive()
  117. self._SetupLogging()
  118. self._SetupServer()
  119. self._ycmd_keepalive.Start()
  120. self._complete_done_hooks = {
  121. 'cs': lambda self: self._OnCompleteDone_Csharp()
  122. }
  123. def _SetupServer( self ):
  124. self._available_completers = {}
  125. self._user_notified_about_crash = False
  126. server_port = utils.GetUnusedLocalhostPort()
  127. # The temp options file is deleted by ycmd during startup
  128. with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
  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. json.dump( options_dict, options_file )
  136. options_file.flush()
  137. args = [ paths.PathToPythonInterpreter(),
  138. paths.PathToServerScript(),
  139. '--port={0}'.format( server_port ),
  140. '--options_file={0}'.format( options_file.name ),
  141. '--log={0}'.format( self._user_options[ 'log_level' ] ),
  142. '--idle_suicide_seconds={0}'.format(
  143. 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( '--stdout={0}'.format( self._server_stdout ) )
  149. args.append( '--stderr={0}'.format( 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. BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
  155. BaseRequest.hmac_secret = hmac_secret
  156. self._NotifyUserIfServerCrashed()
  157. def _SetupLogging( self ):
  158. def FreeFileFromOtherProcesses( file_object ):
  159. if utils.OnWindows():
  160. from ctypes import windll
  161. import msvcrt
  162. file_handle = msvcrt.get_osfhandle( file_object.fileno() )
  163. windll.kernel32.SetHandleInformation( file_handle,
  164. HANDLE_FLAG_INHERIT,
  165. 0 )
  166. self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
  167. log_level = self._user_options[ 'log_level' ]
  168. numeric_level = getattr( logging, log_level.upper(), None )
  169. if not isinstance( numeric_level, int ):
  170. raise ValueError( 'Invalid log level: {0}'.format( log_level ) )
  171. self._logger.setLevel( numeric_level )
  172. handler = logging.FileHandler( self._client_logfile )
  173. # On Windows and Python prior to 3.4, file handles are inherited by child
  174. # processes started with at least one replaced standard stream, which is the
  175. # case when we start the ycmd server (we are redirecting all standard
  176. # outputs into a pipe). These files cannot be removed while the child
  177. # processes are still up. This is not desirable for a logfile because we
  178. # want to remove it at Vim exit without having to wait for the ycmd server
  179. # to be completely shut down. We need to make the logfile handle
  180. # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
  181. # details.
  182. FreeFileFromOtherProcesses( handler.stream )
  183. formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
  184. handler.setFormatter( formatter )
  185. self._logger.addHandler( handler )
  186. def IsServerAlive( self ):
  187. return_code = self._server_popen.poll()
  188. # When the process hasn't finished yet, poll() returns None.
  189. return return_code is None
  190. def _NotifyUserIfServerCrashed( self ):
  191. if self._user_notified_about_crash or self.IsServerAlive():
  192. return
  193. self._user_notified_about_crash = True
  194. return_code = self._server_popen.poll()
  195. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  196. error_message = CORE_UNEXPECTED_MESSAGE
  197. elif return_code == server_utils.CORE_MISSING_STATUS:
  198. error_message = CORE_MISSING_MESSAGE
  199. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  200. error_message = CORE_PYTHON2_MESSAGE
  201. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  202. error_message = CORE_PYTHON3_MESSAGE
  203. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  204. error_message = CORE_OUTDATED_MESSAGE
  205. else:
  206. error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format( code = return_code )
  207. server_stderr = '\n'.join( self._server_popen.stderr.read().splitlines() )
  208. if server_stderr:
  209. self._logger.error( server_stderr )
  210. error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
  211. self._logger.error( error_message )
  212. vimsupport.PostVimMessage( error_message )
  213. def ServerPid( self ):
  214. if not self._server_popen:
  215. return -1
  216. return self._server_popen.pid
  217. def _ShutdownServer( self ):
  218. if self.IsServerAlive():
  219. SendShutdownRequest()
  220. def RestartServer( self ):
  221. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  222. self._ShutdownServer()
  223. self._SetupServer()
  224. def CreateCompletionRequest( self, force_semantic = False ):
  225. request_data = BuildRequestData()
  226. if ( not self.NativeFiletypeCompletionAvailable() and
  227. self.CurrentFiletypeCompletionEnabled() ):
  228. wrapped_request_data = RequestWrap( request_data )
  229. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  230. self._latest_completion_request = OmniCompletionRequest(
  231. self._omnicomp, wrapped_request_data )
  232. return self._latest_completion_request
  233. request_data[ 'working_dir' ] = utils.GetCurrentDirectory()
  234. self._AddExtraConfDataIfNeeded( request_data )
  235. if force_semantic:
  236. request_data[ 'force_semantic' ] = True
  237. self._latest_completion_request = CompletionRequest( request_data )
  238. return self._latest_completion_request
  239. def GetCompletions( self ):
  240. request = self.GetCurrentCompletionRequest()
  241. request.Start()
  242. while not request.Done():
  243. try:
  244. if vimsupport.GetBoolValue( 'complete_check()' ):
  245. return { 'words' : [], 'refresh' : 'always' }
  246. except KeyboardInterrupt:
  247. return { 'words' : [], 'refresh' : 'always' }
  248. results = base.AdjustCandidateInsertionText( request.Response() )
  249. return { 'words' : results, 'refresh' : 'always' }
  250. def SendCommandRequest( self, arguments, completer ):
  251. if self.IsServerAlive():
  252. return SendCommandRequest( arguments, completer )
  253. def GetDefinedSubcommands( self ):
  254. if self.IsServerAlive():
  255. try:
  256. return BaseRequest.PostDataToHandler( BuildRequestData(),
  257. 'defined_subcommands' )
  258. except ServerError:
  259. return []
  260. else:
  261. return []
  262. def GetCurrentCompletionRequest( self ):
  263. return self._latest_completion_request
  264. def GetOmniCompleter( self ):
  265. return self._omnicomp
  266. def FiletypeCompleterExistsForFiletype( self, filetype ):
  267. try:
  268. return self._available_completers[ filetype ]
  269. except KeyError:
  270. pass
  271. if not self.IsServerAlive():
  272. return False
  273. exists_completer = SendCompleterAvailableRequest( filetype )
  274. if exists_completer is None:
  275. return False
  276. self._available_completers[ filetype ] = exists_completer
  277. return exists_completer
  278. def NativeFiletypeCompletionAvailable( self ):
  279. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  280. vimsupport.CurrentFiletypes() ] )
  281. def NativeFiletypeCompletionUsable( self ):
  282. return ( self.CurrentFiletypeCompletionEnabled() and
  283. self.NativeFiletypeCompletionAvailable() )
  284. def OnFileReadyToParse( self ):
  285. if not self.IsServerAlive():
  286. self._NotifyUserIfServerCrashed()
  287. return
  288. self._omnicomp.OnFileReadyToParse( None )
  289. extra_data = {}
  290. self._AddTagsFilesIfNeeded( extra_data )
  291. self._AddSyntaxDataIfNeeded( extra_data )
  292. self._AddExtraConfDataIfNeeded( extra_data )
  293. self._latest_file_parse_request = EventNotification(
  294. 'FileReadyToParse', extra_data = extra_data )
  295. self._latest_file_parse_request.Start()
  296. def OnBufferUnload( self, deleted_buffer_file ):
  297. if not self.IsServerAlive():
  298. return
  299. SendEventNotificationAsync( 'BufferUnload', filepath = deleted_buffer_file )
  300. def OnBufferVisit( self ):
  301. if not self.IsServerAlive():
  302. return
  303. extra_data = {}
  304. self._AddUltiSnipsDataIfNeeded( extra_data )
  305. SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
  306. def OnInsertLeave( self ):
  307. if not self.IsServerAlive():
  308. return
  309. SendEventNotificationAsync( 'InsertLeave' )
  310. def OnCursorMoved( self ):
  311. self._diag_interface.OnCursorMoved()
  312. def _CleanLogfile( self ):
  313. logging.shutdown()
  314. if not self._user_options[ 'keep_logfiles' ]:
  315. if self._client_logfile:
  316. utils.RemoveIfExists( self._client_logfile )
  317. def OnVimLeave( self ):
  318. self._ShutdownServer()
  319. self._CleanLogfile()
  320. def OnCurrentIdentifierFinished( self ):
  321. if not self.IsServerAlive():
  322. return
  323. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  324. def OnCompleteDone( self ):
  325. complete_done_actions = self.GetCompleteDoneHooks()
  326. for action in complete_done_actions:
  327. action(self)
  328. def GetCompleteDoneHooks( self ):
  329. filetypes = vimsupport.CurrentFiletypes()
  330. for key, value in iteritems( self._complete_done_hooks ):
  331. if key in filetypes:
  332. yield value
  333. def GetCompletionsUserMayHaveCompleted( self ):
  334. latest_completion_request = self.GetCurrentCompletionRequest()
  335. if not latest_completion_request or not latest_completion_request.Done():
  336. return []
  337. completions = latest_completion_request.RawResponse()
  338. result = self._FilterToMatchingCompletions( completions, True )
  339. result = list( result )
  340. if result:
  341. return result
  342. if self._HasCompletionsThatCouldBeCompletedWithMoreText( completions ):
  343. # Since the way that YCM works leads to CompleteDone called on every
  344. # character, return blank if the completion might not be done. This won't
  345. # match if the completion is ended with typing a non-keyword character.
  346. return []
  347. result = self._FilterToMatchingCompletions( completions, False )
  348. return list( result )
  349. def _FilterToMatchingCompletions( self, completions, full_match_only ):
  350. self._PatchBasedOnVimVersion()
  351. return self._FilterToMatchingCompletions( completions, full_match_only)
  352. def _HasCompletionsThatCouldBeCompletedWithMoreText( self, completions ):
  353. self._PatchBasedOnVimVersion()
  354. return self._HasCompletionsThatCouldBeCompletedWithMoreText( completions )
  355. def _PatchBasedOnVimVersion( self ):
  356. if vimsupport.VimVersionAtLeast( "7.4.774" ):
  357. self._HasCompletionsThatCouldBeCompletedWithMoreText = \
  358. self._HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim
  359. self._FilterToMatchingCompletions = \
  360. self._FilterToMatchingCompletions_NewerVim
  361. else:
  362. self._FilterToMatchingCompletions = \
  363. self._FilterToMatchingCompletions_OlderVim
  364. self._HasCompletionsThatCouldBeCompletedWithMoreText = \
  365. self._HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim
  366. def _FilterToMatchingCompletions_NewerVim( self,
  367. completions,
  368. full_match_only ):
  369. """Filter to completions matching the item Vim said was completed"""
  370. completed = vimsupport.GetVariableValue( 'v:completed_item' )
  371. for completion in completions:
  372. item = ConvertCompletionDataToVimData( completion )
  373. match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only
  374. else [ 'word' ] )
  375. def matcher( key ):
  376. return ( utils.ToUnicode( completed.get( key, "" ) ) ==
  377. utils.ToUnicode( item.get( key, "" ) ) )
  378. if all( [ matcher( i ) for i in match_keys ] ):
  379. yield completion
  380. def _FilterToMatchingCompletions_OlderVim( self, completions,
  381. full_match_only ):
  382. """ Filter to completions matching the buffer text """
  383. if full_match_only:
  384. return # Only supported in 7.4.774+
  385. # No support for multiple line completions
  386. text = vimsupport.TextBeforeCursor()
  387. for completion in completions:
  388. word = completion[ "insertion_text" ]
  389. # Trim complete-ending character if needed
  390. text = re.sub( r"[^a-zA-Z0-9_]$", "", text )
  391. buffer_text = text[ -1 * len( word ) : ]
  392. if buffer_text == word:
  393. yield completion
  394. def _HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim( self,
  395. completions ):
  396. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  397. if not completed_item:
  398. return False
  399. completed_word = utils.ToUnicode( completed_item[ 'word' ] )
  400. if not completed_word:
  401. return False
  402. # Sometimes CompleteDone is called after the next character is inserted.
  403. # If so, use inserted character to filter possible completions further.
  404. text = vimsupport.TextBeforeCursor()
  405. reject_exact_match = True
  406. if text and text[ -1 ] != completed_word[ -1 ]:
  407. reject_exact_match = False
  408. completed_word += text[ -1 ]
  409. for completion in completions:
  410. word = utils.ToUnicode(
  411. ConvertCompletionDataToVimData( completion )[ 'word' ] )
  412. if reject_exact_match and word == completed_word:
  413. continue
  414. if word.startswith( completed_word ):
  415. return True
  416. return False
  417. def _HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim( self,
  418. completions ):
  419. # No support for multiple line completions
  420. text = vimsupport.TextBeforeCursor()
  421. for completion in completions:
  422. word = utils.ToUnicode(
  423. ConvertCompletionDataToVimData( completion )[ 'word' ] )
  424. for i in range( 1, len( word ) - 1 ): # Excluding full word
  425. if text[ -1 * i : ] == word[ : i ]:
  426. return True
  427. return False
  428. def _OnCompleteDone_Csharp( self ):
  429. completions = self.GetCompletionsUserMayHaveCompleted()
  430. namespaces = [ self._GetRequiredNamespaceImport( c )
  431. for c in completions ]
  432. namespaces = [ n for n in namespaces if n ]
  433. if not namespaces:
  434. return
  435. if len( namespaces ) > 1:
  436. choices = [ "{0} {1}".format( i + 1, n )
  437. for i, n in enumerate( namespaces ) ]
  438. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  439. if choice < 0:
  440. return
  441. namespace = namespaces[ choice ]
  442. else:
  443. namespace = namespaces[ 0 ]
  444. vimsupport.InsertNamespace( namespace )
  445. def _GetRequiredNamespaceImport( self, completion ):
  446. if ( "extra_data" not in completion
  447. or "required_namespace_import" not in completion[ "extra_data" ] ):
  448. return None
  449. return completion[ "extra_data" ][ "required_namespace_import" ]
  450. def GetErrorCount( self ):
  451. return self._diag_interface.GetErrorCount()
  452. def GetWarningCount( self ):
  453. return self._diag_interface.GetWarningCount()
  454. def DiagnosticUiSupportedForCurrentFiletype( self ):
  455. return any( [ x in DIAGNOSTIC_UI_FILETYPES
  456. for x in vimsupport.CurrentFiletypes() ] )
  457. def ShouldDisplayDiagnostics( self ):
  458. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  459. self.DiagnosticUiSupportedForCurrentFiletype() )
  460. def PopulateLocationListWithLatestDiagnostics( self ):
  461. # Do nothing if loc list is already populated by diag_interface
  462. if not self._user_options[ 'always_populate_location_list' ]:
  463. self._diag_interface.PopulateLocationList( self._latest_diagnostics )
  464. return bool( self._latest_diagnostics )
  465. def UpdateDiagnosticInterface( self ):
  466. self._diag_interface.UpdateWithNewDiagnostics( self._latest_diagnostics )
  467. def FileParseRequestReady( self, block = False ):
  468. return bool( self._latest_file_parse_request and
  469. ( block or self._latest_file_parse_request.Done() ) )
  470. def HandleFileParseRequest( self, block = False ):
  471. # Order is important here:
  472. # FileParseRequestReady has a low cost, while
  473. # NativeFiletypeCompletionUsable is a blocking server request
  474. if ( self.FileParseRequestReady( block ) and
  475. self.NativeFiletypeCompletionUsable() ):
  476. if self.ShouldDisplayDiagnostics():
  477. self._latest_diagnostics = self._latest_file_parse_request.Response()
  478. self.UpdateDiagnosticInterface()
  479. else:
  480. # YCM client has a hard-coded list of filetypes which are known
  481. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  482. #
  483. # For filetypes which don't support diagnostics, we just want to check
  484. # the _latest_file_parse_request for any exception or UnknownExtraConf
  485. # response, to allow the server to raise configuration warnings, etc.
  486. # to the user. We ignore any other supplied data.
  487. self._latest_file_parse_request.Response()
  488. # We set the file parse request to None because we want to prevent
  489. # repeated issuing of the same warnings/errors/prompts. Setting this to
  490. # None makes FileParseRequestReady return False until the next
  491. # request is created.
  492. #
  493. # Note: it is the server's responsibility to determine the frequency of
  494. # error/warning/prompts when receiving a FileReadyToParse event, but
  495. # it our responsibility to ensure that we only apply the
  496. # warning/error/prompt received once (for each event).
  497. self._latest_file_parse_request = None
  498. def ShowDetailedDiagnostic( self ):
  499. if not self.IsServerAlive():
  500. return
  501. try:
  502. debug_info = BaseRequest.PostDataToHandler( BuildRequestData(),
  503. 'detailed_diagnostic' )
  504. if 'message' in debug_info:
  505. vimsupport.PostVimMessage( debug_info[ 'message' ],
  506. warning = False )
  507. except ServerError as e:
  508. vimsupport.PostVimMessage( str( e ) )
  509. def DebugInfo( self ):
  510. debug_info = ''
  511. if self._client_logfile:
  512. debug_info += 'Client logfile: {0}\n'.format( self._client_logfile )
  513. if self.IsServerAlive():
  514. debug_info += BaseRequest.PostDataToHandler( BuildRequestData(),
  515. 'debug_info' )
  516. else:
  517. debug_info += 'Server crashed, no debug info from server'
  518. debug_info += '\nServer running at: {0}\n'.format(
  519. BaseRequest.server_location )
  520. debug_info += 'Server process ID: {0}\n'.format( self._server_popen.pid )
  521. if self._server_stderr or self._server_stdout:
  522. debug_info += ( 'Server logfiles:\n'
  523. ' {0}\n'
  524. ' {1}'.format( self._server_stdout,
  525. self._server_stderr ) )
  526. return debug_info
  527. def GetLogfiles( self ):
  528. logfiles_list = [ self._client_logfile,
  529. self._server_stdout,
  530. self._server_stderr ]
  531. logfiles = {}
  532. for logfile in logfiles_list:
  533. logfiles[ os.path.basename( logfile ) ] = logfile
  534. return logfiles
  535. def _OpenLogfile( self, logfile ):
  536. # Open log files in a horizontal window with the same behavior as the
  537. # preview window (same height and winfixheight enabled). Automatically
  538. # watch for changes. Set the cursor position at the end of the file.
  539. options = {
  540. 'size': vimsupport.GetIntValue( '&previewheight' ),
  541. 'fix': True,
  542. 'focus': False,
  543. 'watch': True,
  544. 'position': 'end'
  545. }
  546. vimsupport.OpenFilename( logfile, options )
  547. def _CloseLogfile( self, logfile ):
  548. vimsupport.CloseBuffersForFilename( logfile )
  549. def ToggleLogs( self, *filenames ):
  550. logfiles = self.GetLogfiles()
  551. if not filenames:
  552. vimsupport.PostVimMessage(
  553. 'Available logfiles are:\n'
  554. '{0}'.format( '\n'.join( sorted( list( logfiles ) ) ) ) )
  555. return
  556. for filename in set( filenames ):
  557. if filename not in logfiles:
  558. continue
  559. logfile = logfiles[ filename ]
  560. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  561. self._OpenLogfile( logfile )
  562. continue
  563. self._CloseLogfile( logfile )
  564. def CurrentFiletypeCompletionEnabled( self ):
  565. filetypes = vimsupport.CurrentFiletypes()
  566. filetype_to_disable = self._user_options[
  567. 'filetype_specific_completion_to_disable' ]
  568. if '*' in filetype_to_disable:
  569. return False
  570. else:
  571. return not any([ x in filetype_to_disable for x in filetypes ])
  572. def _AddSyntaxDataIfNeeded( self, extra_data ):
  573. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  574. return
  575. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  576. if filetype in self._filetypes_with_keywords_loaded:
  577. return
  578. self._filetypes_with_keywords_loaded.add( filetype )
  579. extra_data[ 'syntax_keywords' ] = list(
  580. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  581. def _AddTagsFilesIfNeeded( self, extra_data ):
  582. def GetTagFiles():
  583. tag_files = vim.eval( 'tagfiles()' )
  584. return [ os.path.join( utils.GetCurrentDirectory(), tag_file )
  585. for tag_file in tag_files ]
  586. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  587. return
  588. extra_data[ 'tag_files' ] = GetTagFiles()
  589. def _AddExtraConfDataIfNeeded( self, extra_data ):
  590. def BuildExtraConfData( extra_conf_vim_data ):
  591. return dict( ( expr, vimsupport.VimExpressionToPythonType( expr ) )
  592. for expr in extra_conf_vim_data )
  593. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  594. if extra_conf_vim_data:
  595. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  596. extra_conf_vim_data )
  597. def _AddUltiSnipsDataIfNeeded( self, extra_data ):
  598. # See :h UltiSnips#SnippetsInCurrentScope.
  599. try:
  600. vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
  601. except vim.error:
  602. return
  603. snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
  604. extra_data[ 'ultisnips_snippets' ] = [
  605. { 'trigger': trigger,
  606. 'description': snippet[ 'description' ] }
  607. for trigger, snippet in iteritems( snippets )
  608. ]