youcompleteme.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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 re
  30. import signal
  31. import vim
  32. from subprocess import PIPE
  33. from tempfile import NamedTemporaryFile
  34. from ycm import base, paths, vimsupport
  35. from ycmd import utils
  36. from ycmd import server_utils
  37. from ycmd.request_wrap import RequestWrap
  38. from ycm.diagnostic_interface import DiagnosticInterface
  39. from ycm.omni_completer import OmniCompleter
  40. from ycm import syntax_parse
  41. from ycm.client.ycmd_keepalive import YcmdKeepalive
  42. from ycm.client.base_request import ( BaseRequest, BuildRequestData,
  43. HandleServerException )
  44. from ycm.client.completer_available_request import SendCompleterAvailableRequest
  45. from ycm.client.command_request import SendCommandRequest
  46. from ycm.client.completion_request import ( CompletionRequest,
  47. ConvertCompletionDataToVimData )
  48. from ycm.client.debug_info_request import ( SendDebugInfoRequest,
  49. FormatDebugInfoResponse )
  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._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 _NotifyUserIfServerCrashed( self ):
  195. if self._user_notified_about_crash or self.IsServerAlive():
  196. return
  197. self._user_notified_about_crash = True
  198. return_code = self._server_popen.poll()
  199. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  200. error_message = CORE_UNEXPECTED_MESSAGE
  201. elif return_code == server_utils.CORE_MISSING_STATUS:
  202. error_message = CORE_MISSING_MESSAGE
  203. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  204. error_message = CORE_PYTHON2_MESSAGE
  205. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  206. error_message = CORE_PYTHON3_MESSAGE
  207. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  208. error_message = CORE_OUTDATED_MESSAGE
  209. else:
  210. error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format( code = return_code )
  211. server_stderr = '\n'.join(
  212. utils.ToUnicode( self._server_popen.stderr.read() ).splitlines() )
  213. if server_stderr:
  214. self._logger.error( server_stderr )
  215. error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
  216. self._logger.error( error_message )
  217. vimsupport.PostVimMessage( error_message )
  218. def ServerPid( self ):
  219. if not self._server_popen:
  220. return -1
  221. return self._server_popen.pid
  222. def _ShutdownServer( self ):
  223. SendShutdownRequest()
  224. def RestartServer( self ):
  225. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  226. self._ShutdownServer()
  227. self._SetupServer()
  228. def CreateCompletionRequest( self, force_semantic = False ):
  229. request_data = BuildRequestData()
  230. if ( not self.NativeFiletypeCompletionAvailable() and
  231. self.CurrentFiletypeCompletionEnabled() ):
  232. wrapped_request_data = RequestWrap( request_data )
  233. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  234. self._latest_completion_request = OmniCompletionRequest(
  235. self._omnicomp, wrapped_request_data )
  236. return self._latest_completion_request
  237. request_data[ 'working_dir' ] = utils.GetCurrentDirectory()
  238. self._AddExtraConfDataIfNeeded( request_data )
  239. if force_semantic:
  240. request_data[ 'force_semantic' ] = True
  241. self._latest_completion_request = CompletionRequest( request_data )
  242. return self._latest_completion_request
  243. def GetCompletions( self ):
  244. request = self.GetCurrentCompletionRequest()
  245. request.Start()
  246. while not request.Done():
  247. try:
  248. if vimsupport.GetBoolValue( 'complete_check()' ):
  249. return { 'words' : [], 'refresh' : 'always' }
  250. except KeyboardInterrupt:
  251. return { 'words' : [], 'refresh' : 'always' }
  252. results = base.AdjustCandidateInsertionText( request.Response() )
  253. return { 'words' : results, 'refresh' : 'always' }
  254. def SendCommandRequest( self, arguments, completer ):
  255. return SendCommandRequest( arguments, completer )
  256. def GetDefinedSubcommands( self ):
  257. with HandleServerException():
  258. return BaseRequest.PostDataToHandler( BuildRequestData(),
  259. 'defined_subcommands' )
  260. return []
  261. def GetCurrentCompletionRequest( self ):
  262. return self._latest_completion_request
  263. def GetOmniCompleter( self ):
  264. return self._omnicomp
  265. def FiletypeCompleterExistsForFiletype( self, filetype ):
  266. try:
  267. return self._available_completers[ filetype ]
  268. except KeyError:
  269. pass
  270. exists_completer = SendCompleterAvailableRequest( filetype )
  271. if exists_completer is None:
  272. return False
  273. self._available_completers[ filetype ] = exists_completer
  274. return exists_completer
  275. def NativeFiletypeCompletionAvailable( self ):
  276. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  277. vimsupport.CurrentFiletypes() ] )
  278. def NativeFiletypeCompletionUsable( self ):
  279. return ( self.CurrentFiletypeCompletionEnabled() and
  280. self.NativeFiletypeCompletionAvailable() )
  281. def ServerBecomesReady( self ):
  282. if not self._server_is_ready_with_cache:
  283. with HandleServerException( display = False ):
  284. self._server_is_ready_with_cache = BaseRequest.GetDataFromHandler(
  285. 'ready' )
  286. return self._server_is_ready_with_cache
  287. return False
  288. def OnFileReadyToParse( self ):
  289. if not self.IsServerAlive():
  290. self._NotifyUserIfServerCrashed()
  291. return
  292. self._omnicomp.OnFileReadyToParse( None )
  293. extra_data = {}
  294. self._AddTagsFilesIfNeeded( extra_data )
  295. self._AddSyntaxDataIfNeeded( extra_data )
  296. self._AddExtraConfDataIfNeeded( extra_data )
  297. self._latest_file_parse_request = EventNotification(
  298. 'FileReadyToParse', extra_data = extra_data )
  299. self._latest_file_parse_request.Start()
  300. def OnBufferUnload( self, deleted_buffer_file ):
  301. SendEventNotificationAsync( 'BufferUnload', filepath = deleted_buffer_file )
  302. def OnBufferVisit( self ):
  303. extra_data = {}
  304. self._AddUltiSnipsDataIfNeeded( extra_data )
  305. SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
  306. def OnInsertLeave( self ):
  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. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  320. def OnCompleteDone( self ):
  321. complete_done_actions = self.GetCompleteDoneHooks()
  322. for action in complete_done_actions:
  323. action(self)
  324. def GetCompleteDoneHooks( self ):
  325. filetypes = vimsupport.CurrentFiletypes()
  326. for key, value in iteritems( self._complete_done_hooks ):
  327. if key in filetypes:
  328. yield value
  329. def GetCompletionsUserMayHaveCompleted( self ):
  330. latest_completion_request = self.GetCurrentCompletionRequest()
  331. if not latest_completion_request or not latest_completion_request.Done():
  332. return []
  333. completions = latest_completion_request.RawResponse()
  334. result = self._FilterToMatchingCompletions( completions, True )
  335. result = list( result )
  336. if result:
  337. return result
  338. if self._HasCompletionsThatCouldBeCompletedWithMoreText( completions ):
  339. # Since the way that YCM works leads to CompleteDone called on every
  340. # character, return blank if the completion might not be done. This won't
  341. # match if the completion is ended with typing a non-keyword character.
  342. return []
  343. result = self._FilterToMatchingCompletions( completions, False )
  344. return list( result )
  345. def _FilterToMatchingCompletions( self, completions, full_match_only ):
  346. self._PatchBasedOnVimVersion()
  347. return self._FilterToMatchingCompletions( completions, full_match_only)
  348. def _HasCompletionsThatCouldBeCompletedWithMoreText( self, completions ):
  349. self._PatchBasedOnVimVersion()
  350. return self._HasCompletionsThatCouldBeCompletedWithMoreText( completions )
  351. def _PatchBasedOnVimVersion( self ):
  352. if vimsupport.VimVersionAtLeast( "7.4.774" ):
  353. self._HasCompletionsThatCouldBeCompletedWithMoreText = \
  354. self._HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim
  355. self._FilterToMatchingCompletions = \
  356. self._FilterToMatchingCompletions_NewerVim
  357. else:
  358. self._FilterToMatchingCompletions = \
  359. self._FilterToMatchingCompletions_OlderVim
  360. self._HasCompletionsThatCouldBeCompletedWithMoreText = \
  361. self._HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim
  362. def _FilterToMatchingCompletions_NewerVim( self,
  363. completions,
  364. full_match_only ):
  365. """Filter to completions matching the item Vim said was completed"""
  366. completed = vimsupport.GetVariableValue( 'v:completed_item' )
  367. for completion in completions:
  368. item = ConvertCompletionDataToVimData( completion )
  369. match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only
  370. else [ 'word' ] )
  371. def matcher( key ):
  372. return ( utils.ToUnicode( completed.get( key, "" ) ) ==
  373. utils.ToUnicode( item.get( key, "" ) ) )
  374. if all( [ matcher( i ) for i in match_keys ] ):
  375. yield completion
  376. def _FilterToMatchingCompletions_OlderVim( self, completions,
  377. full_match_only ):
  378. """ Filter to completions matching the buffer text """
  379. if full_match_only:
  380. return # Only supported in 7.4.774+
  381. # No support for multiple line completions
  382. text = vimsupport.TextBeforeCursor()
  383. for completion in completions:
  384. word = completion[ "insertion_text" ]
  385. # Trim complete-ending character if needed
  386. text = re.sub( r"[^a-zA-Z0-9_]$", "", text )
  387. buffer_text = text[ -1 * len( word ) : ]
  388. if buffer_text == word:
  389. yield completion
  390. def _HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim( self,
  391. completions ):
  392. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  393. if not completed_item:
  394. return False
  395. completed_word = utils.ToUnicode( completed_item[ 'word' ] )
  396. if not completed_word:
  397. return False
  398. # Sometimes CompleteDone is called after the next character is inserted.
  399. # If so, use inserted character to filter possible completions further.
  400. text = vimsupport.TextBeforeCursor()
  401. reject_exact_match = True
  402. if text and text[ -1 ] != completed_word[ -1 ]:
  403. reject_exact_match = False
  404. completed_word += text[ -1 ]
  405. for completion in completions:
  406. word = utils.ToUnicode(
  407. ConvertCompletionDataToVimData( completion )[ 'word' ] )
  408. if reject_exact_match and word == completed_word:
  409. continue
  410. if word.startswith( completed_word ):
  411. return True
  412. return False
  413. def _HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim( self,
  414. completions ):
  415. # No support for multiple line completions
  416. text = vimsupport.TextBeforeCursor()
  417. for completion in completions:
  418. word = utils.ToUnicode(
  419. ConvertCompletionDataToVimData( completion )[ 'word' ] )
  420. for i in range( 1, len( word ) - 1 ): # Excluding full word
  421. if text[ -1 * i : ] == word[ : i ]:
  422. return True
  423. return False
  424. def _OnCompleteDone_Csharp( self ):
  425. completions = self.GetCompletionsUserMayHaveCompleted()
  426. namespaces = [ self._GetRequiredNamespaceImport( c )
  427. for c in completions ]
  428. namespaces = [ n for n in namespaces if n ]
  429. if not namespaces:
  430. return
  431. if len( namespaces ) > 1:
  432. choices = [ "{0} {1}".format( i + 1, n )
  433. for i, n in enumerate( namespaces ) ]
  434. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  435. if choice < 0:
  436. return
  437. namespace = namespaces[ choice ]
  438. else:
  439. namespace = namespaces[ 0 ]
  440. vimsupport.InsertNamespace( namespace )
  441. def _GetRequiredNamespaceImport( self, completion ):
  442. if ( "extra_data" not in completion
  443. or "required_namespace_import" not in completion[ "extra_data" ] ):
  444. return None
  445. return completion[ "extra_data" ][ "required_namespace_import" ]
  446. def GetErrorCount( self ):
  447. return self._diag_interface.GetErrorCount()
  448. def GetWarningCount( self ):
  449. return self._diag_interface.GetWarningCount()
  450. def DiagnosticUiSupportedForCurrentFiletype( self ):
  451. return any( [ x in DIAGNOSTIC_UI_FILETYPES
  452. for x in vimsupport.CurrentFiletypes() ] )
  453. def ShouldDisplayDiagnostics( self ):
  454. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  455. self.DiagnosticUiSupportedForCurrentFiletype() )
  456. def _PopulateLocationListWithLatestDiagnostics( self ):
  457. # Do nothing if loc list is already populated by diag_interface
  458. if not self._user_options[ 'always_populate_location_list' ]:
  459. self._diag_interface.PopulateLocationList( self._latest_diagnostics )
  460. return bool( self._latest_diagnostics )
  461. def UpdateDiagnosticInterface( self ):
  462. self._diag_interface.UpdateWithNewDiagnostics( self._latest_diagnostics )
  463. def FileParseRequestReady( self, block = False ):
  464. return bool( self._latest_file_parse_request and
  465. ( block or self._latest_file_parse_request.Done() ) )
  466. def HandleFileParseRequest( self, block = False ):
  467. # Order is important here:
  468. # FileParseRequestReady has a low cost, while
  469. # NativeFiletypeCompletionUsable is a blocking server request
  470. if ( self.FileParseRequestReady( block ) and
  471. self.NativeFiletypeCompletionUsable() ):
  472. if self.ShouldDisplayDiagnostics():
  473. self._latest_diagnostics = self._latest_file_parse_request.Response()
  474. self.UpdateDiagnosticInterface()
  475. else:
  476. # YCM client has a hard-coded list of filetypes which are known
  477. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  478. #
  479. # For filetypes which don't support diagnostics, we just want to check
  480. # the _latest_file_parse_request for any exception or UnknownExtraConf
  481. # response, to allow the server to raise configuration warnings, etc.
  482. # to the user. We ignore any other supplied data.
  483. self._latest_file_parse_request.Response()
  484. # We set the file parse request to None because we want to prevent
  485. # repeated issuing of the same warnings/errors/prompts. Setting this to
  486. # None makes FileParseRequestReady return False until the next
  487. # request is created.
  488. #
  489. # Note: it is the server's responsibility to determine the frequency of
  490. # error/warning/prompts when receiving a FileReadyToParse event, but
  491. # it our responsibility to ensure that we only apply the
  492. # warning/error/prompt received once (for each event).
  493. self._latest_file_parse_request = None
  494. def DebugInfo( self ):
  495. debug_info = ''
  496. if self._client_logfile:
  497. debug_info += 'Client logfile: {0}\n'.format( self._client_logfile )
  498. debug_info += FormatDebugInfoResponse( SendDebugInfoRequest() )
  499. debug_info += (
  500. 'Server running at: {0}\n'
  501. 'Server process ID: {1}\n'.format( BaseRequest.server_location,
  502. self._server_popen.pid ) )
  503. if self._server_stdout and self._server_stderr:
  504. debug_info += ( 'Server logfiles:\n'
  505. ' {0}\n'
  506. ' {1}'.format( self._server_stdout,
  507. self._server_stderr ) )
  508. return debug_info
  509. def GetLogfiles( self ):
  510. logfiles_list = [ self._client_logfile,
  511. self._server_stdout,
  512. self._server_stderr ]
  513. debug_info = SendDebugInfoRequest()
  514. if debug_info:
  515. completer = debug_info[ 'completer' ]
  516. if completer:
  517. for server in completer[ 'servers' ]:
  518. logfiles_list.extend( server[ 'logfiles' ] )
  519. logfiles = {}
  520. for logfile in logfiles_list:
  521. logfiles[ os.path.basename( logfile ) ] = logfile
  522. return logfiles
  523. def _OpenLogfile( self, logfile ):
  524. # Open log files in a horizontal window with the same behavior as the
  525. # preview window (same height and winfixheight enabled). Automatically
  526. # watch for changes. Set the cursor position at the end of the file.
  527. options = {
  528. 'size': vimsupport.GetIntValue( '&previewheight' ),
  529. 'fix': True,
  530. 'focus': False,
  531. 'watch': True,
  532. 'position': 'end'
  533. }
  534. vimsupport.OpenFilename( logfile, options )
  535. def _CloseLogfile( self, logfile ):
  536. vimsupport.CloseBuffersForFilename( logfile )
  537. def ToggleLogs( self, *filenames ):
  538. logfiles = self.GetLogfiles()
  539. if not filenames:
  540. vimsupport.PostVimMessage(
  541. 'Available logfiles are:\n'
  542. '{0}'.format( '\n'.join( sorted( list( logfiles ) ) ) ) )
  543. return
  544. for filename in set( filenames ):
  545. if filename not in logfiles:
  546. continue
  547. logfile = logfiles[ filename ]
  548. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  549. self._OpenLogfile( logfile )
  550. continue
  551. self._CloseLogfile( logfile )
  552. def CurrentFiletypeCompletionEnabled( self ):
  553. filetypes = vimsupport.CurrentFiletypes()
  554. filetype_to_disable = self._user_options[
  555. 'filetype_specific_completion_to_disable' ]
  556. if '*' in filetype_to_disable:
  557. return False
  558. else:
  559. return not any([ x in filetype_to_disable for x in filetypes ])
  560. def ShowDetailedDiagnostic( self ):
  561. with HandleServerException():
  562. detailed_diagnostic = BaseRequest.PostDataToHandler(
  563. BuildRequestData(), 'detailed_diagnostic' )
  564. if 'message' in detailed_diagnostic:
  565. vimsupport.PostVimMessage( detailed_diagnostic[ 'message' ],
  566. warning = False )
  567. def ForceCompileAndDiagnostics( self ):
  568. if not self.NativeFiletypeCompletionUsable():
  569. vimsupport.PostVimMessage(
  570. 'Native filetype completion not supported for current file, '
  571. 'cannot force recompilation.', warning = False )
  572. return False
  573. vimsupport.PostVimMessage(
  574. 'Forcing compilation, this will block Vim until done.',
  575. warning = False )
  576. self.OnFileReadyToParse()
  577. self.HandleFileParseRequest( block = True )
  578. vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
  579. return True
  580. def ShowDiagnostics( self ):
  581. if not self.ForceCompileAndDiagnostics():
  582. return
  583. if not self._PopulateLocationListWithLatestDiagnostics():
  584. vimsupport.PostVimMessage( 'No warnings or errors detected.',
  585. warning = False )
  586. return
  587. if self._user_options[ 'open_loclist_on_ycm_diags' ]:
  588. vimsupport.OpenLocationList( focus = True )
  589. def _AddSyntaxDataIfNeeded( self, extra_data ):
  590. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  591. return
  592. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  593. if filetype in self._filetypes_with_keywords_loaded:
  594. return
  595. if self._server_is_ready_with_cache:
  596. self._filetypes_with_keywords_loaded.add( filetype )
  597. extra_data[ 'syntax_keywords' ] = list(
  598. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  599. def _AddTagsFilesIfNeeded( self, extra_data ):
  600. def GetTagFiles():
  601. tag_files = vim.eval( 'tagfiles()' )
  602. return [ os.path.join( utils.GetCurrentDirectory(), tag_file )
  603. for tag_file in tag_files ]
  604. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  605. return
  606. extra_data[ 'tag_files' ] = GetTagFiles()
  607. def _AddExtraConfDataIfNeeded( self, extra_data ):
  608. def BuildExtraConfData( extra_conf_vim_data ):
  609. return dict( ( expr, vimsupport.VimExpressionToPythonType( expr ) )
  610. for expr in extra_conf_vim_data )
  611. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  612. if extra_conf_vim_data:
  613. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  614. extra_conf_vim_data )
  615. def _AddUltiSnipsDataIfNeeded( self, extra_data ):
  616. # See :h UltiSnips#SnippetsInCurrentScope.
  617. try:
  618. vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
  619. except vim.error:
  620. return
  621. snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
  622. extra_data[ 'ultisnips_snippets' ] = [
  623. { 'trigger': trigger,
  624. 'description': snippet[ 'description' ] }
  625. for trigger, snippet in iteritems( snippets )
  626. ]