youcompleteme.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. # Copyright (C) 2011, 2012 Google Inc.
  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. from future import standard_library
  22. standard_library.install_aliases()
  23. from builtins import * # noqa
  24. from future.utils import iteritems
  25. import os
  26. import vim
  27. import json
  28. import re
  29. import signal
  30. import base64
  31. from subprocess import PIPE
  32. from tempfile import NamedTemporaryFile
  33. from ycm import paths, vimsupport
  34. from ycmd import utils
  35. from ycmd import server_utils
  36. from ycmd.request_wrap import RequestWrap
  37. from ycmd.responses import ServerError
  38. from ycm.diagnostic_interface import DiagnosticInterface
  39. from ycm.omni_completer import OmniCompleter
  40. from ycm import syntax_parse
  41. from ycm.client.ycmd_keepalive import YcmdKeepalive
  42. from ycm.client.base_request import BaseRequest, BuildRequestData
  43. 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. ConvertCompletionDataToVimData )
  47. from ycm.client.omni_completion_request import OmniCompletionRequest
  48. from ycm.client.event_notification import ( SendEventNotificationAsync,
  49. EventNotification )
  50. try:
  51. from UltiSnips import UltiSnips_Manager
  52. USE_ULTISNIPS_DATA = True
  53. except ImportError:
  54. USE_ULTISNIPS_DATA = False
  55. def PatchNoProxy():
  56. current_value = os.environ.get('no_proxy', '')
  57. additions = '127.0.0.1,localhost'
  58. os.environ['no_proxy'] = ( additions if not current_value
  59. else current_value + ',' + additions )
  60. # We need this so that Requests doesn't end up using the local HTTP proxy when
  61. # talking to ycmd. Users should actually be setting this themselves when
  62. # configuring a proxy server on their machine, but most don't know they need to
  63. # or how to do it, so we do it for them.
  64. # Relevant issues:
  65. # https://github.com/Valloric/YouCompleteMe/issues/641
  66. # https://github.com/kennethreitz/requests/issues/879
  67. PatchNoProxy()
  68. # Force the Python interpreter embedded in Vim (in which we are running) to
  69. # ignore the SIGINT signal. This helps reduce the fallout of a user pressing
  70. # Ctrl-C in Vim.
  71. signal.signal( signal.SIGINT, signal.SIG_IGN )
  72. HMAC_SECRET_LENGTH = 16
  73. SERVER_SHUTDOWN_MESSAGE = (
  74. "The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." )
  75. STDERR_FILE_MESSAGE = (
  76. "Run ':YcmToggleLogs stderr' to check the logs." )
  77. STDERR_FILE_DELETED_MESSAGE = (
  78. "Logfile was deleted; set 'g:ycm_server_keep_logfiles' to see errors "
  79. "in the future." )
  80. CORE_UNEXPECTED_MESSAGE = (
  81. 'Unexpected error while loading the YCM core library.' )
  82. CORE_MISSING_MESSAGE = (
  83. 'YCM core library not detected; you need to compile YCM before using it. '
  84. 'Follow the instructions in the documentation.' )
  85. CORE_PYTHON2_MESSAGE = (
  86. "YCM core library compiled for Python 2 but loaded in Python 3. "
  87. "Set the 'g:ycm_server_python_interpreter' option to a Python 2 "
  88. "interpreter path." )
  89. CORE_PYTHON3_MESSAGE = (
  90. "YCM core library compiled for Python 3 but loaded in Python 2. "
  91. "Set the 'g:ycm_server_python_interpreter' option to a Python 3 "
  92. "interpreter path." )
  93. CORE_OUTDATED_MESSAGE = (
  94. 'YCM core library too old; PLEASE RECOMPILE by running the install.py '
  95. 'script. See the documentation for more details.' )
  96. SERVER_IDLE_SUICIDE_SECONDS = 10800 # 3 hours
  97. DIAGNOSTIC_UI_FILETYPES = set( [ 'cpp', 'cs', 'c', 'objc', 'objcpp' ] )
  98. class YouCompleteMe( object ):
  99. def __init__( self, user_options ):
  100. self._user_options = user_options
  101. self._user_notified_about_crash = False
  102. self._diag_interface = DiagnosticInterface( user_options )
  103. self._omnicomp = OmniCompleter( user_options )
  104. self._latest_file_parse_request = None
  105. self._latest_completion_request = None
  106. self._latest_diagnostics = []
  107. self._server_stdout = None
  108. self._server_stderr = None
  109. self._server_popen = None
  110. self._filetypes_with_keywords_loaded = set()
  111. self._ycmd_keepalive = YcmdKeepalive()
  112. self._SetupServer()
  113. self._ycmd_keepalive.Start()
  114. self._complete_done_hooks = {
  115. 'cs': lambda self: self._OnCompleteDone_Csharp()
  116. }
  117. def _SetupServer( self ):
  118. self._available_completers = {}
  119. server_port = utils.GetUnusedLocalhostPort()
  120. # The temp options file is deleted by ycmd during startup
  121. with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
  122. hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
  123. options_dict = dict( self._user_options )
  124. options_dict[ 'hmac_secret' ] = utils.ToUnicode(
  125. base64.b64encode( hmac_secret ) )
  126. json.dump( options_dict, options_file )
  127. options_file.flush()
  128. args = [ paths.PathToPythonInterpreter(),
  129. paths.PathToServerScript(),
  130. '--port={0}'.format( server_port ),
  131. '--options_file={0}'.format( options_file.name ),
  132. '--log={0}'.format( self._user_options[ 'server_log_level' ] ),
  133. '--idle_suicide_seconds={0}'.format(
  134. SERVER_IDLE_SUICIDE_SECONDS )]
  135. filename_format = os.path.join( utils.PathToCreatedTempDir(),
  136. 'server_{port}_{std}.log' )
  137. self._server_stdout = filename_format.format( port = server_port,
  138. std = 'stdout' )
  139. self._server_stderr = filename_format.format( port = server_port,
  140. std = 'stderr' )
  141. args.append( '--stdout={0}'.format( self._server_stdout ) )
  142. args.append( '--stderr={0}'.format( self._server_stderr ) )
  143. if self._user_options[ 'server_keep_logfiles' ]:
  144. args.append( '--keep_logfiles' )
  145. self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
  146. stdout = PIPE, stderr = PIPE )
  147. BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
  148. BaseRequest.hmac_secret = hmac_secret
  149. self._NotifyUserIfServerCrashed()
  150. def IsServerAlive( self ):
  151. returncode = self._server_popen.poll()
  152. # When the process hasn't finished yet, poll() returns None.
  153. return returncode is None
  154. def _NotifyUserIfServerCrashed( self ):
  155. if self._user_notified_about_crash or self.IsServerAlive():
  156. return
  157. self._user_notified_about_crash = True
  158. try:
  159. vimsupport.CheckFilename( self._server_stderr )
  160. stderr_message = STDERR_FILE_MESSAGE
  161. except RuntimeError:
  162. stderr_message = STDERR_FILE_DELETED_MESSAGE
  163. message = SERVER_SHUTDOWN_MESSAGE
  164. return_code = self._server_popen.poll()
  165. if return_code == server_utils.CORE_UNEXPECTED_STATUS:
  166. message += ' ' + CORE_UNEXPECTED_MESSAGE + ' ' + stderr_message
  167. elif return_code == server_utils.CORE_MISSING_STATUS:
  168. message += ' ' + CORE_MISSING_MESSAGE
  169. elif return_code == server_utils.CORE_PYTHON2_STATUS:
  170. message += ' ' + CORE_PYTHON2_MESSAGE
  171. elif return_code == server_utils.CORE_PYTHON3_STATUS:
  172. message += ' ' + CORE_PYTHON3_MESSAGE
  173. elif return_code == server_utils.CORE_OUTDATED_STATUS:
  174. message += ' ' + CORE_OUTDATED_MESSAGE
  175. else:
  176. message += ' ' + stderr_message
  177. vimsupport.PostVimMessage( message )
  178. def ServerPid( self ):
  179. if not self._server_popen:
  180. return -1
  181. return self._server_popen.pid
  182. def _ServerCleanup( self ):
  183. if self.IsServerAlive():
  184. self._server_popen.terminate()
  185. def RestartServer( self ):
  186. self._CloseLogs()
  187. vimsupport.PostVimMessage( 'Restarting ycmd server...' )
  188. self._user_notified_about_crash = False
  189. self._ServerCleanup()
  190. self._SetupServer()
  191. def CreateCompletionRequest( self, force_semantic = False ):
  192. request_data = BuildRequestData()
  193. if ( not self.NativeFiletypeCompletionAvailable() and
  194. self.CurrentFiletypeCompletionEnabled() ):
  195. wrapped_request_data = RequestWrap( request_data )
  196. if self._omnicomp.ShouldUseNow( wrapped_request_data ):
  197. self._latest_completion_request = OmniCompletionRequest(
  198. self._omnicomp, wrapped_request_data )
  199. return self._latest_completion_request
  200. request_data[ 'working_dir' ] = os.getcwd()
  201. self._AddExtraConfDataIfNeeded( request_data )
  202. if force_semantic:
  203. request_data[ 'force_semantic' ] = True
  204. self._latest_completion_request = CompletionRequest( request_data )
  205. return self._latest_completion_request
  206. def SendCommandRequest( self, arguments, completer ):
  207. if self.IsServerAlive():
  208. return SendCommandRequest( arguments, completer )
  209. def GetDefinedSubcommands( self ):
  210. if self.IsServerAlive():
  211. try:
  212. return BaseRequest.PostDataToHandler( BuildRequestData(),
  213. 'defined_subcommands' )
  214. except ServerError:
  215. return []
  216. else:
  217. return []
  218. def GetCurrentCompletionRequest( self ):
  219. return self._latest_completion_request
  220. def GetOmniCompleter( self ):
  221. return self._omnicomp
  222. def FiletypeCompleterExistsForFiletype( self, filetype ):
  223. try:
  224. return self._available_completers[ filetype ]
  225. except KeyError:
  226. pass
  227. if not self.IsServerAlive():
  228. return False
  229. exists_completer = SendCompleterAvailableRequest( filetype )
  230. if exists_completer is None:
  231. return False
  232. self._available_completers[ filetype ] = exists_completer
  233. return exists_completer
  234. def NativeFiletypeCompletionAvailable( self ):
  235. return any( [ self.FiletypeCompleterExistsForFiletype( x ) for x in
  236. vimsupport.CurrentFiletypes() ] )
  237. def NativeFiletypeCompletionUsable( self ):
  238. return ( self.CurrentFiletypeCompletionEnabled() and
  239. self.NativeFiletypeCompletionAvailable() )
  240. def OnFileReadyToParse( self ):
  241. if not self.IsServerAlive():
  242. self._NotifyUserIfServerCrashed()
  243. return
  244. self._omnicomp.OnFileReadyToParse( None )
  245. extra_data = {}
  246. self._AddTagsFilesIfNeeded( extra_data )
  247. self._AddSyntaxDataIfNeeded( extra_data )
  248. self._AddExtraConfDataIfNeeded( extra_data )
  249. self._latest_file_parse_request = EventNotification( 'FileReadyToParse',
  250. extra_data )
  251. self._latest_file_parse_request.Start()
  252. def OnBufferUnload( self, deleted_buffer_file ):
  253. if not self.IsServerAlive():
  254. return
  255. SendEventNotificationAsync( 'BufferUnload',
  256. { 'unloaded_buffer': deleted_buffer_file } )
  257. def OnBufferVisit( self ):
  258. if not self.IsServerAlive():
  259. return
  260. extra_data = {}
  261. _AddUltiSnipsDataIfNeeded( extra_data )
  262. SendEventNotificationAsync( 'BufferVisit', extra_data )
  263. def OnInsertLeave( self ):
  264. if not self.IsServerAlive():
  265. return
  266. SendEventNotificationAsync( 'InsertLeave' )
  267. def OnCursorMoved( self ):
  268. self._diag_interface.OnCursorMoved()
  269. def OnVimLeave( self ):
  270. self._ServerCleanup()
  271. def OnCurrentIdentifierFinished( self ):
  272. if not self.IsServerAlive():
  273. return
  274. SendEventNotificationAsync( 'CurrentIdentifierFinished' )
  275. def OnCompleteDone( self ):
  276. complete_done_actions = self.GetCompleteDoneHooks()
  277. for action in complete_done_actions:
  278. action(self)
  279. def GetCompleteDoneHooks( self ):
  280. filetypes = vimsupport.CurrentFiletypes()
  281. for key, value in iteritems( self._complete_done_hooks ):
  282. if key in filetypes:
  283. yield value
  284. def GetCompletionsUserMayHaveCompleted( self ):
  285. latest_completion_request = self.GetCurrentCompletionRequest()
  286. if not latest_completion_request or not latest_completion_request.Done():
  287. return []
  288. completions = latest_completion_request.RawResponse()
  289. result = self._FilterToMatchingCompletions( completions, True )
  290. result = list( result )
  291. if result:
  292. return result
  293. if self._HasCompletionsThatCouldBeCompletedWithMoreText( completions ):
  294. # Since the way that YCM works leads to CompleteDone called on every
  295. # character, return blank if the completion might not be done. This won't
  296. # match if the completion is ended with typing a non-keyword character.
  297. return []
  298. result = self._FilterToMatchingCompletions( completions, False )
  299. return list( result )
  300. def _FilterToMatchingCompletions( self, completions, full_match_only ):
  301. self._PatchBasedOnVimVersion()
  302. return self._FilterToMatchingCompletions( completions, full_match_only)
  303. def _HasCompletionsThatCouldBeCompletedWithMoreText( self, completions ):
  304. self._PatchBasedOnVimVersion()
  305. return self._HasCompletionsThatCouldBeCompletedWithMoreText( completions )
  306. def _PatchBasedOnVimVersion( self ):
  307. if vimsupport.VimVersionAtLeast( "7.4.774" ):
  308. self._HasCompletionsThatCouldBeCompletedWithMoreText = \
  309. self._HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim
  310. self._FilterToMatchingCompletions = \
  311. self._FilterToMatchingCompletions_NewerVim
  312. else:
  313. self._FilterToMatchingCompletions = \
  314. self._FilterToMatchingCompletions_OlderVim
  315. self._HasCompletionsThatCouldBeCompletedWithMoreText = \
  316. self._HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim
  317. def _FilterToMatchingCompletions_NewerVim( self, completions,
  318. full_match_only ):
  319. """ Filter to completions matching the item Vim said was completed """
  320. completed = vimsupport.GetVariableValue( 'v:completed_item' )
  321. for completion in completions:
  322. item = ConvertCompletionDataToVimData( completion )
  323. match_keys = ( [ "word", "abbr", "menu", "info" ] if full_match_only
  324. else [ 'word' ] )
  325. def matcher( key ):
  326. return completed.get( key, "" ) == item.get( key, "" )
  327. if all( [ matcher( i ) for i in match_keys ] ):
  328. yield completion
  329. def _FilterToMatchingCompletions_OlderVim( self, completions,
  330. full_match_only ):
  331. """ Filter to completions matching the buffer text """
  332. if full_match_only:
  333. return # Only supported in 7.4.774+
  334. # No support for multiple line completions
  335. text = vimsupport.TextBeforeCursor()
  336. for completion in completions:
  337. word = completion[ "insertion_text" ]
  338. # Trim complete-ending character if needed
  339. text = re.sub( r"[^a-zA-Z0-9_]$", "", text )
  340. buffer_text = text[ -1 * len( word ) : ]
  341. if buffer_text == word:
  342. yield completion
  343. def _HasCompletionsThatCouldBeCompletedWithMoreText_NewerVim( self,
  344. completions ):
  345. completed_item = vimsupport.GetVariableValue( 'v:completed_item' )
  346. if not completed_item:
  347. return False
  348. completed_word = completed_item[ 'word' ]
  349. if not completed_word:
  350. return False
  351. # Sometime CompleteDone is called after the next character is inserted
  352. # If so, use inserted character to filter possible completions further
  353. text = vimsupport.TextBeforeCursor()
  354. reject_exact_match = True
  355. if text and text[ -1 ] != completed_word[ -1 ]:
  356. reject_exact_match = False
  357. completed_word += text[ -1 ]
  358. for completion in completions:
  359. word = ConvertCompletionDataToVimData( completion )[ 'word' ]
  360. if reject_exact_match and word == completed_word:
  361. continue
  362. if word.startswith( completed_word ):
  363. return True
  364. return False
  365. def _HasCompletionsThatCouldBeCompletedWithMoreText_OlderVim( self,
  366. completions ):
  367. # No support for multiple line completions
  368. text = vimsupport.TextBeforeCursor()
  369. for completion in completions:
  370. word = ConvertCompletionDataToVimData( completion )[ 'word' ]
  371. for i in range( 1, len( word ) - 1 ): # Excluding full word
  372. if text[ -1 * i : ] == word[ : i ]:
  373. return True
  374. return False
  375. def _OnCompleteDone_Csharp( self ):
  376. completions = self.GetCompletionsUserMayHaveCompleted()
  377. namespaces = [ self._GetRequiredNamespaceImport( c )
  378. for c in completions ]
  379. namespaces = [ n for n in namespaces if n ]
  380. if not namespaces:
  381. return
  382. if len( namespaces ) > 1:
  383. choices = [ "{0} {1}".format( i + 1, n )
  384. for i, n in enumerate( namespaces ) ]
  385. choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
  386. if choice < 0:
  387. return
  388. namespace = namespaces[ choice ]
  389. else:
  390. namespace = namespaces[ 0 ]
  391. vimsupport.InsertNamespace( namespace )
  392. def _GetRequiredNamespaceImport( self, completion ):
  393. if ( "extra_data" not in completion
  394. or "required_namespace_import" not in completion[ "extra_data" ] ):
  395. return None
  396. return completion[ "extra_data" ][ "required_namespace_import" ]
  397. def GetErrorCount( self ):
  398. return self._diag_interface.GetErrorCount()
  399. def GetWarningCount( self ):
  400. return self._diag_interface.GetWarningCount()
  401. def DiagnosticUiSupportedForCurrentFiletype( self ):
  402. return any( [ x in DIAGNOSTIC_UI_FILETYPES
  403. for x in vimsupport.CurrentFiletypes() ] )
  404. def ShouldDisplayDiagnostics( self ):
  405. return bool( self._user_options[ 'show_diagnostics_ui' ] and
  406. self.DiagnosticUiSupportedForCurrentFiletype() )
  407. def PopulateLocationListWithLatestDiagnostics( self ):
  408. # Do nothing if loc list is already populated by diag_interface
  409. if not self._user_options[ 'always_populate_location_list' ]:
  410. self._diag_interface.PopulateLocationList( self._latest_diagnostics )
  411. return bool( self._latest_diagnostics )
  412. def UpdateDiagnosticInterface( self ):
  413. self._diag_interface.UpdateWithNewDiagnostics( self._latest_diagnostics )
  414. def FileParseRequestReady( self, block = False ):
  415. return bool( self._latest_file_parse_request and
  416. ( block or self._latest_file_parse_request.Done() ) )
  417. def HandleFileParseRequest( self, block = False ):
  418. # Order is important here:
  419. # FileParseRequestReady has a low cost, while
  420. # NativeFiletypeCompletionUsable is a blocking server request
  421. if ( self.FileParseRequestReady( block ) and
  422. self.NativeFiletypeCompletionUsable() ):
  423. if self.ShouldDisplayDiagnostics():
  424. self._latest_diagnostics = self._latest_file_parse_request.Response()
  425. self.UpdateDiagnosticInterface()
  426. else:
  427. # YCM client has a hard-coded list of filetypes which are known
  428. # to support diagnostics, self.DiagnosticUiSupportedForCurrentFiletype()
  429. #
  430. # For filetypes which don't support diagnostics, we just want to check
  431. # the _latest_file_parse_request for any exception or UnknownExtraConf
  432. # response, to allow the server to raise configuration warnings, etc.
  433. # to the user. We ignore any other supplied data.
  434. self._latest_file_parse_request.Response()
  435. # We set the file parse request to None because we want to prevent
  436. # repeated issuing of the same warnings/errors/prompts. Setting this to
  437. # None makes FileParseRequestReady return False until the next
  438. # request is created.
  439. #
  440. # Note: it is the server's responsibility to determine the frequency of
  441. # error/warning/prompts when receiving a FileReadyToParse event, but
  442. # it our responsibility to ensure that we only apply the
  443. # warning/error/prompt received once (for each event).
  444. self._latest_file_parse_request = None
  445. def ShowDetailedDiagnostic( self ):
  446. if not self.IsServerAlive():
  447. return
  448. try:
  449. debug_info = BaseRequest.PostDataToHandler( BuildRequestData(),
  450. 'detailed_diagnostic' )
  451. if 'message' in debug_info:
  452. vimsupport.EchoText( debug_info[ 'message' ] )
  453. except ServerError as e:
  454. vimsupport.PostVimMessage( str( e ) )
  455. def DebugInfo( self ):
  456. if self.IsServerAlive():
  457. debug_info = BaseRequest.PostDataToHandler( BuildRequestData(),
  458. 'debug_info' )
  459. else:
  460. debug_info = 'Server crashed, no debug info from server'
  461. debug_info += '\nServer running at: {0}'.format(
  462. BaseRequest.server_location )
  463. debug_info += '\nServer process ID: {0}'.format( self._server_popen.pid )
  464. if self._server_stderr or self._server_stdout:
  465. debug_info += '\nServer logfiles:\n {0}\n {1}'.format(
  466. self._server_stdout,
  467. self._server_stderr )
  468. return debug_info
  469. def _OpenLogs( self, stdout = True, stderr = True ):
  470. # Open log files in a horizontal window with the same behavior as the
  471. # preview window (same height and winfixheight enabled). Automatically
  472. # watch for changes. Set the cursor position at the end of the file.
  473. options = {
  474. 'size': vimsupport.GetIntValue( '&previewheight' ),
  475. 'fix': True,
  476. 'watch': True,
  477. 'position': 'end'
  478. }
  479. if stdout:
  480. vimsupport.OpenFilename( self._server_stdout, options )
  481. if stderr:
  482. vimsupport.OpenFilename( self._server_stderr, options )
  483. def _CloseLogs( self, stdout = True, stderr = True ):
  484. if stdout:
  485. vimsupport.CloseBuffersForFilename( self._server_stdout )
  486. if stderr:
  487. vimsupport.CloseBuffersForFilename( self._server_stderr )
  488. def ToggleLogs( self, stdout = True, stderr = True ):
  489. if ( stdout and
  490. vimsupport.BufferIsVisibleForFilename( self._server_stdout ) or
  491. stderr and
  492. vimsupport.BufferIsVisibleForFilename( self._server_stderr ) ):
  493. return self._CloseLogs( stdout = stdout, stderr = stderr )
  494. # Close hidden logfile buffers if any to keep a clean state
  495. self._CloseLogs( stdout = stdout, stderr = stderr )
  496. try:
  497. self._OpenLogs( stdout = stdout, stderr = stderr )
  498. except RuntimeError as error:
  499. vimsupport.PostVimMessage( 'YouCompleteMe encountered an error when '
  500. 'opening logs: {0}.'.format( error ) )
  501. def CurrentFiletypeCompletionEnabled( self ):
  502. filetypes = vimsupport.CurrentFiletypes()
  503. filetype_to_disable = self._user_options[
  504. 'filetype_specific_completion_to_disable' ]
  505. if '*' in filetype_to_disable:
  506. return False
  507. else:
  508. return not any([ x in filetype_to_disable for x in filetypes ])
  509. def _AddSyntaxDataIfNeeded( self, extra_data ):
  510. if not self._user_options[ 'seed_identifiers_with_syntax' ]:
  511. return
  512. filetype = vimsupport.CurrentFiletypes()[ 0 ]
  513. if filetype in self._filetypes_with_keywords_loaded:
  514. return
  515. self._filetypes_with_keywords_loaded.add( filetype )
  516. extra_data[ 'syntax_keywords' ] = list(
  517. syntax_parse.SyntaxKeywordsForCurrentBuffer() )
  518. def _AddTagsFilesIfNeeded( self, extra_data ):
  519. def GetTagFiles():
  520. tag_files = vim.eval( 'tagfiles()' )
  521. # getcwd() throws an exception when the CWD has been deleted.
  522. try:
  523. current_working_directory = os.getcwd()
  524. except OSError:
  525. return []
  526. return [ os.path.join( current_working_directory, x ) for x in tag_files ]
  527. if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
  528. return
  529. extra_data[ 'tag_files' ] = GetTagFiles()
  530. def _AddExtraConfDataIfNeeded( self, extra_data ):
  531. def BuildExtraConfData( extra_conf_vim_data ):
  532. return dict( ( expr, vimsupport.VimExpressionToPythonType( expr ) )
  533. for expr in extra_conf_vim_data )
  534. extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
  535. if extra_conf_vim_data:
  536. extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
  537. extra_conf_vim_data )
  538. def _AddUltiSnipsDataIfNeeded( extra_data ):
  539. if not USE_ULTISNIPS_DATA:
  540. return
  541. try:
  542. # Since UltiSnips may run in a different python interpreter (python 3) than
  543. # YCM, UltiSnips_Manager singleton is not necessary the same as the one
  544. # used by YCM. In particular, it means that we cannot rely on UltiSnips to
  545. # set the current filetypes to the singleton. We need to do it ourself.
  546. UltiSnips_Manager.reset_buffer_filetypes()
  547. UltiSnips_Manager.add_buffer_filetypes(
  548. vimsupport.GetVariableValue( '&filetype' ) )
  549. rawsnips = UltiSnips_Manager._snips( '', True )
  550. except:
  551. return
  552. # UltiSnips_Manager._snips() returns a class instance where:
  553. # class.trigger - name of snippet trigger word ( e.g. defn or testcase )
  554. # class.description - description of the snippet
  555. extra_data[ 'ultisnips_snippets' ] = [
  556. { 'trigger': x.trigger, 'description': x.description } for x in rawsnips
  557. ]