youcompleteme.py 27 KB

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