youcompleteme.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. DIAGNOSTIC_UI_FILETYPES,
  35. DIAGNOSTIC_UI_ASYNC_FILETYPES )
  36. from ycmd import utils
  37. from ycmd import server_utils
  38. from ycmd.request_wrap import RequestWrap
  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. from ycm.client.shutdown_request import SendShutdownRequest
  53. from ycm.client.messages_request import MessagesPoll
  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. "Type ':YcmToggleLogs {logfile}' to check the logs." )
  77. CORE_UNEXPECTED_MESSAGE = (
  78. "Unexpected error while loading the YCM core library. "
  79. "Type ':YcmToggleLogs {logfile}' 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 = 1800 # 30 minutes
  95. CLIENT_LOGFILE_FORMAT = 'ycm_'
  96. SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'
  97. # Flag to set a file handle inheritable by child processes on Windows. See
  98. # https://msdn.microsoft.com/en-us/library/ms724935.aspx
  99. HANDLE_FLAG_INHERIT = 0x00000001
  100. # The following two methods exist for testability only
  101. def _CompleteDoneHook_CSharp( ycm ):
  102. ycm._OnCompleteDone_Csharp()
  103. def _CompleteDoneHook_Java( ycm ):
  104. ycm._OnCompleteDone_Java()
  105. class YouCompleteMe( object ):
  106. def __init__( self, user_options ):
  107. self._available_completers = {}
  108. self._user_options = user_options
  109. self._user_notified_about_crash = False
  110. self._omnicomp = OmniCompleter( user_options )
  111. self._buffers = BufferDict( user_options )
  112. self._latest_completion_request = None
  113. self._logger = logging.getLogger( 'ycm' )
  114. self._client_logfile = None
  115. self._server_stdout = None
  116. self._server_stderr = None
  117. self._server_popen = None
  118. self._filetypes_with_keywords_loaded = set()
  119. self._ycmd_keepalive = YcmdKeepalive()
  120. self._server_is_ready_with_cache = False
  121. self._SetUpLogging()
  122. self._SetUpServer()
  123. self._ycmd_keepalive.Start()
  124. self._complete_done_hooks = {
  125. 'cs': _CompleteDoneHook_CSharp,
  126. 'java': _CompleteDoneHook_Java,
  127. }
  128. def _SetUpServer( self ):
  129. self._available_completers = {}
  130. self._user_notified_about_crash = False
  131. self._filetypes_with_keywords_loaded = set()
  132. self._server_is_ready_with_cache = False
  133. self._message_poll_request = None
  134. hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
  135. options_dict = dict( self._user_options )
  136. options_dict[ 'hmac_secret' ] = utils.ToUnicode(
  137. base64.b64encode( hmac_secret ) )
  138. options_dict[ 'server_keep_logfiles' ] = self._user_options[
  139. 'keep_logfiles' ]
  140. # The temp options file is deleted by ycmd during startup.
  141. with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
  142. json.dump( options_dict, options_file )
  143. server_port = utils.GetUnusedLocalhostPort()
  144. BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
  145. BaseRequest.hmac_secret = hmac_secret
  146. try:
  147. python_interpreter = paths.PathToPythonInterpreter()
  148. except RuntimeError as error:
  149. error_message = (
  150. "Unable to start the ycmd server. {0}. "
  151. "Correct the error then restart the server "
  152. "with ':YcmRestartServer'.".format( str( error ).rstrip( '.' ) ) )
  153. self._logger.exception( error_message )
  154. vimsupport.PostVimMessage( error_message )
  155. return
  156. args = [ python_interpreter,
  157. paths.PathToServerScript(),
  158. '--port={0}'.format( server_port ),
  159. '--options_file={0}'.format( options_file.name ),
  160. '--log={0}'.format( self._user_options[ 'log_level' ] ),
  161. '--idle_suicide_seconds={0}'.format(
  162. SERVER_IDLE_SUICIDE_SECONDS ) ]
  163. self._server_stdout = utils.CreateLogfile(
  164. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
  165. self._server_stderr = utils.CreateLogfile(
  166. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
  167. args.append( '--stdout={0}'.format( self._server_stdout ) )
  168. args.append( '--stderr={0}'.format( self._server_stderr ) )
  169. if self._user_options[ 'keep_logfiles' ]:
  170. args.append( '--keep_logfiles' )
  171. self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
  172. stdout = PIPE, stderr = PIPE )
  173. def _SetUpLogging( self ):
  174. def FreeFileFromOtherProcesses( file_object ):
  175. if utils.OnWindows():
  176. from ctypes import windll
  177. import msvcrt
  178. file_handle = msvcrt.get_osfhandle( file_object.fileno() )
  179. windll.kernel32.SetHandleInformation( file_handle,
  180. HANDLE_FLAG_INHERIT,
  181. 0 )
  182. self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
  183. log_level = self._user_options[ 'log_level' ]
  184. numeric_level = getattr( logging, log_level.upper(), None )
  185. if not isinstance( numeric_level, int ):
  186. raise ValueError( 'Invalid log level: {0}'.format( log_level ) )
  187. self._logger.setLevel( numeric_level )
  188. handler = logging.FileHandler( self._client_logfile )
  189. # On Windows and Python prior to 3.4, file handles are inherited by child
  190. # processes started with at least one replaced standard stream, which is the
  191. # case when we start the ycmd server (we are redirecting all standard
  192. # outputs into a pipe). These files cannot be removed while the child
  193. # processes are still up. This is not desirable for a logfile because we
  194. # want to remove it at Vim exit without having to wait for the ycmd server
  195. # to be completely shut down. We need to make the logfile handle
  196. # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
  197. # details.
  198. FreeFileFromOtherProcesses( handler.stream )
  199. formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
  200. handler.setFormatter( formatter )
  201. self._logger.addHandler( handler )
  202. def IsServerAlive( self ):
  203. # When the process hasn't finished yet, poll() returns None.
  204. return bool( self._server_popen ) and self._server_popen.poll() is None
  205. def CheckIfServerIsReady( self ):
  206. if not self._server_is_ready_with_cache:
  207. with HandleServerException( display = False ):
  208. self._server_is_ready_with_cache = BaseRequest.GetDataFromHandler(
  209. 'ready' )
  210. return self._server_is_ready_with_cache
  211. def IsServerReady( self ):
  212. return self._server_is_ready_with_cache
  213. def NotifyUserIfServerCrashed( self ):
  214. if ( not self._server_popen or self._user_notified_about_crash or
  215. self.IsServerAlive() ):
  216. return
  217. self._user_notified_about_crash = True
  218. return_code = self._server_popen.poll()
  219. logfile = os.path.basename( self._server_stderr )
  220. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  221. error_message = CORE_UNEXPECTED_MESSAGE.format(
  222. logfile = logfile )
  223. elif return_code == server_utils.CORE_MISSING_STATUS:
  224. error_message = CORE_MISSING_MESSAGE
  225. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  226. error_message = CORE_PYTHON2_MESSAGE
  227. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  228. error_message = CORE_PYTHON3_MESSAGE
  229. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  230. error_message = CORE_OUTDATED_MESSAGE
  231. else:
  232. error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format(
  233. code = return_code,
  234. logfile = logfile )
  235. error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
  236. self._logger.error( error_message )
  237. vimsupport.PostVimMessage( error_message )
  238. def ServerPid( self ):
  239. if not self._server_popen:
  240. return -1
  241. return self._server_popen.pid
  242. def _ShutdownServer( self ):
  243. SendShutdownRequest()
  244. def RestartServer( self ):
  245. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  246. self._ShutdownServer()
  247. self._SetUpServer()
  248. def SendCompletionRequest( self, force_semantic = False ):
  249. request_data = BuildRequestData()
  250. request_data[ 'force_semantic' ] = force_semantic
  251. if ( not self.NativeFiletypeCompletionAvailable() and
  252. self.CurrentFiletypeCompletionEnabled() ):
  253. wrapped_request_data = RequestWrap( request_data )
  254. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  255. self._latest_completion_request = OmniCompletionRequest(
  256. self._omnicomp, wrapped_request_data )
  257. self._latest_completion_request.Start()
  258. return
  259. self._AddExtraConfDataIfNeeded( request_data )
  260. self._latest_completion_request = CompletionRequest( request_data )
  261. self._latest_completion_request.Start()
  262. def CompletionRequestReady( self ):
  263. return bool( self._latest_completion_request and
  264. self._latest_completion_request.Done() )
  265. def GetCompletionResponse( self ):
  266. response = self._latest_completion_request.Response()
  267. response[ 'completions' ] = base.AdjustCandidateInsertionText(
  268. response[ 'completions' ] )
  269. return response
  270. def SendCommandRequest( self, arguments, completer ):
  271. extra_data = {}
  272. self._AddExtraConfDataIfNeeded( extra_data )
  273. return SendCommandRequest( arguments, completer, extra_data )
  274. def GetDefinedSubcommands( self ):
  275. with HandleServerException():
  276. return BaseRequest.PostDataToHandler( BuildRequestData(),
  277. 'defined_subcommands' )
  278. return []
  279. def GetCurrentCompletionRequest( self ):
  280. return self._latest_completion_request
  281. def GetOmniCompleter( self ):
  282. return self._omnicomp
  283. def FiletypeCompleterExistsForFiletype( self, filetype ):
  284. try:
  285. return self._available_completers[ filetype ]
  286. except KeyError:
  287. pass
  288. exists_completer = SendCompleterAvailableRequest( filetype )
  289. if exists_completer is None:
  290. return False
  291. self._available_completers[ filetype ] = exists_completer
  292. return exists_completer
  293. def NativeFiletypeCompletionAvailable( self ):
  294. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  295. vimsupport.CurrentFiletypes() ] )
  296. def NativeFiletypeCompletionUsable( self ):
  297. return ( self.CurrentFiletypeCompletionEnabled() and
  298. self.NativeFiletypeCompletionAvailable() )
  299. def NeedsReparse( self ):
  300. return self.CurrentBuffer().NeedsReparse()
  301. def UpdateWithNewDiagnosticsForFile( self, filepath, diagnostics ):
  302. bufnr = vimsupport.GetBufferNumberForFilename( filepath )
  303. if bufnr in self._buffers and vimsupport.BufferIsVisible( bufnr ):
  304. # Note: We only update location lists, etc. for visible buffers, because
  305. # otherwise we defualt to using the curren location list and the results
  306. # are that non-visible buffer errors clobber visible ones.
  307. self._buffers[ bufnr ].UpdateWithNewDiagnostics( diagnostics )
  308. else:
  309. # The project contains errors in file "filepath", but that file is not
  310. # open in any buffer. This happens for Language Server Protocol-based
  311. # completers, as they return diagnostics for the entire "project"
  312. # asynchronously (rather than per-file in the response to the parse
  313. # request).
  314. #
  315. # There are a number of possible approaches for
  316. # this, but for now we simply ignore them. Other options include:
  317. # - Use the QuickFix list to report project errors?
  318. # - Use a special buffer for project errors
  319. # - Put them in the location list of whatever the "current" buffer is
  320. # - Store them in case the buffer is opened later
  321. # - add a :YcmProjectDiags command
  322. # - Add them to errror/warning _counts_ but not any actual location list
  323. # or other
  324. # - etc.
  325. #
  326. # However, none of those options are great, and lead to their own
  327. # complexities. So for now, we just ignore these diagnostics for files not
  328. # open in any buffer.
  329. pass
  330. def OnPeriodicTick( self ):
  331. if not self.IsServerAlive():
  332. # Server has died. We'll reset when the server is started again.
  333. return False
  334. elif not self.IsServerReady():
  335. # Try again in a jiffy
  336. return True
  337. if not self._message_poll_request:
  338. self._message_poll_request = MessagesPoll()
  339. if not self._message_poll_request.Poll( self ):
  340. # Don't poll again until some event which might change the server's mind
  341. # about whether to provide messages for the current buffer (e.g. buffer
  342. # visit, file ready to parse, etc.)
  343. self._message_poll_request = None
  344. return False
  345. # Poll again in a jiffy
  346. return True
  347. def OnFileReadyToParse( self ):
  348. if not self.IsServerAlive():
  349. self.NotifyUserIfServerCrashed()
  350. return
  351. if not self.IsServerReady():
  352. return
  353. extra_data = {}
  354. self._AddTagsFilesIfNeeded( extra_data )
  355. self._AddSyntaxDataIfNeeded( extra_data )
  356. self._AddExtraConfDataIfNeeded( extra_data )
  357. self.CurrentBuffer().SendParseRequest( extra_data )
  358. def OnBufferUnload( self, deleted_buffer_number ):
  359. SendEventNotificationAsync( 'BufferUnload', deleted_buffer_number )
  360. def OnBufferVisit( self ):
  361. extra_data = {}
  362. self._AddUltiSnipsDataIfNeeded( extra_data )
  363. SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
  364. def CurrentBuffer( self ):
  365. return self._buffers[ vimsupport.GetCurrentBufferNumber() ]
  366. def OnInsertLeave( self ):
  367. SendEventNotificationAsync( 'InsertLeave' )
  368. def OnCursorMoved( self ):
  369. self.CurrentBuffer().OnCursorMoved()
  370. def _CleanLogfile( self ):
  371. logging.shutdown()
  372. if not self._user_options[ 'keep_logfiles' ]:
  373. if self._client_logfile:
  374. utils.RemoveIfExists( self._client_logfile )
  375. def OnVimLeave( self ):
  376. self._ShutdownServer()
  377. self._CleanLogfile()
  378. def OnCurrentIdentifierFinished( self ):
  379. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  380. def OnCompleteDone( self ):
  381. complete_done_actions = self.GetCompleteDoneHooks()
  382. for action in complete_done_actions:
  383. action(self)
  384. def GetCompleteDoneHooks( self ):
  385. filetypes = vimsupport.CurrentFiletypes()
  386. for key, value in iteritems( self._complete_done_hooks ):
  387. if key in filetypes:
  388. yield value
  389. def GetCompletionsUserMayHaveCompleted( self ):
  390. latest_completion_request = self.GetCurrentCompletionRequest()
  391. if not latest_completion_request or not latest_completion_request.Done():
  392. return []
  393. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  394. completions = latest_completion_request.RawResponse()[ 'completions' ]
  395. if 'user_data' in completed_item and completed_item[ 'user_data' ] != '':
  396. # Vim supports user_data (8.0.1493) or later, so we actually know the
  397. # _exact_ element that was selected, having put its index in the user_data
  398. # field.
  399. return [ completions[ int( completed_item[ 'user_data' ] ) ] ]
  400. # Otherwise, we have to guess by matching the values in the completed item
  401. # and the list of completions. Sometimes this returns multiple
  402. # possibilities, which is essentially unresolvable.
  403. result = self._FilterToMatchingCompletions( completed_item,
  404. completions,
  405. True )
  406. result = list( result )
  407. if result:
  408. return result
  409. if self._HasCompletionsThatCouldBeCompletedWithMoreText( completed_item,
  410. completions ):
  411. # Since the way that YCM works leads to CompleteDone called on every
  412. # character, return blank if the completion might not be done. This won't
  413. # match if the completion is ended with typing a non-keyword character.
  414. return []
  415. result = self._FilterToMatchingCompletions( completed_item,
  416. completions,
  417. False )
  418. return list( result )
  419. def _FilterToMatchingCompletions( self,
  420. completed_item,
  421. completions,
  422. full_match_only ):
  423. """Filter to completions matching the item Vim said was completed"""
  424. match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only
  425. else [ 'word' ] )
  426. for index, completion in enumerate( completions ):
  427. item = ConvertCompletionDataToVimData( index, completion )
  428. def matcher( key ):
  429. return ( utils.ToUnicode( completed_item.get( key, "" ) ) ==
  430. utils.ToUnicode( item.get( key, "" ) ) )
  431. if all( [ matcher( i ) for i in match_keys ] ):
  432. yield completion
  433. def _HasCompletionsThatCouldBeCompletedWithMoreText( self,
  434. completed_item,
  435. completions ):
  436. if not completed_item:
  437. return False
  438. completed_word = utils.ToUnicode( completed_item[ 'word' ] )
  439. if not completed_word:
  440. return False
  441. # Sometimes CompleteDone is called after the next character is inserted.
  442. # If so, use inserted character to filter possible completions further.
  443. text = vimsupport.TextBeforeCursor()
  444. reject_exact_match = True
  445. if text and text[ -1 ] != completed_word[ -1 ]:
  446. reject_exact_match = False
  447. completed_word += text[ -1 ]
  448. for index, completion in enumerate( completions ):
  449. word = utils.ToUnicode(
  450. ConvertCompletionDataToVimData( index, completion )[ 'word' ] )
  451. if reject_exact_match and word == completed_word:
  452. continue
  453. if word.startswith( completed_word ):
  454. return True
  455. return False
  456. def _OnCompleteDone_Csharp( self ):
  457. completions = self.GetCompletionsUserMayHaveCompleted()
  458. namespaces = [ self._GetRequiredNamespaceImport( c )
  459. for c in completions ]
  460. namespaces = [ n for n in namespaces if n ]
  461. if not namespaces:
  462. return
  463. if len( namespaces ) > 1:
  464. choices = [ "{0} {1}".format( i + 1, n )
  465. for i, n in enumerate( namespaces ) ]
  466. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  467. if choice < 0:
  468. return
  469. namespace = namespaces[ choice ]
  470. else:
  471. namespace = namespaces[ 0 ]
  472. vimsupport.InsertNamespace( namespace )
  473. def _GetRequiredNamespaceImport( self, completion ):
  474. if ( "extra_data" not in completion
  475. or "required_namespace_import" not in completion[ "extra_data" ] ):
  476. return None
  477. return completion[ "extra_data" ][ "required_namespace_import" ]
  478. def _OnCompleteDone_Java( self ):
  479. completions = self.GetCompletionsUserMayHaveCompleted()
  480. fixit_completions = [ self._GetFixItCompletion( c ) for c in completions ]
  481. fixit_completions = [ f for f in fixit_completions if f ]
  482. if not fixit_completions:
  483. return
  484. # If we have user_data in completions (8.0.1493 or later), then we would
  485. # only ever return max. 1 completion here. However, if we had to guess, it
  486. # is possible that we matched multiple completion items (e.g. for overloads,
  487. # or similar classes in multiple packages). In any case, rather than
  488. # prompting the user and disturbing her workflow, we just apply the first
  489. # one. This might be wrong, but the solution is to use a (very) new version
  490. # of Vim which supports user_data on completion items
  491. fixit_completion = fixit_completions[ 0 ]
  492. for fixit in fixit_completion:
  493. vimsupport.ReplaceChunks( fixit[ 'chunks' ], silent=True )
  494. def _GetFixItCompletion( self, completion ):
  495. if ( "extra_data" not in completion
  496. or "fixits" not in completion[ "extra_data" ] ):
  497. return None
  498. return completion[ "extra_data" ][ "fixits" ]
  499. def GetErrorCount( self ):
  500. return self.CurrentBuffer().GetErrorCount()
  501. def GetWarningCount( self ):
  502. return self.CurrentBuffer().GetWarningCount()
  503. def DiagnosticUiSupportedForCurrentFiletype( self ):
  504. return any( [ x in DIAGNOSTIC_UI_FILETYPES or
  505. x in DIAGNOSTIC_UI_ASYNC_FILETYPES
  506. for x in vimsupport.CurrentFiletypes() ] )
  507. def ShouldDisplayDiagnostics( self ):
  508. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  509. self.DiagnosticUiSupportedForCurrentFiletype() )
  510. def _PopulateLocationListWithLatestDiagnostics( self ):
  511. return self.CurrentBuffer().PopulateLocationList()
  512. def FileParseRequestReady( self ):
  513. # Return True if server is not ready yet, to stop repeating check timer.
  514. return ( not self.IsServerReady() or
  515. self.CurrentBuffer().FileParseRequestReady() )
  516. def HandleFileParseRequest( self, block = False ):
  517. if not self.IsServerReady():
  518. return
  519. current_buffer = self.CurrentBuffer()
  520. # Order is important here:
  521. # FileParseRequestReady has a low cost, while
  522. # NativeFiletypeCompletionUsable is a blocking server request
  523. if ( not current_buffer.IsResponseHandled() and
  524. current_buffer.FileParseRequestReady( block ) and
  525. self.NativeFiletypeCompletionUsable() ):
  526. if self.ShouldDisplayDiagnostics():
  527. # Forcefuly update the location list, etc. from the parse request when
  528. # doing something like :YcmDiags
  529. current_buffer.UpdateDiagnostics( block is True )
  530. else:
  531. # YCM client has a hard-coded list of filetypes which are known
  532. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  533. #
  534. # For filetypes which don't support diagnostics, we just want to check
  535. # the _latest_file_parse_request for any exception or UnknownExtraConf
  536. # response, to allow the server to raise configuration warnings, etc.
  537. # to the user. We ignore any other supplied data.
  538. current_buffer.GetResponse()
  539. # We set the file parse request as handled because we want to prevent
  540. # repeated issuing of the same warnings/errors/prompts. Setting this
  541. # makes IsRequestHandled return True until the next request is created.
  542. #
  543. # Note: it is the server's responsibility to determine the frequency of
  544. # error/warning/prompts when receiving a FileReadyToParse event, but
  545. # it is our responsibility to ensure that we only apply the
  546. # warning/error/prompt received once (for each event).
  547. current_buffer.MarkResponseHandled()
  548. def DebugInfo( self ):
  549. debug_info = ''
  550. if self._client_logfile:
  551. debug_info += 'Client logfile: {0}\n'.format( self._client_logfile )
  552. extra_data = {}
  553. self._AddExtraConfDataIfNeeded( extra_data )
  554. debug_info += FormatDebugInfoResponse( SendDebugInfoRequest( extra_data ) )
  555. debug_info += 'Server running at: {0}\n'.format(
  556. BaseRequest.server_location )
  557. if self._server_popen:
  558. debug_info += 'Server process ID: {0}\n'.format( self._server_popen.pid )
  559. if self._server_stdout and self._server_stderr:
  560. debug_info += ( 'Server logfiles:\n'
  561. ' {0}\n'
  562. ' {1}'.format( self._server_stdout,
  563. self._server_stderr ) )
  564. return debug_info
  565. def GetLogfiles( self ):
  566. logfiles_list = [ self._client_logfile,
  567. self._server_stdout,
  568. self._server_stderr ]
  569. debug_info = SendDebugInfoRequest()
  570. if debug_info:
  571. completer = debug_info[ 'completer' ]
  572. if completer:
  573. for server in completer[ 'servers' ]:
  574. logfiles_list.extend( server[ 'logfiles' ] )
  575. logfiles = {}
  576. for logfile in logfiles_list:
  577. logfiles[ os.path.basename( logfile ) ] = logfile
  578. return logfiles
  579. def _OpenLogfile( self, logfile ):
  580. # Open log files in a horizontal window with the same behavior as the
  581. # preview window (same height and winfixheight enabled). Automatically
  582. # watch for changes. Set the cursor position at the end of the file.
  583. options = {
  584. 'size': vimsupport.GetIntValue( '&previewheight' ),
  585. 'fix': True,
  586. 'focus': False,
  587. 'watch': True,
  588. 'position': 'end'
  589. }
  590. vimsupport.OpenFilename( logfile, options )
  591. def _CloseLogfile( self, logfile ):
  592. vimsupport.CloseBuffersForFilename( logfile )
  593. def ToggleLogs( self, *filenames ):
  594. logfiles = self.GetLogfiles()
  595. if not filenames:
  596. sorted_logfiles = sorted( list( logfiles ) )
  597. try:
  598. logfile_index = vimsupport.SelectFromList(
  599. 'Which logfile do you wish to open (or close if already open)?',
  600. sorted_logfiles )
  601. except RuntimeError as e:
  602. vimsupport.PostVimMessage( str( e ) )
  603. return
  604. logfile = logfiles[ sorted_logfiles[ logfile_index ] ]
  605. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  606. self._OpenLogfile( logfile )
  607. else:
  608. self._CloseLogfile( logfile )
  609. return
  610. for filename in set( filenames ):
  611. if filename not in logfiles:
  612. continue
  613. logfile = logfiles[ filename ]
  614. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  615. self._OpenLogfile( logfile )
  616. continue
  617. self._CloseLogfile( logfile )
  618. def CurrentFiletypeCompletionEnabled( self ):
  619. filetypes = vimsupport.CurrentFiletypes()
  620. filetype_to_disable = self._user_options[
  621. 'filetype_specific_completion_to_disable' ]
  622. if '*' in filetype_to_disable:
  623. return False
  624. else:
  625. return not any( [ x in filetype_to_disable for x in filetypes ] )
  626. def ShowDetailedDiagnostic( self ):
  627. with HandleServerException():
  628. detailed_diagnostic = BaseRequest.PostDataToHandler(
  629. BuildRequestData(), 'detailed_diagnostic' )
  630. if 'message' in detailed_diagnostic:
  631. vimsupport.PostVimMessage( detailed_diagnostic[ 'message' ],
  632. warning = False )
  633. def ForceCompileAndDiagnostics( self ):
  634. if not self.NativeFiletypeCompletionUsable():
  635. vimsupport.PostVimMessage(
  636. 'Native filetype completion not supported for current file, '
  637. 'cannot force recompilation.', warning = False )
  638. return False
  639. vimsupport.PostVimMessage(
  640. 'Forcing compilation, this will block Vim until done.',
  641. warning = False )
  642. self.OnFileReadyToParse()
  643. self.HandleFileParseRequest( block = True )
  644. vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
  645. return True
  646. def ShowDiagnostics( self ):
  647. if not self.ForceCompileAndDiagnostics():
  648. return
  649. if not self._PopulateLocationListWithLatestDiagnostics():
  650. vimsupport.PostVimMessage( 'No warnings or errors detected.',
  651. warning = False )
  652. return
  653. if self._user_options[ 'open_loclist_on_ycm_diags' ]:
  654. vimsupport.OpenLocationList( focus = True )
  655. def _AddSyntaxDataIfNeeded( self, extra_data ):
  656. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  657. return
  658. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  659. if filetype in self._filetypes_with_keywords_loaded:
  660. return
  661. if self.IsServerReady():
  662. self._filetypes_with_keywords_loaded.add( filetype )
  663. extra_data[ 'syntax_keywords' ] = list(
  664. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  665. def _AddTagsFilesIfNeeded( self, extra_data ):
  666. def GetTagFiles():
  667. tag_files = vim.eval( 'tagfiles()' )
  668. return [ os.path.join( utils.GetCurrentDirectory(), tag_file )
  669. for tag_file in tag_files ]
  670. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  671. return
  672. extra_data[ 'tag_files' ] = GetTagFiles()
  673. def _AddExtraConfDataIfNeeded( self, extra_data ):
  674. def BuildExtraConfData( extra_conf_vim_data ):
  675. extra_conf_data = {}
  676. for expr in extra_conf_vim_data:
  677. try:
  678. extra_conf_data[ expr ] = vimsupport.VimExpressionToPythonType( expr )
  679. except vim.error:
  680. message = (
  681. "Error evaluating '{expr}' in the 'g:ycm_extra_conf_vim_data' "
  682. "option.".format( expr = expr ) )
  683. vimsupport.PostVimMessage( message, truncate = True )
  684. self._logger.exception( message )
  685. return extra_conf_data
  686. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  687. if extra_conf_vim_data:
  688. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  689. extra_conf_vim_data )
  690. def _AddUltiSnipsDataIfNeeded( self, extra_data ):
  691. # See :h UltiSnips#SnippetsInCurrentScope.
  692. try:
  693. vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
  694. except vim.error:
  695. return
  696. snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
  697. extra_data[ 'ultisnips_snippets' ] = [
  698. { 'trigger': trigger,
  699. 'description': snippet[ 'description' ] }
  700. for trigger, snippet in iteritems( snippets )
  701. ]