youcompleteme.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. from ycm.client.completer_available_request import SendCompleterAvailableRequest
  44. from ycm.client.command_request import SendCommandRequest
  45. from ycm.client.completion_request import CompletionRequest
  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. from ycm.client.messages_request import MessagesPoll
  52. def PatchNoProxy():
  53. current_value = os.environ.get('no_proxy', '')
  54. additions = '127.0.0.1,localhost'
  55. os.environ['no_proxy'] = ( additions if not current_value
  56. else current_value + ',' + additions )
  57. # We need this so that Requests doesn't end up using the local HTTP proxy when
  58. # talking to ycmd. Users should actually be setting this themselves when
  59. # configuring a proxy server on their machine, but most don't know they need to
  60. # or how to do it, so we do it for them.
  61. # Relevant issues:
  62. # https://github.com/Valloric/YouCompleteMe/issues/641
  63. # https://github.com/kennethreitz/requests/issues/879
  64. PatchNoProxy()
  65. # Force the Python interpreter embedded in Vim (in which we are running) to
  66. # ignore the SIGINT signal. This helps reduce the fallout of a user pressing
  67. # Ctrl-C in Vim.
  68. signal.signal( signal.SIGINT, signal.SIG_IGN )
  69. HMAC_SECRET_LENGTH = 16
  70. SERVER_SHUTDOWN_MESSAGE = (
  71. "The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." )
  72. EXIT_CODE_UNEXPECTED_MESSAGE = (
  73. "Unexpected exit code {code}. "
  74. "Type ':YcmToggleLogs {logfile}' to check the logs." )
  75. CORE_UNEXPECTED_MESSAGE = (
  76. "Unexpected error while loading the YCM core library. "
  77. "Type ':YcmToggleLogs {logfile}' to check the logs." )
  78. CORE_MISSING_MESSAGE = (
  79. 'YCM core library not detected; you need to compile YCM before using it. '
  80. 'Follow the instructions in the documentation.' )
  81. CORE_PYTHON2_MESSAGE = (
  82. "YCM core library compiled for Python 2 but loaded in Python 3. "
  83. "Set the 'g:ycm_server_python_interpreter' option to a Python 2 "
  84. "interpreter path." )
  85. CORE_PYTHON3_MESSAGE = (
  86. "YCM core library compiled for Python 3 but loaded in Python 2. "
  87. "Set the 'g:ycm_server_python_interpreter' option to a Python 3 "
  88. "interpreter path." )
  89. CORE_OUTDATED_MESSAGE = (
  90. 'YCM core library too old; PLEASE RECOMPILE by running the install.py '
  91. 'script. See the documentation for more details.' )
  92. SERVER_IDLE_SUICIDE_SECONDS = 1800 # 30 minutes
  93. CLIENT_LOGFILE_FORMAT = 'ycm_'
  94. SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'
  95. # Flag to set a file handle inheritable by child processes on Windows. See
  96. # https://msdn.microsoft.com/en-us/library/ms724935.aspx
  97. HANDLE_FLAG_INHERIT = 0x00000001
  98. class YouCompleteMe( object ):
  99. def __init__( self, user_options ):
  100. self._available_completers = {}
  101. self._user_options = user_options
  102. self._user_notified_about_crash = False
  103. self._omnicomp = OmniCompleter( user_options )
  104. self._buffers = BufferDict( user_options )
  105. self._latest_completion_request = None
  106. self._logger = logging.getLogger( 'ycm' )
  107. self._client_logfile = None
  108. self._server_stdout = None
  109. self._server_stderr = None
  110. self._server_popen = None
  111. self._filetypes_with_keywords_loaded = set()
  112. self._ycmd_keepalive = YcmdKeepalive()
  113. self._server_is_ready_with_cache = False
  114. self._SetUpLogging()
  115. self._SetUpServer()
  116. self._ycmd_keepalive.Start()
  117. def _SetUpServer( self ):
  118. self._available_completers = {}
  119. self._user_notified_about_crash = False
  120. self._filetypes_with_keywords_loaded = set()
  121. self._server_is_ready_with_cache = False
  122. self._message_poll_request = None
  123. hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
  124. options_dict = dict( self._user_options )
  125. options_dict[ 'hmac_secret' ] = utils.ToUnicode(
  126. base64.b64encode( hmac_secret ) )
  127. options_dict[ 'server_keep_logfiles' ] = self._user_options[
  128. 'keep_logfiles' ]
  129. # The temp options file is deleted by ycmd during startup.
  130. with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
  131. json.dump( options_dict, options_file )
  132. server_port = utils.GetUnusedLocalhostPort()
  133. BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
  134. BaseRequest.hmac_secret = hmac_secret
  135. try:
  136. python_interpreter = paths.PathToPythonInterpreter()
  137. except RuntimeError as error:
  138. error_message = (
  139. "Unable to start the ycmd server. {0}. "
  140. "Correct the error then restart the server "
  141. "with ':YcmRestartServer'.".format( str( error ).rstrip( '.' ) ) )
  142. self._logger.exception( error_message )
  143. vimsupport.PostVimMessage( error_message )
  144. return
  145. args = [ python_interpreter,
  146. paths.PathToServerScript(),
  147. '--port={0}'.format( server_port ),
  148. '--options_file={0}'.format( options_file.name ),
  149. '--log={0}'.format( self._user_options[ 'log_level' ] ),
  150. '--idle_suicide_seconds={0}'.format(
  151. SERVER_IDLE_SUICIDE_SECONDS ) ]
  152. self._server_stdout = utils.CreateLogfile(
  153. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
  154. self._server_stderr = utils.CreateLogfile(
  155. SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
  156. args.append( '--stdout={0}'.format( self._server_stdout ) )
  157. args.append( '--stderr={0}'.format( self._server_stderr ) )
  158. if self._user_options[ 'keep_logfiles' ]:
  159. args.append( '--keep_logfiles' )
  160. self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
  161. stdout = PIPE, stderr = PIPE )
  162. def _SetUpLogging( self ):
  163. def FreeFileFromOtherProcesses( file_object ):
  164. if utils.OnWindows():
  165. from ctypes import windll
  166. import msvcrt
  167. file_handle = msvcrt.get_osfhandle( file_object.fileno() )
  168. windll.kernel32.SetHandleInformation( file_handle,
  169. HANDLE_FLAG_INHERIT,
  170. 0 )
  171. self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )
  172. log_level = self._user_options[ 'log_level' ]
  173. numeric_level = getattr( logging, log_level.upper(), None )
  174. if not isinstance( numeric_level, int ):
  175. raise ValueError( 'Invalid log level: {0}'.format( log_level ) )
  176. self._logger.setLevel( numeric_level )
  177. handler = logging.FileHandler( self._client_logfile )
  178. # On Windows and Python prior to 3.4, file handles are inherited by child
  179. # processes started with at least one replaced standard stream, which is the
  180. # case when we start the ycmd server (we are redirecting all standard
  181. # outputs into a pipe). These files cannot be removed while the child
  182. # processes are still up. This is not desirable for a logfile because we
  183. # want to remove it at Vim exit without having to wait for the ycmd server
  184. # to be completely shut down. We need to make the logfile handle
  185. # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
  186. # details.
  187. FreeFileFromOtherProcesses( handler.stream )
  188. formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
  189. handler.setFormatter( formatter )
  190. self._logger.addHandler( handler )
  191. def IsServerAlive( self ):
  192. # When the process hasn't finished yet, poll() returns None.
  193. return bool( self._server_popen ) and self._server_popen.poll() is None
  194. def CheckIfServerIsReady( self ):
  195. if not self._server_is_ready_with_cache and self.IsServerAlive():
  196. self._server_is_ready_with_cache = BaseRequest.GetDataFromHandler(
  197. 'ready', display_message = False )
  198. return self._server_is_ready_with_cache
  199. def IsServerReady( self ):
  200. return self._server_is_ready_with_cache
  201. def NotifyUserIfServerCrashed( self ):
  202. if ( not self._server_popen or self._user_notified_about_crash or
  203. self.IsServerAlive() ):
  204. return
  205. self._user_notified_about_crash = True
  206. return_code = self._server_popen.poll()
  207. logfile = os.path.basename( self._server_stderr )
  208. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  209. error_message = CORE_UNEXPECTED_MESSAGE.format(
  210. logfile = logfile )
  211. elif return_code == server_utils.CORE_MISSING_STATUS:
  212. error_message = CORE_MISSING_MESSAGE
  213. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  214. error_message = CORE_PYTHON2_MESSAGE
  215. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  216. error_message = CORE_PYTHON3_MESSAGE
  217. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  218. error_message = CORE_OUTDATED_MESSAGE
  219. else:
  220. error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format(
  221. code = return_code,
  222. logfile = logfile )
  223. error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
  224. self._logger.error( error_message )
  225. vimsupport.PostVimMessage( error_message )
  226. def ServerPid( self ):
  227. if not self._server_popen:
  228. return -1
  229. return self._server_popen.pid
  230. def _ShutdownServer( self ):
  231. SendShutdownRequest()
  232. def RestartServer( self ):
  233. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  234. self._ShutdownServer()
  235. self._SetUpServer()
  236. def SendCompletionRequest( self, force_semantic = False ):
  237. request_data = BuildRequestData()
  238. request_data[ 'force_semantic' ] = force_semantic
  239. if ( not self.NativeFiletypeCompletionAvailable() and
  240. self.CurrentFiletypeCompletionEnabled() ):
  241. wrapped_request_data = RequestWrap( request_data )
  242. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  243. self._latest_completion_request = OmniCompletionRequest(
  244. self._omnicomp, wrapped_request_data )
  245. self._latest_completion_request.Start()
  246. return
  247. self._AddExtraConfDataIfNeeded( request_data )
  248. self._latest_completion_request = CompletionRequest( request_data )
  249. self._latest_completion_request.Start()
  250. def CompletionRequestReady( self ):
  251. return bool( self._latest_completion_request and
  252. self._latest_completion_request.Done() )
  253. def GetCompletionResponse( self ):
  254. response = self._latest_completion_request.Response()
  255. response[ 'completions' ] = base.AdjustCandidateInsertionText(
  256. response[ 'completions' ] )
  257. return response
  258. def SendCommandRequest( self,
  259. arguments,
  260. completer,
  261. has_range,
  262. start_line,
  263. end_line ):
  264. extra_data = {
  265. 'options': {
  266. 'tab_size': vimsupport.GetIntValue( 'shiftwidth()' ),
  267. 'insert_spaces': vimsupport.GetBoolValue( '&expandtab' )
  268. }
  269. }
  270. if has_range:
  271. extra_data.update( vimsupport.BuildRange( start_line, end_line ) )
  272. self._AddExtraConfDataIfNeeded( extra_data )
  273. return SendCommandRequest( arguments, completer, extra_data )
  274. def GetDefinedSubcommands( self ):
  275. subcommands = BaseRequest.PostDataToHandler( BuildRequestData(),
  276. 'defined_subcommands' )
  277. return subcommands if subcommands else []
  278. def GetCurrentCompletionRequest( self ):
  279. return self._latest_completion_request
  280. def GetOmniCompleter( self ):
  281. return self._omnicomp
  282. def FiletypeCompleterExistsForFiletype( self, filetype ):
  283. try:
  284. return self._available_completers[ filetype ]
  285. except KeyError:
  286. pass
  287. exists_completer = SendCompleterAvailableRequest( filetype )
  288. if exists_completer is None:
  289. return False
  290. self._available_completers[ filetype ] = exists_completer
  291. return exists_completer
  292. def NativeFiletypeCompletionAvailable( self ):
  293. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  294. vimsupport.CurrentFiletypes() ] )
  295. def NativeFiletypeCompletionUsable( self ):
  296. return ( self.CurrentFiletypeCompletionEnabled() and
  297. self.NativeFiletypeCompletionAvailable() )
  298. def NeedsReparse( self ):
  299. return self.CurrentBuffer().NeedsReparse()
  300. def UpdateWithNewDiagnosticsForFile( self, filepath, diagnostics ):
  301. bufnr = vimsupport.GetBufferNumberForFilename( filepath )
  302. if bufnr in self._buffers and vimsupport.BufferIsVisible( bufnr ):
  303. # Note: We only update location lists, etc. for visible buffers, because
  304. # otherwise we defualt to using the curren location list and the results
  305. # are that non-visible buffer errors clobber visible ones.
  306. self._buffers[ bufnr ].UpdateWithNewDiagnostics( diagnostics )
  307. else:
  308. # The project contains errors in file "filepath", but that file is not
  309. # open in any buffer. This happens for Language Server Protocol-based
  310. # completers, as they return diagnostics for the entire "project"
  311. # asynchronously (rather than per-file in the response to the parse
  312. # request).
  313. #
  314. # There are a number of possible approaches for
  315. # this, but for now we simply ignore them. Other options include:
  316. # - Use the QuickFix list to report project errors?
  317. # - Use a special buffer for project errors
  318. # - Put them in the location list of whatever the "current" buffer is
  319. # - Store them in case the buffer is opened later
  320. # - add a :YcmProjectDiags command
  321. # - Add them to errror/warning _counts_ but not any actual location list
  322. # or other
  323. # - etc.
  324. #
  325. # However, none of those options are great, and lead to their own
  326. # complexities. So for now, we just ignore these diagnostics for files not
  327. # open in any buffer.
  328. pass
  329. def OnPeriodicTick( self ):
  330. if not self.IsServerAlive():
  331. # Server has died. We'll reset when the server is started again.
  332. return False
  333. elif not self.IsServerReady():
  334. # Try again in a jiffy
  335. return True
  336. if not self._message_poll_request:
  337. self._message_poll_request = MessagesPoll()
  338. if not self._message_poll_request.Poll( self ):
  339. # Don't poll again until some event which might change the server's mind
  340. # about whether to provide messages for the current buffer (e.g. buffer
  341. # visit, file ready to parse, etc.)
  342. self._message_poll_request = None
  343. return False
  344. # Poll again in a jiffy
  345. return True
  346. def OnFileReadyToParse( self ):
  347. if not self.IsServerAlive():
  348. self.NotifyUserIfServerCrashed()
  349. return
  350. if not self.IsServerReady():
  351. return
  352. extra_data = {}
  353. self._AddTagsFilesIfNeeded( extra_data )
  354. self._AddSyntaxDataIfNeeded( extra_data )
  355. self._AddExtraConfDataIfNeeded( extra_data )
  356. self.CurrentBuffer().SendParseRequest( extra_data )
  357. def OnBufferUnload( self, deleted_buffer_number ):
  358. SendEventNotificationAsync( 'BufferUnload', deleted_buffer_number )
  359. def UpdateMatches( self ):
  360. self.CurrentBuffer().UpdateMatches()
  361. def OnBufferVisit( self ):
  362. extra_data = {}
  363. self._AddUltiSnipsDataIfNeeded( extra_data )
  364. SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )
  365. def CurrentBuffer( self ):
  366. return self._buffers[ vimsupport.GetCurrentBufferNumber() ]
  367. def OnInsertLeave( self ):
  368. SendEventNotificationAsync( 'InsertLeave' )
  369. def OnCursorMoved( self ):
  370. self.CurrentBuffer().OnCursorMoved()
  371. def _CleanLogfile( self ):
  372. logging.shutdown()
  373. if not self._user_options[ 'keep_logfiles' ]:
  374. if self._client_logfile:
  375. utils.RemoveIfExists( self._client_logfile )
  376. def OnVimLeave( self ):
  377. self._ShutdownServer()
  378. self._CleanLogfile()
  379. def OnCurrentIdentifierFinished( self ):
  380. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  381. def OnCompleteDone( self ):
  382. completion_request = self.GetCurrentCompletionRequest()
  383. if completion_request:
  384. completion_request.OnCompleteDone()
  385. def GetErrorCount( self ):
  386. return self.CurrentBuffer().GetErrorCount()
  387. def GetWarningCount( self ):
  388. return self.CurrentBuffer().GetWarningCount()
  389. def DiagnosticUiSupportedForCurrentFiletype( self ):
  390. return any( [ x in DIAGNOSTIC_UI_FILETYPES or
  391. x in DIAGNOSTIC_UI_ASYNC_FILETYPES
  392. for x in vimsupport.CurrentFiletypes() ] )
  393. def ShouldDisplayDiagnostics( self ):
  394. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  395. self.DiagnosticUiSupportedForCurrentFiletype() )
  396. def _PopulateLocationListWithLatestDiagnostics( self ):
  397. return self.CurrentBuffer().PopulateLocationList()
  398. def FileParseRequestReady( self ):
  399. # Return True if server is not ready yet, to stop repeating check timer.
  400. return ( not self.IsServerReady() or
  401. self.CurrentBuffer().FileParseRequestReady() )
  402. def HandleFileParseRequest( self, block = False ):
  403. if not self.IsServerReady():
  404. return
  405. current_buffer = self.CurrentBuffer()
  406. # Order is important here:
  407. # FileParseRequestReady has a low cost, while
  408. # NativeFiletypeCompletionUsable is a blocking server request
  409. if ( not current_buffer.IsResponseHandled() and
  410. current_buffer.FileParseRequestReady( block ) and
  411. self.NativeFiletypeCompletionUsable() ):
  412. if self.ShouldDisplayDiagnostics():
  413. # Forcefuly update the location list, etc. from the parse request when
  414. # doing something like :YcmDiags
  415. current_buffer.UpdateDiagnostics( block is True )
  416. else:
  417. # YCM client has a hard-coded list of filetypes which are known
  418. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  419. #
  420. # For filetypes which don't support diagnostics, we just want to check
  421. # the _latest_file_parse_request for any exception or UnknownExtraConf
  422. # response, to allow the server to raise configuration warnings, etc.
  423. # to the user. We ignore any other supplied data.
  424. current_buffer.GetResponse()
  425. # We set the file parse request as handled because we want to prevent
  426. # repeated issuing of the same warnings/errors/prompts. Setting this
  427. # makes IsRequestHandled return True until the next request is created.
  428. #
  429. # Note: it is the server's responsibility to determine the frequency of
  430. # error/warning/prompts when receiving a FileReadyToParse event, but
  431. # it is our responsibility to ensure that we only apply the
  432. # warning/error/prompt received once (for each event).
  433. current_buffer.MarkResponseHandled()
  434. def DebugInfo( self ):
  435. debug_info = ''
  436. if self._client_logfile:
  437. debug_info += 'Client logfile: {0}\n'.format( self._client_logfile )
  438. extra_data = {}
  439. self._AddExtraConfDataIfNeeded( extra_data )
  440. debug_info += FormatDebugInfoResponse( SendDebugInfoRequest( extra_data ) )
  441. debug_info += 'Server running at: {0}\n'.format(
  442. BaseRequest.server_location )
  443. if self._server_popen:
  444. debug_info += 'Server process ID: {0}\n'.format( self._server_popen.pid )
  445. if self._server_stdout and self._server_stderr:
  446. debug_info += ( 'Server logfiles:\n'
  447. ' {0}\n'
  448. ' {1}'.format( self._server_stdout,
  449. self._server_stderr ) )
  450. return debug_info
  451. def GetLogfiles( self ):
  452. logfiles_list = [ self._client_logfile,
  453. self._server_stdout,
  454. self._server_stderr ]
  455. debug_info = SendDebugInfoRequest()
  456. if debug_info:
  457. completer = debug_info[ 'completer' ]
  458. if completer:
  459. for server in completer[ 'servers' ]:
  460. logfiles_list.extend( server[ 'logfiles' ] )
  461. logfiles = {}
  462. for logfile in logfiles_list:
  463. logfiles[ os.path.basename( logfile ) ] = logfile
  464. return logfiles
  465. def _OpenLogfile( self, logfile ):
  466. # Open log files in a horizontal window with the same behavior as the
  467. # preview window (same height and winfixheight enabled). Automatically
  468. # watch for changes. Set the cursor position at the end of the file.
  469. options = {
  470. 'size': vimsupport.GetIntValue( '&previewheight' ),
  471. 'fix': True,
  472. 'focus': False,
  473. 'watch': True,
  474. 'position': 'end'
  475. }
  476. vimsupport.OpenFilename( logfile, options )
  477. def _CloseLogfile( self, logfile ):
  478. vimsupport.CloseBuffersForFilename( logfile )
  479. def ToggleLogs( self, *filenames ):
  480. logfiles = self.GetLogfiles()
  481. if not filenames:
  482. sorted_logfiles = sorted( list( logfiles ) )
  483. try:
  484. logfile_index = vimsupport.SelectFromList(
  485. 'Which logfile do you wish to open (or close if already open)?',
  486. sorted_logfiles )
  487. except RuntimeError as e:
  488. vimsupport.PostVimMessage( str( e ) )
  489. return
  490. logfile = logfiles[ sorted_logfiles[ logfile_index ] ]
  491. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  492. self._OpenLogfile( logfile )
  493. else:
  494. self._CloseLogfile( logfile )
  495. return
  496. for filename in set( filenames ):
  497. if filename not in logfiles:
  498. continue
  499. logfile = logfiles[ filename ]
  500. if not vimsupport.BufferIsVisibleForFilename( logfile ):
  501. self._OpenLogfile( logfile )
  502. continue
  503. self._CloseLogfile( logfile )
  504. def CurrentFiletypeCompletionEnabled( self ):
  505. filetypes = vimsupport.CurrentFiletypes()
  506. filetype_to_disable = self._user_options[
  507. 'filetype_specific_completion_to_disable' ]
  508. if '*' in filetype_to_disable:
  509. return False
  510. else:
  511. return not any( [ x in filetype_to_disable for x in filetypes ] )
  512. def ShowDetailedDiagnostic( self ):
  513. detailed_diagnostic = BaseRequest.PostDataToHandler(
  514. BuildRequestData(), 'detailed_diagnostic' )
  515. if 'message' in detailed_diagnostic:
  516. vimsupport.PostVimMessage( detailed_diagnostic[ 'message' ],
  517. warning = False )
  518. def ForceCompileAndDiagnostics( self ):
  519. if not self.NativeFiletypeCompletionUsable():
  520. vimsupport.PostVimMessage(
  521. 'Native filetype completion not supported for current file, '
  522. 'cannot force recompilation.', warning = False )
  523. return False
  524. vimsupport.PostVimMessage(
  525. 'Forcing compilation, this will block Vim until done.',
  526. warning = False )
  527. self.OnFileReadyToParse()
  528. self.HandleFileParseRequest( block = True )
  529. vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
  530. return True
  531. def ShowDiagnostics( self ):
  532. if not self.ForceCompileAndDiagnostics():
  533. return
  534. if not self._PopulateLocationListWithLatestDiagnostics():
  535. vimsupport.PostVimMessage( 'No warnings or errors detected.',
  536. warning = False )
  537. return
  538. if self._user_options[ 'open_loclist_on_ycm_diags' ]:
  539. vimsupport.OpenLocationList( focus = True )
  540. def _AddSyntaxDataIfNeeded( self, extra_data ):
  541. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  542. return
  543. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  544. if filetype in self._filetypes_with_keywords_loaded:
  545. return
  546. if self.IsServerReady():
  547. self._filetypes_with_keywords_loaded.add( filetype )
  548. extra_data[ 'syntax_keywords' ] = list(
  549. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  550. def _AddTagsFilesIfNeeded( self, extra_data ):
  551. def GetTagFiles():
  552. tag_files = vim.eval( 'tagfiles()' )
  553. return [ os.path.join( utils.GetCurrentDirectory(), tag_file )
  554. for tag_file in tag_files ]
  555. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  556. return
  557. extra_data[ 'tag_files' ] = GetTagFiles()
  558. def _AddExtraConfDataIfNeeded( self, extra_data ):
  559. def BuildExtraConfData( extra_conf_vim_data ):
  560. extra_conf_data = {}
  561. for expr in extra_conf_vim_data:
  562. try:
  563. extra_conf_data[ expr ] = vimsupport.VimExpressionToPythonType( expr )
  564. except vim.error:
  565. message = (
  566. "Error evaluating '{expr}' in the 'g:ycm_extra_conf_vim_data' "
  567. "option.".format( expr = expr ) )
  568. vimsupport.PostVimMessage( message, truncate = True )
  569. self._logger.exception( message )
  570. return extra_conf_data
  571. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  572. if extra_conf_vim_data:
  573. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  574. extra_conf_vim_data )
  575. def _AddUltiSnipsDataIfNeeded( self, extra_data ):
  576. # See :h UltiSnips#SnippetsInCurrentScope.
  577. try:
  578. vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
  579. except vim.error:
  580. return
  581. snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
  582. extra_data[ 'ultisnips_snippets' ] = [
  583. { 'trigger': trigger,
  584. 'description': snippet[ 'description' ] }
  585. for trigger, snippet in iteritems( snippets )
  586. ]