youcompleteme.py 26 KB

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