File: run_tests.py

#!/usr/bin/env python3

import argparse
import glob
import os
import os.path as p
import subprocess
import sys

DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )

# We don't include python-future (not to be confused with pythonfutures) because
# it needs to be inserted in sys.path AFTER the standard library imports but we
# can't do that with PYTHONPATH because the std lib paths are always appended to
# PYTHONPATH. We do it correctly inside Vim because we have access to the right
# sys.path. So for dev, we rely on python-future being installed correctly with
#
#   pip install -r python/test_requirements.txt
#
# Pip knows how to install this correctly so that it doesn't matter where in
# sys.path the path is.
python_path = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ),
                p.join( DIR_OF_THIRD_PARTY, 'ycmd' ) ]
if os.environ.get( 'PYTHONPATH' ):
  python_path.append( os.environ[ 'PYTHONPATH' ] )
os.environ[ 'PYTHONPATH' ] = os.pathsep.join( python_path )


def RunFlake8():
  print( 'Running flake8' )
  args = [ sys.executable,
           '-m',
           'flake8',
           p.join( DIR_OF_THIS_SCRIPT, 'python' ) ]
  root_dir_scripts = glob.glob( p.join( DIR_OF_THIS_SCRIPT, '*.py' ) )
  args.extend( root_dir_scripts )
  subprocess.check_call( args )


def ParseArguments():
  parser = argparse.ArgumentParser()
  parser.add_argument( '--skip-build', action = 'store_true',
                       help = 'Do not build ycmd before testing' )
  parser.add_argument( '--coverage', action = 'store_true',
                       help = 'Enable coverage report' )
  parser.add_argument( '--no-flake8', action = 'store_true',
                       help = 'Do not run flake8' )
  parser.add_argument( '--dump-path', action = 'store_true',
                       help = 'Dump the PYTHONPATH required to run tests '
                              'manually, then exit.' )

  parsed_args, unittest_args = parser.parse_known_args()

  if 'COVERAGE' in os.environ:
    parsed_args.coverage = ( os.environ[ 'COVERAGE' ] == 'true' )

  return parsed_args, unittest_args


def BuildYcmdLibs( args ):
  if not args.skip_build:
    subprocess.check_call( [
      sys.executable,
      p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ),
      '--quiet'
    ] )


def UnittestTests( parsed_args, extra_unittest_args ):
  # if any extra arg is a specific file, or the '--' token, then assume the
  # arguments are unittest-aware test selection:
  #  - don't use discover
  #  - don't set the pattern to search for
  unittest_args = [ '-cb' ]
  prefer_regular = any( arg == '--' or p.isfile( arg )
                        for arg in extra_unittest_args )
  if not prefer_regular:
    unittest_args += [ '-p', '*_test.py' ]

  if extra_unittest_args:
    unittest_args.extend( extra_unittest_args )
  if not ( prefer_regular and extra_unittest_args ):
    unittest_args.append( '-s' )
    test_directory = p.join( DIR_OF_THIS_SCRIPT, 'python', 'ycm', 'tests' )
    unittest_args.append( test_directory )

  if parsed_args.coverage:
    executable = [ sys.executable,
                   '-m',
                   'coverage',
                   'run' ]
  else:
    executable = [ sys.executable, '-We' ]

  unittest = [ '-m', 'unittest' ]
  if not prefer_regular:
    unittest.append( 'discover' )
  subprocess.check_call( executable + unittest + unittest_args )


def Main():
  ( parsed_args, unittest_args ) = ParseArguments()
  if parsed_args.dump_path:
    print( os.environ[ 'PYTHONPATH' ] )
    sys.exit()

  if not parsed_args.no_flake8:
    RunFlake8()

  BuildYcmdLibs( parsed_args )
  UnittestTests( parsed_args, unittest_args )


if __name__ == "__main__":
  Main()



File: install.py

#!/usr/bin/env python3

from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import

import os
import subprocess
import sys
import os.path as p
import glob

version = sys.version_info[ 0 : 3 ]
if version < ( 3, 6, 0 ):
  sys.exit( 'YouCompleteMe requires Python >= 3.6.0; '
            'your version of Python is ' + sys.version )

DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_OLD_LIBS = p.join( DIR_OF_THIS_SCRIPT, 'python' )


def CheckCall( args, **kwargs ):
  try:
    subprocess.check_call( args, **kwargs )
  except subprocess.CalledProcessError as error:
    sys.exit( error.returncode )


def Main():
  build_file = p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' )

  if not p.isfile( build_file ):
    sys.exit(
      'File {0} does not exist; you probably forgot to run:\n'
      '\tgit submodule update --init --recursive\n'.format( build_file ) )

  CheckCall( [ sys.executable, build_file ] + sys.argv[ 1: ] )

  # Remove old YCM libs if present so that YCM can start.
  old_libs = (
    glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_core.*' ) ) +
    glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_client_support.*' ) ) +
    glob.glob( p.join( DIR_OF_OLD_LIBS, '*clang*.*' ) ) )
  for lib in old_libs:
    os.remove( lib )


if __name__ == "__main__":
  Main()



File: .ycm_extra_conf.py

# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>

import os.path as p
import subprocess

DIR_OF_THIS_SCRIPT = p.abspath( p.dirname( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )


def GetStandardLibraryIndexInSysPath( sys_path ):
  for index, path in enumerate( sys_path ):
    if p.isfile( p.join( path, 'os.py' ) ):
      return index
  raise RuntimeError( 'Could not find standard library path in Python path.' )


def PythonSysPath( **kwargs ):
  sys_path = kwargs[ 'sys_path' ]

  dependencies = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ),
                   p.join( DIR_OF_THIRD_PARTY, 'requests-futures' ),
                   p.join( DIR_OF_THIRD_PARTY, 'ycmd' ),
                   p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'idna' ),
                   p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'chardet' ),
                   p.join( DIR_OF_THIRD_PARTY,
                           'requests_deps',
                           'urllib3',
                           'src' ),
                   p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'certifi' ),
                   p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'requests' ) ]

  # The concurrent.futures module is part of the standard library on Python 3.
  interpreter_path = kwargs[ 'interpreter_path' ]
  major_version = int( subprocess.check_output( [
    interpreter_path, '-c', 'import sys; print( sys.version_info[ 0 ] )' ]
  ).rstrip().decode( 'utf8' ) )
  if major_version == 2:
    dependencies.append( p.join( DIR_OF_THIRD_PARTY, 'pythonfutures' ) )

  sys_path[ 0:0 ] = dependencies
  sys_path.insert( GetStandardLibraryIndexInSysPath( sys_path ) + 1,
                   p.join( DIR_OF_THIRD_PARTY, 'python-future', 'src' ) )

  return sys_path



File: python/ycm/signature_help.py

# Copyright (C) 2011-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import vim
import json
from ycm import vimsupport
from ycmd import utils
from ycm.vimsupport import memoize, GetIntValue


class SignatureHelpState:
  ACTIVE = 'ACTIVE'
  INACTIVE = 'INACTIVE'
  ACTIVE_SUPPRESSED = 'ACTIVE_SUPPRESSED'

  def __init__( self,
                popup_win_id = None,
                state = INACTIVE ):
    self.popup_win_id = popup_win_id
    self.state = state
    self.anchor = None


  def ToggleVisibility( self ):
    if self.state == 'ACTIVE':
      self.state = 'ACTIVE_SUPPRESSED'
      vim.eval( f'popup_hide( { self.popup_win_id } )' )
    elif self.state == 'ACTIVE_SUPPRESSED':
      self.state = 'ACTIVE'
      vim.eval( f'popup_show( { self.popup_win_id } )' )


  def IsActive( self ):
    if self.state in ( 'ACTIVE', 'ACTIVE_SUPPRESSED' ):
      return 'ACTIVE'
    return 'INACTIVE'


def _MakeSignatureHelpBuffer( signature_info ):
  active_parameter = int( signature_info.get( 'activeParameter', 0 ) )

  lines = []
  signatures = ( signature_info.get( 'signatures' ) or [] )

  for sig_index, signature in enumerate( signatures ):
    props = []

    sig_label = signature[ 'label' ]
    parameters = ( signature.get( 'parameters' ) or [] )
    for param_index, parameter in enumerate( parameters ):
      param_label = parameter[ 'label' ]
      begin = int( param_label[ 0 ] )
      end = int( param_label[ 1 ] )
      if param_index == active_parameter:
        props.append( {
          'col': begin + 1, # 1-based
          'length': end - begin,
          'type': 'YCM-signature-help-current-argument'
        } )

    lines.append( {
      'text': sig_label,
      'props': props
    } )

  return lines


@memoize()
def ShouldUseSignatureHelp():
  return ( vimsupport.VimHasFunctions( 'screenpos', 'pum_getpos' ) and
           vimsupport.VimSupportsPopupWindows() )


def UpdateSignatureHelp( state, signature_info ): # noqa
  if not ShouldUseSignatureHelp():
    return state

  signatures = signature_info.get( 'signatures' ) or []

  if not signatures:
    if state.popup_win_id:
      # TODO/FIXME: Should we use popup_hide() instead ?
      vim.eval( f"popup_close( { state.popup_win_id } )" )
    return SignatureHelpState( None, SignatureHelpState.INACTIVE )

  if state.state == SignatureHelpState.INACTIVE:
    state.anchor = vimsupport.CurrentLineAndColumn()

    state.state = SignatureHelpState.ACTIVE

  # Generate the buffer as a list of lines
  buf_lines = _MakeSignatureHelpBuffer( signature_info )
  screen_pos = vimsupport.ScreenPositionForLineColumnInWindow(
    vim.current.window,
    state.anchor[ 0 ] + 1,  # anchor 0-based
    state.anchor[ 1 ] + 1 ) # anchor 0-based

  # Simulate 'flip' at the screen boundaries by using screenpos and hiding the
  # signature help menu if it overlaps the completion popup (pum).
  #
  # FIXME: revert to cursor-relative positioning and the 'flip' option when that
  # is implemented (if that is indeed better).

  # By default display above the anchor
  line = int( screen_pos[ 'row' ] ) - 1 # -1 to display above the cur line
  pos = "botleft"

  cursor_line = vimsupport.CurrentLineAndColumn()[ 0 ] + 1
  if int( screen_pos[ 'row' ] ) <= len( buf_lines ):
    # No room at the top, display below
    line = int( screen_pos[ 'row' ] ) + 1
    pos = "topleft"

  # Don't allow the popup to overlap the cursor
  if ( pos == 'topleft' and
       line < cursor_line and
       line + len( buf_lines ) >= cursor_line ):
    line = 0

  # Don't allow the popup to overlap the pum
  if line > 0 and GetIntValue( 'pumvisible()' ):
    pum_line = GetIntValue( 'pum_getpos().row' ) + 1
    if pos == 'botleft' and pum_line <= line:
      line = 0
    elif ( pos == 'topleft' and
           pum_line >= line and
           pum_line < ( line + len( buf_lines ) ) ):
      line = 0

  if line <= 0:
    # Nowhere to put it so hide it
    if state.popup_win_id:
      # TODO/FIXME: Should we use popup_hide() instead ?
      vim.eval( f"popup_close( { state.popup_win_id } )" )
    return SignatureHelpState( None, SignatureHelpState.INACTIVE )

  if int( screen_pos[ 'curscol' ] ) <= 1:
    col = 1
  else:
    # -1 for padding,
    # -1 for the trigger character inserted (the anchor is set _after_ the
    # character is inserted, so we remove it).
    # FIXME: multi-byte characters would be wrong. Need to set anchor before
    # inserting the char ?
    col = int( screen_pos[ 'curscol' ] ) - 2

  if col <= 0:
    col = 1

  options = {
    "line": line,
    "col": col,
    "pos": pos,
    "wrap": 0,
    # NOTE: We *dont'* use "cursorline" here - that actually uses PMenuSel,
    # which is just too invasive for us (it's more selected item than actual
    # cursorline. So instead, we manually set 'cursorline' in the popup window
    # and enable syntax based on the current file syntax)
    "flip": 1,
    "padding": [ 0, 1, 0, 1 ], # Pad 1 char in X axis to match completion menu
    "hidden": int( state.state == SignatureHelpState.ACTIVE_SUPPRESSED )
  }

  if not state.popup_win_id:
    state.popup_win_id = GetIntValue(
      f'popup_create( { json.dumps( buf_lines ) }, '
                    f'{ json.dumps( options ) } )' )
  else:
    vim.eval( f'popup_settext( { state.popup_win_id }, '
                             f'{ json.dumps( buf_lines ) } )' )

  # Should do nothing if already visible
  vim.eval( f'popup_move( { state.popup_win_id }, { json.dumps( options ) } )' )
  if state.state == SignatureHelpState.ACTIVE:
    vim.eval( f'popup_show( { state.popup_win_id } )' )

  if vim.vars.get( 'ycm_signature_help_disable_syntax', False ):
    syntax = ''
  else:
    syntax = utils.ToUnicode( vim.current.buffer.options[ 'syntax' ] )

  active_signature = int( signature_info.get( 'activeSignature', 0 ) )
  vim.eval( f"win_execute( { state.popup_win_id }, "
            f"'set syntax={ syntax } cursorline | "
            f"call cursor( [ { active_signature + 1 }, 1 ] )' )" )

  return state



File: python/ycm/youcompleteme.py

# Copyright (C) 2011-2024 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import base64
import json
import logging
import os
import signal
import vim
from subprocess import PIPE
from tempfile import NamedTemporaryFile
from ycm import base, paths, signature_help, vimsupport
from ycm.buffer import BufferDict
from ycmd import utils
from ycmd.request_wrap import RequestWrap
from ycm.omni_completer import OmniCompleter
from ycm import syntax_parse
from ycm.hierarchy_tree import HierarchyTree
from ycm.client.ycmd_keepalive import YcmdKeepalive
from ycm.client.base_request import BaseRequest, BuildRequestData
from ycm.client.completer_available_request import SendCompleterAvailableRequest
from ycm.client.command_request import ( SendCommandRequest,
                                         SendCommandRequestAsync,
                                         GetCommandResponse,
                                         GetRawCommandResponse )
from ycm.client.completion_request import CompletionRequest
from ycm.client.resolve_completion_request import ResolveCompletionItem
from ycm.client.signature_help_request import ( SignatureHelpRequest,
                                                SigHelpAvailableByFileType )
from ycm.client.debug_info_request import ( SendDebugInfoRequest,
                                            FormatDebugInfoResponse )
from ycm.client.omni_completion_request import OmniCompletionRequest
from ycm.client.event_notification import SendEventNotificationAsync
from ycm.client.shutdown_request import SendShutdownRequest
from ycm.client.messages_request import MessagesPoll


def PatchNoProxy():
  current_value = os.environ.get( 'no_proxy', '' )
  additions = '127.0.0.1,localhost'
  os.environ[ 'no_proxy' ] = ( additions if not current_value
                               else current_value + ',' + additions )


# We need this so that Requests doesn't end up using the local HTTP proxy when
# talking to ycmd. Users should actually be setting this themselves when
# configuring a proxy server on their machine, but most don't know they need to
# or how to do it, so we do it for them.
# Relevant issues:
#  https://github.com/Valloric/YouCompleteMe/issues/641
#  https://github.com/kennethreitz/requests/issues/879
PatchNoProxy()

# Force the Python interpreter embedded in Vim (in which we are running) to
# ignore the SIGINT signal. This helps reduce the fallout of a user pressing
# Ctrl-C in Vim.
signal.signal( signal.SIGINT, signal.SIG_IGN )

HMAC_SECRET_LENGTH = 16
SERVER_SHUTDOWN_MESSAGE = (
  "The ycmd server SHUT DOWN (restart with ':YcmRestartServer')." )
EXIT_CODE_UNEXPECTED_MESSAGE = (
  "Unexpected exit code {code}. "
  "Type ':YcmToggleLogs {logfile}' to check the logs." )
CORE_UNEXPECTED_MESSAGE = (
  "Unexpected error while loading the YCM core library. "
  "Type ':YcmToggleLogs {logfile}' to check the logs." )
CORE_MISSING_MESSAGE = (
  'YCM core library not detected; you need to compile YCM before using it. '
  'Follow the instructions in the documentation.' )
CORE_OUTDATED_MESSAGE = (
  'YCM core library too old; PLEASE RECOMPILE by running the install.py '
  'script. See the documentation for more details.' )
PYTHON_TOO_OLD_MESSAGE = (
  'Your python is too old to run YCM server. '
  'Please see troubleshooting guide on YCM GitHub wiki.'
)
SERVER_IDLE_SUICIDE_SECONDS = 1800  # 30 minutes
CLIENT_LOGFILE_FORMAT = 'ycm_'
SERVER_LOGFILE_FORMAT = 'ycmd_{port}_{std}_'

# Flag to set a file handle inheritable by child processes on Windows. See
# https://msdn.microsoft.com/en-us/library/ms724935.aspx
HANDLE_FLAG_INHERIT = 0x00000001


class YouCompleteMe:
  def __init__( self, default_options = {} ):
    self._logger = logging.getLogger( 'ycm' )
    self._client_logfile = None
    self._server_stdout = None
    self._server_stderr = None
    self._server_popen = None
    self._default_options = default_options
    self._ycmd_keepalive = YcmdKeepalive()
    self._SetUpLogging()
    self._SetUpServer()
    self._ycmd_keepalive.Start()
    self._current_hierarchy = HierarchyTree()


  def InitializeCurrentHierarchy( self, items, kind ):
    return self._current_hierarchy.SetRootNode( items, kind )


  def UpdateCurrentHierarchy( self, handle : int, direction : str ):
    if not self._current_hierarchy.UpdateChangesRoot( handle, direction ):
      items = self._ResolveHierarchyItem( handle, direction )
      self._current_hierarchy.UpdateHierarchy( handle, items, direction )

      if items is not None and direction == 'up':
        offset = sum( len( item[ 'locations' ] ) for item in items )
      else:
        offset = 0

      return self._current_hierarchy.HierarchyToLines(), offset
    else:
      location = self._current_hierarchy.HandleToRootLocation( handle )
      kind = self._current_hierarchy._kind
      self._current_hierarchy.Reset()
      items = GetRawCommandResponse(
        [ f'{ kind.title() }Hierarchy' ],
        silent = False,
        location = location
      )
      # [ 0 ] chooses the data for the 1st (and only) line.
      # [ 1 ] chooses only the handle
      handle = self.InitializeCurrentHierarchy( items, kind )[ 0 ][ 1 ]
      return self.UpdateCurrentHierarchy( handle, direction )


  def _ResolveHierarchyItem( self, handle : int, direction : str ):
    return GetRawCommandResponse(
      self._current_hierarchy.ResolveArguments( handle, direction ),
      silent = False
    )


  def ShouldResolveItem( self, handle : int, direction : str ):
    return self._current_hierarchy.ShouldResolveItem( handle, direction )


  def ResetCurrentHierarchy( self ):
    self._current_hierarchy.Reset()


  def JumpToHierarchyItem( self, handle ):
    self._current_hierarchy.JumpToItem(
        handle,
        self._user_options[ 'goto_buffer_command' ] )


  def _SetUpServer( self ):
    self._available_completers = {}
    self._user_notified_about_crash = False
    self._filetypes_with_keywords_loaded = set()
    self._server_is_ready_with_cache = False
    self._message_poll_requests = {}

    self._latest_completion_request = None
    self._latest_signature_help_request = None
    self._signature_help_available_requests = SigHelpAvailableByFileType()
    self._command_requests = {}
    self._next_command_request_id = 0

    self._signature_help_state = signature_help.SignatureHelpState()
    self._user_options = base.GetUserOptions( self._default_options )
    self._omnicomp = OmniCompleter( self._user_options )
    self._buffers = BufferDict( self._user_options )

    self._SetLogLevel()

    hmac_secret = os.urandom( HMAC_SECRET_LENGTH )
    options_dict = dict( self._user_options )
    options_dict[ 'hmac_secret' ] = utils.ToUnicode(
      base64.b64encode( hmac_secret ) )
    options_dict[ 'server_keep_logfiles' ] = self._user_options[
      'keep_logfiles' ]

    # The temp options file is deleted by ycmd during startup.
    with NamedTemporaryFile( delete = False, mode = 'w+' ) as options_file:
      json.dump( options_dict, options_file )

    server_port = utils.GetUnusedLocalhostPort()

    BaseRequest.server_location = 'http://127.0.0.1:' + str( server_port )
    BaseRequest.hmac_secret = hmac_secret

    try:
      python_interpreter = paths.PathToPythonInterpreter()
    except RuntimeError as error:
      error_message = (
        f"Unable to start the ycmd server. { str( error ).rstrip( '.' ) }. "
        "Correct the error then restart the server "
        "with ':YcmRestartServer'." )
      self._logger.exception( error_message )
      vimsupport.PostVimMessage( error_message )
      return

    args = [ python_interpreter,
             paths.PathToServerScript(),
             f'--port={ server_port }',
             f'--options_file={ options_file.name }',
             f'--log={ self._user_options[ "log_level" ] }',
             f'--idle_suicide_seconds={ SERVER_IDLE_SUICIDE_SECONDS }' ]

    self._server_stdout = utils.CreateLogfile(
        SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stdout' ) )
    self._server_stderr = utils.CreateLogfile(
        SERVER_LOGFILE_FORMAT.format( port = server_port, std = 'stderr' ) )
    args.append( f'--stdout={ self._server_stdout }' )
    args.append( f'--stderr={ self._server_stderr }' )

    if self._user_options[ 'keep_logfiles' ]:
      args.append( '--keep_logfiles' )

    self._server_popen = utils.SafePopen( args, stdin_windows = PIPE,
                                          stdout = PIPE, stderr = PIPE )


  def _SetUpLogging( self ):
    def FreeFileFromOtherProcesses( file_object ):
      if utils.OnWindows():
        from ctypes import windll
        import msvcrt

        file_handle = msvcrt.get_osfhandle( file_object.fileno() )
        windll.kernel32.SetHandleInformation( file_handle,
                                              HANDLE_FLAG_INHERIT,
                                              0 )

    self._client_logfile = utils.CreateLogfile( CLIENT_LOGFILE_FORMAT )

    handler = logging.FileHandler( self._client_logfile )

    # On Windows and Python prior to 3.4, file handles are inherited by child
    # processes started with at least one replaced standard stream, which is the
    # case when we start the ycmd server (we are redirecting all standard
    # outputs into a pipe). These files cannot be removed while the child
    # processes are still up. This is not desirable for a logfile because we
    # want to remove it at Vim exit without having to wait for the ycmd server
    # to be completely shut down. We need to make the logfile handle
    # non-inheritable. See https://www.python.org/dev/peps/pep-0446 for more
    # details.
    FreeFileFromOtherProcesses( handler.stream )

    formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' )
    handler.setFormatter( formatter )

    self._logger.addHandler( handler )


  def _SetLogLevel( self ):
    log_level = self._user_options[ 'log_level' ]
    numeric_level = getattr( logging, log_level.upper(), None )
    if not isinstance( numeric_level, int ):
      raise ValueError( f'Invalid log level: { log_level }' )
    self._logger.setLevel( numeric_level )


  def IsServerAlive( self ):
    # When the process hasn't finished yet, poll() returns None.
    return bool( self._server_popen ) and self._server_popen.poll() is None


  def CheckIfServerIsReady( self ):
    if not self._server_is_ready_with_cache and self.IsServerAlive():
      self._server_is_ready_with_cache = BaseRequest().GetDataFromHandler(
          'ready', display_message = False )
    return self._server_is_ready_with_cache


  def IsServerReady( self ):
    return self._server_is_ready_with_cache


  def NotifyUserIfServerCrashed( self ):
    if ( not self._server_popen or self._user_notified_about_crash or
         self.IsServerAlive() ):
      return
    self._user_notified_about_crash = True

    return_code = self._server_popen.poll()
    logfile = os.path.basename( self._server_stderr )
    # See https://github.com/Valloric/ycmd#exit-codes for the list of exit
    # codes.
    if return_code == 3:
      error_message = CORE_UNEXPECTED_MESSAGE.format( logfile = logfile )
    elif return_code == 4:
      error_message = CORE_MISSING_MESSAGE
    elif return_code == 7:
      error_message = CORE_OUTDATED_MESSAGE
    elif return_code == 8:
      # TODO: here we could retry but discard g:ycm_server_python_interpreter
      error_message = PYTHON_TOO_OLD_MESSAGE
    else:
      error_message = EXIT_CODE_UNEXPECTED_MESSAGE.format( code = return_code,
                                                           logfile = logfile )

    if return_code != 8:
      error_message = SERVER_SHUTDOWN_MESSAGE + ' ' + error_message
    self._logger.error( error_message )
    vimsupport.PostVimMessage( error_message )


  def ServerPid( self ):
    if not self._server_popen:
      return -1
    return self._server_popen.pid


  def _ShutdownServer( self ):
    SendShutdownRequest()


  def RestartServer( self ):
    vimsupport.PostVimMessage( 'Restarting ycmd server...' )
    self._ShutdownServer()
    self._SetUpServer()


  def SendCompletionRequest( self, force_semantic = False ):
    request_data = BuildRequestData()
    request_data[ 'force_semantic' ] = force_semantic

    if not self.NativeFiletypeCompletionUsable():
      wrapped_request_data = RequestWrap( request_data )
      if self._omnicomp.ShouldUseNow( wrapped_request_data ):
        self._latest_completion_request = OmniCompletionRequest(
            self._omnicomp, wrapped_request_data )
        self._latest_completion_request.Start()
        return

    self._AddExtraConfDataIfNeeded( request_data )
    self._latest_completion_request = CompletionRequest( request_data )
    self._latest_completion_request.Start()


  def CompletionRequestReady( self ):
    return bool( self._latest_completion_request and
                 self._latest_completion_request.Done() )


  def GetCompletionResponse( self ):
    return self._latest_completion_request.Response()


  def SignatureHelpAvailableRequestComplete( self, filetype, send_new=True ):
    """Triggers or polls signature help available request. Returns whether or
    not the request is complete. When send_new is False, won't send a new
    request, only return the current status (This is used by the tests)"""
    if not send_new and filetype not in self._signature_help_available_requests:
      return False

    return self._signature_help_available_requests[ filetype ].Done()


  def SendSignatureHelpRequest( self ):
    """Send a signature help request, if we're ready to. Return whether or not a
    request was sent (and should be checked later)"""
    if not self.NativeFiletypeCompletionUsable():
      return False

    for filetype in vimsupport.CurrentFiletypes():
      if not self.SignatureHelpAvailableRequestComplete( filetype ):
        continue

      sig_help_available = self._signature_help_available_requests[
          filetype ].Response()
      if sig_help_available == 'NO':
        continue

      if sig_help_available == 'PENDING':
        # Send another /signature_help_available request
        self._signature_help_available_requests[ filetype ].Start( filetype )
        continue

      if not self._latest_completion_request:
        return False

      request_data = self._latest_completion_request.request_data.copy()
      request_data[ 'signature_help_state' ] = (
          self._signature_help_state.IsActive()
      )

      self._AddExtraConfDataIfNeeded( request_data )

      self._latest_signature_help_request = SignatureHelpRequest( request_data )
      self._latest_signature_help_request.Start()
      return True

    return False


  def SignatureHelpRequestReady( self ):
    return bool( self._latest_signature_help_request and
                 self._latest_signature_help_request.Done() )


  def GetSignatureHelpResponse( self ):
    return self._latest_signature_help_request.Response()


  def ClearSignatureHelp( self ):
    self.UpdateSignatureHelp( {} )
    if self._latest_signature_help_request:
      self._latest_signature_help_request.Reset()


  def UpdateSignatureHelp( self, signature_info ):
    self._signature_help_state = signature_help.UpdateSignatureHelp(
      self._signature_help_state,
      signature_info )


  def _GetCommandRequestArguments( self,
                                   arguments,
                                   has_range,
                                   start_line,
                                   end_line ):
    extra_data = {
      'options': {
        'tab_size': vimsupport.GetIntValue( 'shiftwidth()' ),
        'insert_spaces': vimsupport.GetBoolValue( '&expandtab' )
      }
    }

    final_arguments = []
    for argument in arguments:
      if argument.startswith( 'ft=' ):
        extra_data[ 'completer_target' ] = argument[ 3: ]
        continue
      elif argument.startswith( '--bufnr=' ):
        extra_data[ 'bufnr' ] = int( argument[ len( '--bufnr=' ): ] )
        continue

      final_arguments.append( argument )

    if has_range:
      extra_data.update( vimsupport.BuildRange( start_line, end_line ) )
    self._AddExtraConfDataIfNeeded( extra_data )

    return final_arguments, extra_data



  def SendCommandRequest( self,
                          arguments,
                          modifiers,
                          has_range,
                          start_line,
                          end_line ):
    final_arguments, extra_data = self._GetCommandRequestArguments(
      arguments,
      has_range,
      start_line,
      end_line )
    return SendCommandRequest(
      final_arguments,
      modifiers,
      self._user_options[ 'goto_buffer_command' ],
      extra_data )


  def GetCommandResponse( self, arguments ):
    final_arguments, extra_data = self._GetCommandRequestArguments(
      arguments,
      False,
      0,
      0 )
    return GetCommandResponse( final_arguments, extra_data )


  def SendCommandRequestAsync( self,
                               arguments,
                               silent = True,
                               location = None ):
    final_arguments, extra_data = self._GetCommandRequestArguments(
      arguments,
      False,
      0,
      0 )

    request_id = self._next_command_request_id
    self._next_command_request_id += 1
    self._command_requests[ request_id ] = SendCommandRequestAsync(
      final_arguments,
      extra_data,
      silent,
      location = location )
    return request_id


  def GetCommandRequest( self, request_id ):
    return self._command_requests.get( request_id )


  def FlushCommandRequest( self, request_id ):
    self._command_requests.pop( request_id, None )


  def GetDefinedSubcommands( self ):
    request = BaseRequest()
    subcommands = request.PostDataToHandler( BuildRequestData(),
                                             'defined_subcommands' )
    return subcommands if subcommands else []


  def GetCurrentCompletionRequest( self ):
    return self._latest_completion_request


  def GetOmniCompleter( self ):
    return self._omnicomp


  def FiletypeCompleterExistsForFiletype( self, filetype ):
    try:
      return self._available_completers[ filetype ]
    except KeyError:
      pass

    exists_completer = SendCompleterAvailableRequest( filetype )
    if exists_completer is None:
      return False

    self._available_completers[ filetype ] = exists_completer
    return exists_completer


  def NativeFiletypeCompletionAvailable( self ):
    return any( self.FiletypeCompleterExistsForFiletype( x ) for x in
                vimsupport.CurrentFiletypes() )


  def NativeFiletypeCompletionUsable( self ):
    disabled_filetypes = self._user_options[
      'filetype_specific_completion_to_disable' ]
    return ( vimsupport.CurrentFiletypesEnabled( disabled_filetypes ) and
             self.NativeFiletypeCompletionAvailable() )


  def NeedsReparse( self ):
    return self.CurrentBuffer().NeedsReparse()


  def UpdateWithNewDiagnosticsForFile( self, filepath, diagnostics ):
    if not self._user_options[ 'show_diagnostics_ui' ]:
      return

    bufnr = vimsupport.GetBufferNumberForFilename( filepath )
    if bufnr in self._buffers and vimsupport.BufferIsVisible( bufnr ):
      # Note: We only update location lists, etc. for visible buffers, because
      # otherwise we default to using the current location list and the results
      # are that non-visible buffer errors clobber visible ones.
      self._buffers[ bufnr ].UpdateWithNewDiagnostics( diagnostics, True )
    else:
      # The project contains errors in file "filepath", but that file is not
      # open in any buffer. This happens for Language Server Protocol-based
      # completers, as they return diagnostics for the entire "project"
      # asynchronously (rather than per-file in the response to the parse
      # request).
      #
      # There are a number of possible approaches for
      # this, but for now we simply ignore them. Other options include:
      # - Use the QuickFix list to report project errors?
      # - Use a special buffer for project errors
      # - Put them in the location list of whatever the "current" buffer is
      # - Store them in case the buffer is opened later
      # - add a :YcmProjectDiags command
      # - Add them to errror/warning _counts_ but not any actual location list
      #   or other
      # - etc.
      #
      # However, none of those options are great, and lead to their own
      # complexities. So for now, we just ignore these diagnostics for files not
      # open in any buffer.
      pass


  def OnPeriodicTick( self ):
    if not self.IsServerAlive():
      # Server has died. We'll reset when the server is started again.
      return False
    elif not self.IsServerReady():
      # Try again in a jiffy
      return True

    for w in vim.windows:
      for filetype in vimsupport.FiletypesForBuffer( w.buffer ):
        if filetype not in self._message_poll_requests:
          self._message_poll_requests[ filetype ] = MessagesPoll( w.buffer )

        # None means don't poll this filetype
        if ( self._message_poll_requests[ filetype ] and
             not self._message_poll_requests[ filetype ].Poll( self ) ):
          self._message_poll_requests[ filetype ] = None

    return any( self._message_poll_requests.values() )


  def OnFileReadyToParse( self ):
    if not self.IsServerAlive():
      self.NotifyUserIfServerCrashed()
      return

    if not self.IsServerReady():
      return

    extra_data = {}
    self._AddTagsFilesIfNeeded( extra_data )
    self._AddSyntaxDataIfNeeded( extra_data )
    self._AddExtraConfDataIfNeeded( extra_data )

    self.CurrentBuffer().SendParseRequest( extra_data )


  def OnFileSave( self, saved_buffer_number ):
    SendEventNotificationAsync( 'FileSave', saved_buffer_number )


  def OnBufferUnload( self, deleted_buffer_number ):
    SendEventNotificationAsync( 'BufferUnload', deleted_buffer_number )


  def UpdateMatches( self ):
    self.CurrentBuffer().UpdateMatches()


  def OnFileTypeSet( self ):
    buffer_number = vimsupport.GetCurrentBufferNumber()
    filetypes = vimsupport.CurrentFiletypes()
    self._buffers[ buffer_number ].UpdateFromFileTypes( filetypes )
    self.OnBufferVisit()


  def OnBufferVisit( self ):
    for filetype in vimsupport.CurrentFiletypes():
      # Send the signature help available request for these filetypes if we need
      # to (as a side effect of checking if it is complete)
      self.SignatureHelpAvailableRequestComplete( filetype, True )

    extra_data = {}
    self._AddUltiSnipsDataIfNeeded( extra_data )
    SendEventNotificationAsync( 'BufferVisit', extra_data = extra_data )


  def CurrentBuffer( self ):
    return self.Buffer( vimsupport.GetCurrentBufferNumber() )


  def Buffer( self, bufnr ):
    return self._buffers[ bufnr ]


  def OnInsertEnter( self ):
    if not self._user_options[ 'update_diagnostics_in_insert_mode' ]:
      self.CurrentBuffer().ClearDiagnosticsUI()


  def OnInsertLeave( self ):
    async_diags = any( self._message_poll_requests.get( filetype )
                      for filetype in vimsupport.CurrentFiletypes() )
    if ( not self._user_options[ 'update_diagnostics_in_insert_mode' ] and
         ( async_diags or not self.CurrentBuffer().ParseRequestPending() ) ):
      self.CurrentBuffer().RefreshDiagnosticsUI()
    SendEventNotificationAsync( 'InsertLeave' )


  def OnCursorMoved( self ):
    self.CurrentBuffer().OnCursorMoved()


  def _CleanLogfile( self ):
    logging.shutdown()
    if not self._user_options[ 'keep_logfiles' ]:
      if self._client_logfile:
        utils.RemoveIfExists( self._client_logfile )


  def OnVimLeave( self ):
    self._ShutdownServer()
    self._CleanLogfile()


  def OnCurrentIdentifierFinished( self ):
    SendEventNotificationAsync( 'CurrentIdentifierFinished' )


  def OnCompleteDone( self ):
    completion_request = self.GetCurrentCompletionRequest()
    if completion_request:
      completion_request.OnCompleteDone()


  def ResolveCompletionItem( self, item ):
    # Note: As mentioned elsewhere, we replace the current completion request
    # with a resolve request. It's not valid to have simultaneous resolve and
    # completion requests, because the resolve request uses the request data
    # from the last completion request and is therefore dependent on it not
    # having changed.
    #
    # The result of this is that self.GetCurrentCompletionRequest() might return
    # either a completion request of a resolve request and it's the
    # responsibility of the vimscript code to ensure that it only does one at a
    # time. This is handled by re-using the same poller for completions and
    # resolves.
    completion_request = self.GetCurrentCompletionRequest()
    if not completion_request:
      return False

    request  = ResolveCompletionItem( completion_request, item )
    if not request:
      return False

    self._latest_completion_request = request
    return True


  def GetErrorCount( self ):
    return self.CurrentBuffer().GetErrorCount()


  def GetWarningCount( self ):
    return self.CurrentBuffer().GetWarningCount()


  def _PopulateLocationListWithLatestDiagnostics( self ):
    return self.CurrentBuffer().PopulateLocationList(
        self._user_options[ 'open_loclist_on_ycm_diags' ] )


  def FileParseRequestReady( self ):
    # Return True if server is not ready yet, to stop repeating check timer.
    return ( not self.IsServerReady() or
             self.CurrentBuffer().FileParseRequestReady() )


  def HandleFileParseRequest( self, block = False ):
    if not self.IsServerReady():
      return

    current_buffer = self.CurrentBuffer()
    # Order is important here:
    # FileParseRequestReady has a low cost, while
    # NativeFiletypeCompletionUsable is a blocking server request
    if ( not current_buffer.IsResponseHandled() and
         current_buffer.FileParseRequestReady( block ) and
         self.NativeFiletypeCompletionUsable() ):

      if self._user_options[ 'show_diagnostics_ui' ]:
        # Forcefuly update the location list, etc. from the parse request when
        # doing something like :YcmDiags
        async_diags = any( self._message_poll_requests.get( filetype )
                           for filetype in vimsupport.CurrentFiletypes() )
        current_buffer.UpdateDiagnostics( block or not async_diags )
      else:
        # If the user disabled diagnostics, we just want to check
        # the _latest_file_parse_request for any exception or UnknownExtraConf
        # response, to allow the server to raise configuration warnings, etc.
        # to the user. We ignore any other supplied data.
        current_buffer.GetResponse()

      # We set the file parse request as handled because we want to prevent
      # repeated issuing of the same warnings/errors/prompts. Setting this
      # makes IsRequestHandled return True until the next request is created.
      #
      # Note: it is the server's responsibility to determine the frequency of
      # error/warning/prompts when receiving a FileReadyToParse event, but
      # it is our responsibility to ensure that we only apply the
      # warning/error/prompt received once (for each event).
      current_buffer.MarkResponseHandled()


  def ShouldResendFileParseRequest( self ):
    return self.CurrentBuffer().ShouldResendParseRequest()


  def DebugInfo( self ):
    debug_info = ''
    if self._client_logfile:
      debug_info += f'Client logfile: { self._client_logfile }\n'
    extra_data = {}
    self._AddExtraConfDataIfNeeded( extra_data )
    debug_info += FormatDebugInfoResponse( SendDebugInfoRequest( extra_data ) )
    debug_info += f'Server running at: { BaseRequest.server_location }\n'
    if self._server_popen:
      debug_info += f'Server process ID: { self._server_popen.pid }\n'
    if self._server_stdout and self._server_stderr:
      debug_info += ( 'Server logfiles:\n'
                      f'  { self._server_stdout }\n'
                      f'  { self._server_stderr }' )
    debug_info += ( '\nSemantic highlighting supported: ' +
                    str( not vimsupport.VimIsNeovim() ) )
    debug_info += ( '\nVirtual text supported: ' +
                    str( not vimsupport.VimIsNeovim() ) )
    debug_info += ( '\nPopup windows supported: ' +
                    str( vimsupport.VimSupportsPopupWindows() ) )
    return debug_info


  def GetLogfiles( self ):
    logfiles_list = [ self._client_logfile,
                      self._server_stdout,
                      self._server_stderr ]

    extra_data = {}
    self._AddExtraConfDataIfNeeded( extra_data )
    debug_info = SendDebugInfoRequest( extra_data )
    if debug_info:
      completer = debug_info[ 'completer' ]
      if completer:
        for server in completer[ 'servers' ]:
          logfiles_list.extend( server[ 'logfiles' ] )

    logfiles = {}
    for logfile in logfiles_list:
      logfiles[ os.path.basename( logfile ) ] = logfile
    return logfiles


  def _OpenLogfile( self, size, mods, logfile ):
    # Open log files in a horizontal window with the same behavior as the
    # preview window (same height and winfixheight enabled). Automatically
    # watch for changes. Set the cursor position at the end of the file.
    if not size:
      size = vimsupport.GetIntValue( '&previewheight' )

    options = {
      'size': size,
      'fix': True,
      'focus': False,
      'watch': True,
      'position': 'end',
      'mods': mods
    }

    vimsupport.OpenFilename( logfile, options )


  def _CloseLogfile( self, logfile ):
    vimsupport.CloseBuffersForFilename( logfile )


  def ToggleLogs( self, size, mods, *filenames ):
    logfiles = self.GetLogfiles()
    if not filenames:
      sorted_logfiles = sorted( logfiles )
      try:
        logfile_index = vimsupport.SelectFromList(
          'Which logfile do you wish to open (or close if already open)?',
          sorted_logfiles )
      except RuntimeError as e:
        vimsupport.PostVimMessage( str( e ) )
        return

      logfile = logfiles[ sorted_logfiles[ logfile_index ] ]
      if not vimsupport.BufferIsVisibleForFilename( logfile ):
        self._OpenLogfile( size, mods, logfile )
      else:
        self._CloseLogfile( logfile )
      return

    for filename in set( filenames ):
      if filename not in logfiles:
        continue

      logfile = logfiles[ filename ]

      if not vimsupport.BufferIsVisibleForFilename( logfile ):
        self._OpenLogfile( size, mods, logfile )
        continue

      self._CloseLogfile( logfile )


  def ShowDetailedDiagnostic( self, message_in_popup ):
    detailed_diagnostic = BaseRequest().PostDataToHandler(
        BuildRequestData(), 'detailed_diagnostic' )
    if detailed_diagnostic and 'message' in detailed_diagnostic:
      message = detailed_diagnostic[ 'message' ]
      if message_in_popup and vimsupport.VimSupportsPopupWindows():
        window = vim.current.window
        buffer_number = vimsupport.GetCurrentBufferNumber()
        diags_on_this_line = self._buffers[ buffer_number ].DiagnosticsForLine(
            window.cursor[ 0 ] )

        lines = message.split( '\n' )
        available_columns = vimsupport.GetIntValue( '&columns' )
        col = window.cursor[ 1 ] + 1
        if col > available_columns - 2: # -2 accounts for padding.
          col = 0
        options = {
          'col': col,
          'padding': [ 0, 1, 0, 1 ],
          'maxwidth': available_columns,
          'close': 'click',
          'fixed': 0,
          'highlight': 'YcmErrorPopup',
          'border': [ 1, 1, 1, 1 ],
          # Close when moving cursor
          'moved': 'expr',
        }
        popup_func = 'popup_atcursor'
        for diag in diags_on_this_line:
          if message == diag[ 'text' ]:
            popup_func = 'popup_create'
            prop = vimsupport.GetTextPropertyForDiag( buffer_number,
                                                      window.cursor[ 0 ],
                                                      diag )
            options.update( {
              'textpropid': prop[ 'id' ],
              'textprop': prop[ 'type' ],
            } )
            options.pop( 'col' )
            break
        vim.eval( f'{ popup_func }( { json.dumps( lines ) }, '
                                  f'{ json.dumps( options ) } )' )
      else:
        vimsupport.PostVimMessage( message, warning = False )


  def ForceCompileAndDiagnostics( self ):
    if not self.NativeFiletypeCompletionUsable():
      vimsupport.PostVimMessage(
          'Native filetype completion not supported for current file, '
          'cannot force recompilation.', warning = False )
      return False
    vimsupport.PostVimMessage(
        'Forcing compilation, this will block Vim until done.',
        warning = False )
    self.OnFileReadyToParse()
    self.HandleFileParseRequest( block = True )
    vimsupport.PostVimMessage( 'Diagnostics refreshed', warning = False )
    return True


  def ShowDiagnostics( self ):
    if not self.ForceCompileAndDiagnostics():
      return

    if not self._PopulateLocationListWithLatestDiagnostics():
      vimsupport.PostVimMessage( 'No warnings or errors detected.',
                                 warning = False )
      return

    if self._user_options[ 'open_loclist_on_ycm_diags' ]:
      vimsupport.OpenLocationList( focus = True )


  def FilterAndSortItems( self,
                          items,
                          sort_property,
                          query,
                          max_items = 0 ):
    return BaseRequest().PostDataToHandler( {
      'candidates': items,
      'sort_property': sort_property,
      'max_num_candidates': max_items,
      'query': vimsupport.ToUnicode( query )
    }, 'filter_and_sort_candidates' )


  def ToggleSignatureHelp( self ):
    self._signature_help_state.ToggleVisibility()


  def _AddSyntaxDataIfNeeded( self, extra_data ):
    if not self._user_options[ 'seed_identifiers_with_syntax' ]:
      return
    filetype = vimsupport.CurrentFiletypes()[ 0 ]
    if filetype in self._filetypes_with_keywords_loaded:
      return

    if self.IsServerReady():
      self._filetypes_with_keywords_loaded.add( filetype )
    extra_data[ 'syntax_keywords' ] = list(
       syntax_parse.SyntaxKeywordsForCurrentBuffer() )


  def _AddTagsFilesIfNeeded( self, extra_data ):
    def GetTagFiles():
      tag_files = vim.eval( 'tagfiles()' )
      return [ ( os.path.join( utils.GetCurrentDirectory(), tag_file )
                 if not os.path.isabs( tag_file ) else tag_file )
               for tag_file in tag_files ]

    if not self._user_options[ 'collect_identifiers_from_tags_files' ]:
      return
    extra_data[ 'tag_files' ] = GetTagFiles()


  def _AddExtraConfDataIfNeeded( self, extra_data ):
    def BuildExtraConfData( extra_conf_vim_data ):
      extra_conf_data = {}
      for expr in extra_conf_vim_data:
        try:
          extra_conf_data[ expr ] = vimsupport.VimExpressionToPythonType( expr )
        except vim.error:
          message = (
            f"Error evaluating '{ expr }' in the 'g:ycm_extra_conf_vim_data' "
            "option." )
          vimsupport.PostVimMessage( message, truncate = True )
          self._logger.exception( message )
      return extra_conf_data

    extra_conf_vim_data = self._user_options[ 'extra_conf_vim_data' ]
    if extra_conf_vim_data:
      extra_data[ 'extra_conf_data' ] = BuildExtraConfData(
        extra_conf_vim_data )


  def _AddUltiSnipsDataIfNeeded( self, extra_data ):
    # See :h UltiSnips#SnippetsInCurrentScope.
    try:
      vim.eval( 'UltiSnips#SnippetsInCurrentScope( 1 )' )
    except vim.error:
      return

    snippets = vimsupport.GetVariableValue( 'g:current_ulti_dict_info' )
    extra_data[ 'ultisnips_snippets' ] = [
      { 'trigger': trigger,
        'description': snippet[ 'description' ] }
      for trigger, snippet in snippets.items()
    ]



File: python/ycm/vimsupport.py

# Copyright (C) 2011-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import vim
import os
import json
import re
from collections import defaultdict, namedtuple
from functools import lru_cache as memoize
from ycmd.utils import ( ByteOffsetToCodepointOffset,
                         GetCurrentDirectory,
                         JoinLinesAsUnicode,
                         OnMac,
                         OnWindows,
                         ToBytes,
                         ToUnicode )

BUFFER_COMMAND_MAP = { 'same-buffer'      : 'edit',
                       'split'            : 'split',
                       # These commands are obsolete. :vertical or :tab should
                       # be used with the 'split' command instead.
                       'horizontal-split' : 'split',
                       'vertical-split'   : 'vsplit',
                       'new-tab'          : 'tabedit' }

FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = (
    'The requested operation will apply changes to {0} files which are not '
    'currently open. This will therefore open {0} new files in the hidden '
    'buffers. The quickfix list can then be used to review the changes. No '
    'files will be written to disk. Do you wish to continue?' )

NO_SELECTION_MADE_MSG = "No valid selection was made; aborting."

# When we're in a buffer without a file name associated with it, we need to
# invent a file name. We do so by the means of $CWD/$BUFNR.
# However, that causes problems with diagnostics - we also need a way to map
# those same file names back to their originating buffer numbers.
MADEUP_FILENAME_TO_BUFFER_NUMBER = {}

NO_COMPLETIONS = {
  'line': -1,
  'column': -1,
  'completion_start_column': -1,
  'completions': []
}

YCM_NEOVIM_NS_ID = vim.eval( 'g:ycm_neovim_ns_id' )


def CurrentLineAndColumn():
  """Returns the 0-based current line and 0-based current column."""
  # See the comment in CurrentColumn about the calculation for the line and
  # column number
  line, column = vim.current.window.cursor
  line -= 1
  return line, column


def SetCurrentLineAndColumn( line, column ):
  """Sets the cursor position to the 0-based line and 0-based column."""
  # Line from vim.current.window.cursor is 1-based.
  vim.current.window.cursor = ( line + 1, column )


def CurrentColumn():
  """Returns the 0-based current column. Do NOT access the CurrentColumn in
  vim.current.line. It doesn't exist yet when the cursor is at the end of the
  line. Only the chars before the current column exist in vim.current.line."""

  # vim's columns are 1-based while vim.current.line columns are 0-based
  # ... but vim.current.window.cursor (which returns a (line, column) tuple)
  # columns are 0-based, while the line from that same tuple is 1-based.
  # vim.buffers buffer objects OTOH have 0-based lines and columns.
  # Pigs have wings and I'm a loopy purple duck. Everything makes sense now.
  return vim.current.window.cursor[ 1 ]


def CurrentLineContents():
  return ToUnicode( vim.current.line )


def CurrentLineContentsAndCodepointColumn():
  """Returns the line contents as a unicode string and the 0-based current
  column as a codepoint offset. If the current column is outside the line,
  returns the column position at the end of the line."""
  line = CurrentLineContents()
  byte_column = CurrentColumn()
  # ByteOffsetToCodepointOffset expects 1-based offset.
  column = ByteOffsetToCodepointOffset( line, byte_column + 1 ) - 1
  return line, column


def TextAfterCursor():
  """Returns the text after CurrentColumn."""
  return ToUnicode( vim.current.line[ CurrentColumn(): ] )


def TextBeforeCursor():
  """Returns the text before CurrentColumn."""
  return ToUnicode( vim.current.line[ :CurrentColumn() ] )


def BufferModified( buffer_object ):
  return buffer_object.options[ 'mod' ]


def GetBufferData( buffer_object ):
  return {
    # Add a newline to match what gets saved to disk. See #1455 for details.
    'contents': JoinLinesAsUnicode( buffer_object ) + '\n',
    'filetypes': FiletypesForBuffer( buffer_object )
  }


def GetUnsavedAndSpecifiedBufferData( included_buffer, included_filepath ):
  """Build part of the request containing the contents and filetypes of all
  dirty buffers as well as the buffer |included_buffer| with its filepath
  |included_filepath|."""
  buffers_data = { included_filepath: GetBufferData( included_buffer ) }

  for buffer_object in vim.buffers:
    if not BufferModified( buffer_object ):
      continue

    filepath = GetBufferFilepath( buffer_object )
    if filepath in buffers_data:
      continue

    buffers_data[ filepath ] = GetBufferData( buffer_object )

  return buffers_data


def GetBufferNumberForFilename( filename, create_buffer_if_needed = False ):
  realpath = os.path.realpath( filename )
  return MADEUP_FILENAME_TO_BUFFER_NUMBER.get( realpath, GetIntValue(
      f"bufnr( '{ EscapeForVim( realpath ) }', "
             f"{ int( create_buffer_if_needed ) } )" ) )


def GetCurrentBufferFilepath():
  return GetBufferFilepath( vim.current.buffer )


def BufferIsVisible( buffer_number ):
  if buffer_number < 0:
    return False
  window_number = GetIntValue( f"bufwinnr( { buffer_number } )" )
  return window_number != -1


def GetBufferFilepath( buffer_object ):
  if buffer_object.name:
    return os.path.abspath( ToUnicode( buffer_object.name ) )
  # Buffers that have just been created by a command like :enew don't have any
  # buffer name so we use the buffer number for that.
  name = os.path.join( GetCurrentDirectory(), str( buffer_object.number ) )
  MADEUP_FILENAME_TO_BUFFER_NUMBER[ name ] = buffer_object.number
  return name


def GetCurrentBufferNumber():
  return vim.current.buffer.number


def GetBufferChangedTick( bufnr ):
  try:
    return GetIntValue( f'getbufvar({ bufnr }, "changedtick")' )
  except ValueError:
    # For some reason, occasionally changedtick returns '' and causes an error.
    # In that case, just return 0 rather than spamming an error to the console.
    return 0


# Returns a range covering the earliest and latest lines visible in the current
# tab page for the supplied buffer number. By default this range is then
# extended by half of the resulting range size
def RangeVisibleInBuffer( bufnr, grow_factor=0.5 ):
  windows = [ w for w in vim.eval( f'win_findbuf( { bufnr } )' )
              if GetIntValue( vim.eval( f'win_id2tabwin( { w } )[ 0 ]' ) ) ==
                vim.current.tabpage.number ]

  class Location:
    line: int = None
    col: int = None

  class Range:
    start: Location = Location()
    end: Location = Location()

  try:
    buffer = vim.buffers[ bufnr ]
  except KeyError:
    return None

  if not windows:
    return None

  r = Range()
  # Note, for this we ignore horizontal scrolling
  for winid in windows:
    win_info = vim.eval( f'getwininfo( { winid } )[ 0 ]' )
    if r.start.line is None or r.start.line > int( win_info[ 'topline' ] ):
      r.start.line = int( win_info[ 'topline' ] )
    if r.end.line is None or r.end.line < int( win_info[ 'botline' ] ):
      r.end.line = int( win_info[ 'botline' ] )

  # Extend the range by 1 factor, and calculate the columns
  num_lines = r.end.line - r.start.line + 1
  r.start.line = max( r.start.line - int( num_lines * grow_factor ), 1 )
  r.start.col = 1
  r.end.line = min( r.end.line + int( num_lines * grow_factor ), len( buffer ) )
  r.end.col = len( buffer[ r.end.line - 1 ] )

  filepath = GetBufferFilepath( buffer )
  return {
    'start': {
      'line_num': r.start.line,
      'column_num': r.start.col,
      'filepath': filepath,
    },
    'end': {
      'line_num': r.end.line,
      'column_num': r.end.col,
      'filepath': filepath,
    }
  }


def VisibleRangeOfBufferOverlaps( bufnr, expanded_range ):
  visible_range = RangeVisibleInBuffer( bufnr, 0 )
  # As above, we ignore horizontal scroll and only check lines
  return (
    expanded_range is not None and
    visible_range is not None and
    visible_range[ 'start' ][ 'line_num' ]
      >= expanded_range[ 'start' ][ 'line_num' ] and
    visible_range[ 'end' ][ 'line_num' ]
      <= expanded_range[ 'end' ][ 'line_num' ]
  )


def CaptureVimCommand( command ):
  return vim.eval( f"execute( '{ EscapeForVim( command ) }', 'silent!' )" )


def GetSignsInBuffer( buffer_number ):
  return vim.eval(
      f'sign_getplaced( { buffer_number }, {{ "group": "ycm_signs" }} )'
  )[ 0 ][ 'signs' ]


class DiagnosticProperty( namedtuple( 'DiagnosticProperty', [ 'id',
                                                              'type',
                                                              'line',
                                                              'column',
                                                              'length' ] ) ):
  def __eq__( self, other ):
    return ( self.type == other.type and
             self.line == other.line and
             self.column == other.column and
             self.length == other.length )


def GetTextPropertyForDiag( buffer_number, line_number, diag ):
  range = diag[ 'location_extent' ]
  start = range[ 'start' ]
  end = range[ 'end' ]
  start_line = start[ 'line_num' ]
  end_line = end[ 'line_num' ]
  if start_line == end_line:
    length = end[ 'column_num' ] - start[ 'column_num' ]
    column = start[ 'column_num' ]
  elif start_line == line_number:
    # -1 switches to 0-based indexing.
    current_line_len = len( vim.buffers[ buffer_number ][ line_number - 1 ] )
    # +2 includes the start columnand accounts for properties at the end of line
    # covering \n as well.
    length = current_line_len - start[ 'column_num' ] + 2
    column = start[ 'column_num' ]
  elif end_line == line_number:
    length = end[ 'column_num' ] - 1
    column = 1
  else:
    # -1 switches to 0-based indexing.
    # +1 accounts for properties at the end of line covering \n as well.
    length = len( vim.buffers[ buffer_number ][ line_number - 1 ] ) + 1
    column = 1
  if diag[ 'kind' ] == 'ERROR':
    property_name = 'YcmErrorProperty'
  else:
    property_name = 'YcmWarningProperty'
  vim_props = vim.eval( f'prop_list( { line_number }, '
                        f'{{ "bufnr": { buffer_number }, '
                           f'"types": [ "{ property_name }" ] }} )' )
  return next( filter(
      lambda p: column == int( p[ 'col' ] ) and
                length == int( p[ 'length' ] ),
      vim_props ) )


def GetTextProperties( buffer_number ):
  if not VimIsNeovim():
    return [
      DiagnosticProperty(
          int( p[ 'id' ] ),
          p[ 'type' ],
          int( p[ 'lnum' ] ),
          int( p[ 'col' ] ),
          int( p[ 'length' ] ) )
      for p in vim.eval(
          f'prop_list( 1, '
                       f'{{ "bufnr": { buffer_number }, '
                           '"end_lnum": -1, '
                           '"types": [ "YcmErrorProperty", '
                                      '"YcmWarningProperty" ] } )' ) ]
  else:
    ext_marks = vim.eval(
      f'nvim_buf_get_extmarks( { buffer_number }, '
                             f'{ YCM_NEOVIM_NS_ID }, '
                              '0, '
                              '-1, '
                              '{ "details": 1 } )' )
    return [ DiagnosticProperty(
               int( id ),
               extra_args[ 'hl_group' ],
               int( line ) + 1, # Neovim uses 0-based lines and columns
               int( column ) + 1,
               int( extra_args[ 'end_col' ] ) - int( column ) )
             for id, line, column, extra_args in ext_marks ]


def AddTextProperty( buffer_number,
                     line,
                     column,
                     prop_type,
                     extra_args ):
  if not VimIsNeovim():
    extra_args.update( {
      'type': prop_type,
      'bufnr': buffer_number
    } )
    return GetIntValue( f'prop_add( { line }, '
                                  f'{ column }, '
                                  f'{ json.dumps( extra_args ) } )' )
  else:
    extra_args[ 'hl_group' ] = prop_type
    # Neovim uses 0-based offsets
    if 'end_lnum' in extra_args:
      extra_args[ 'end_line' ] = extra_args.pop( 'end_lnum' ) - 1
    if 'end_col' in extra_args:
      extra_args[ 'end_col' ] = extra_args.pop( 'end_col' ) - 1
    line -= 1
    column -= 1
    return GetIntValue( f'nvim_buf_set_extmark( { buffer_number }, '
                                              f'{ YCM_NEOVIM_NS_ID }, '
                                              f'{ line }, '
                                              f'{ column }, '
                                              f'{ extra_args } )' )


def RemoveDiagnosticProperty( buffer_number: int, prop: DiagnosticProperty ):
  RemoveTextProperty( buffer_number,
                      prop.line,
                      prop.id,
                      prop.type )


def RemoveTextProperty( buffer_number, line_num, prop_id, prop_type ):
  if not VimIsNeovim():
    p = {
      'bufnr': buffer_number,
      'id': prop_id,
      'type': prop_type,
      'both': 1,
      'all': 1
    }
    vim.eval( f'prop_remove( { p }, { line_num } )' )
  else:
    vim.eval( f'nvim_buf_del_extmark( { buffer_number }, '
                                    f'{ YCM_NEOVIM_NS_ID }, '
                                    f'{ prop_id } )' )


# Clamps the line and column numbers so that they are not past the contents of
# the buffer. Numbers are 1-based byte offsets.
def LineAndColumnNumbersClamped( bufnr, line_num, column_num ):
  vim_buffer = vim.buffers[ bufnr ]
  line_num = max( min( line_num, len( vim_buffer ) ), 1 )
  # Vim buffers are lists Unicode objects on Python 3.
  max_column = len( ToBytes( vim_buffer[ line_num - 1 ] ) ) + 1

  return line_num, max( min( column_num, max_column ), 1 )


def SetLocationList( diagnostics ):
  """Set the location list for the current window to the supplied diagnostics"""
  SetLocationListForWindow( vim.current.window, diagnostics )


def GetWindowsForBufferNumber( buffer_number ):
  """Return the list of windows containing the buffer with number
  |buffer_number| for the current tab page."""
  return [ window for window in vim.windows
           if window.buffer.number == buffer_number ]


def SetLocationListsForBuffer( buffer_number,
                               diagnostics,
                               open_on_edit = False ):
  """Populate location lists for all windows containing the buffer with number
  |buffer_number|. See SetLocationListForWindow for format of diagnostics."""
  for window in GetWindowsForBufferNumber( buffer_number ):
    SetLocationListForWindow( window, diagnostics, open_on_edit )


def SetLocationListForWindow( window,
                              diagnostics,
                              open_on_edit = False ):
  window_id = WinIDForWindow( window )
  """Populate the location list with diagnostics. Diagnostics should be in
  qflist format; see ":h setqflist" for details."""
  ycm_loc_id = window.vars.get( 'ycm_loc_id' )
  # User may have made a bunch of `:lgrep` calls and we do not own the
  # location list with the ID we remember any more.
  if ( ycm_loc_id is not None and
       vim.eval( f'getloclist( { window_id }, '
                               f'{{ "id": { ycm_loc_id }, '
                                '"title": 0 } ).title' ) == 'ycm_loc' ):
    ycm_loc_id = None

  if ycm_loc_id is None:
    # Create new and populate
    vim.eval( f'setloclist( { window_id }, '
                           '[], '
                           '" ", '
                           '{ "title": "ycm_loc", '
                            f'"items": { json.dumps( diagnostics ) } }} )' )
    window.vars[ 'ycm_loc_id' ] = GetIntValue(
        f'getloclist( { window_id }, {{ "nr": "$", "id": 0 }} ).id' )
  elif open_on_edit:
    # Remove old and create new list
    vim.eval( f'setloclist( { window_id }, '
                           '[], '
                           '"r", '
                          f'{{ "id": { ycm_loc_id }, '
                              '"items": [], "title": "" } )' )
    vim.eval( f'setloclist( { window_id }, '
                           '[], '
                           '" ", '
                           '{ "title": "ycm_loc", '
                            f'"items": { json.dumps( diagnostics ) } }} )' )
    window.vars[ 'ycm_loc_id' ] = GetIntValue(
        f'getloclist( { window_id }, {{ "nr": "$", "id": 0 }} ).id' )
  else:
    # Just populate the old one
    vim.eval( f'setloclist( { window_id }, '
                           '[], '
                           '"r", '
                          f'{{ "id": { ycm_loc_id }, '
                             f'"items": { json.dumps( diagnostics ) } }} )' )


def OpenLocationList( focus = False, autoclose = False ):
  """Open the location list to the bottom of the current window with its
  height automatically set to fit all entries. This behavior can be overridden
  by using the YcmLocationOpened autocommand. When focus is set to True, the
  location list window becomes the active window. When autoclose is set to True,
  the location list window is automatically closed after an entry is
  selected."""
  vim.command( 'lopen' )

  SetFittingHeightForCurrentWindow()

  if autoclose:
    AutoCloseOnCurrentBuffer( 'ycmlocation' )

  if VariableExists( '#User#YcmLocationOpened' ):
    vim.command( 'doautocmd User YcmLocationOpened' )

  if not focus:
    JumpToPreviousWindow()


def SetQuickFixList( quickfix_list ):
  """Populate the quickfix list and open it. List should be in qflist format:
  see ":h setqflist" for details."""
  vim.eval( f'setqflist( { json.dumps( quickfix_list ) } )' )


def OpenQuickFixList( focus = False, autoclose = False ):
  """Open the quickfix list to full width at the bottom of the screen with its
  height automatically set to fit all entries. This behavior can be overridden
  by using the YcmQuickFixOpened autocommand.
  See the OpenLocationList function for the focus and autoclose options."""
  vim.command( 'botright copen' )

  SetFittingHeightForCurrentWindow()

  if autoclose:
    AutoCloseOnCurrentBuffer( 'ycmquickfix' )

  if VariableExists( '#User#YcmQuickFixOpened' ):
    vim.command( 'doautocmd User YcmQuickFixOpened' )

  if not focus:
    JumpToPreviousWindow()


def ComputeFittingHeightForCurrentWindow():
  current_window = vim.current.window
  if not current_window.options[ 'wrap' ]:
    return len( vim.current.buffer )

  window_width = current_window.width
  fitting_height = 0
  for line in vim.current.buffer:
    fitting_height += len( line ) // window_width + 1
  return fitting_height


def SetFittingHeightForCurrentWindow():
  if int( vim.current.buffer.vars.get( 'ycm_no_resize', 0 ) ):
    return

  vim.command( f'{ ComputeFittingHeightForCurrentWindow() }wincmd _' )


def ConvertDiagnosticsToQfList( diagnostics ):
  def ConvertDiagnosticToQfFormat( diagnostic ):
    # See :h getqflist for a description of the dictionary fields.
    # Note that, as usual, Vim is completely inconsistent about whether
    # line/column numbers are 1 or 0 based in its various APIs. Here, it wants
    # them to be 1-based. The documentation states quite clearly that it
    # expects a byte offset, by which it means "1-based column number" as
    # described in :h getqflist ("the first column is 1").
    location = diagnostic[ 'location' ]
    line_num = location[ 'line_num' ]

    # libclang can give us diagnostics that point "outside" the file; Vim borks
    # on these.
    if line_num < 1:
      line_num = 1

    text = diagnostic[ 'text' ]
    if diagnostic.get( 'fixit_available', False ):
      text += ' (FixIt available)'

    return {
      'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ],
                                            create_buffer_if_needed = True ),
      'lnum'  : line_num,
      'col'   : location[ 'column_num' ],
      'text'  : text,
      'type'  : diagnostic[ 'kind' ][ 0 ],
      'valid' : 1
    }

  return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]


def GetVimGlobalsKeys():
  return vim.eval( 'keys( g: )' )


def VimExpressionToPythonType( vim_expression ):
  """Returns a Python type from the return value of the supplied Vim expression.
  If the expression returns a list, dict or other non-string type, then it is
  returned unmodified. If the string return can be converted to an
  integer, returns an integer, otherwise returns the result converted to a
  Unicode string."""

  result = vim.eval( vim_expression )
  if not ( isinstance( result, str ) or isinstance( result, bytes ) ):
    return result

  try:
    return int( result )
  except ValueError:
    return ToUnicode( result )


def HiddenEnabled( buffer_object ):
  if buffer_object.options[ 'bh' ] == "hide":
    return True
  return GetBoolValue( '&hidden' )


def BufferIsUsable( buffer_object ):
  return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )


def EscapeFilepathForVimCommand( filepath ):
  return GetVariableValue( f"fnameescape('{ EscapeForVim( filepath ) }')" )


def ComparePaths( path1, path2 ):
  # Assume that the file system is case-insensitive on Windows and macOS and
  # case-sensitive on other platforms. While this is not necessarily true, being
  # completely correct here is not worth the trouble as this assumption
  # represents the overwhelming use case and detecting the case sensitivity of a
  # file system is tricky.
  if OnWindows() or OnMac():
    return path1.lower() == path2.lower()
  return path1 == path2


# Both |line| and |column| need to be 1-based
def TryJumpLocationInTab( tab, filename, line, column ):
  for win in tab.windows:
    if ComparePaths( GetBufferFilepath( win.buffer ), filename ):
      vim.current.tabpage = tab
      vim.current.window = win
      if line is not None and column is not None:
        vim.current.window.cursor = ( line, column - 1 )
        # Open possible folding at location
        vim.command( 'normal! zv' )
        # Center the screen on the jumped-to location
        vim.command( 'normal! zz' )

      return True
  # 'filename' is not opened in this tab page
  return False


# Both |line| and |column| need to be 1-based
def TryJumpLocationInTabs( filename, line, column ):
  for tab in vim.tabpages:
    if TryJumpLocationInTab( tab, filename, line, column ):
      return True
  # 'filename' is not opened in any tab pages
  return False


# Maps User command to vim command
def GetVimCommand( user_command, default = 'edit' ):
  vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
  if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
    vim_command = 'split'
  return vim_command


def JumpToFile( filename, command, modifiers ):
  vim_command = GetVimCommand( command )
  try:
    escaped_filename = EscapeFilepathForVimCommand( filename )
    vim.command(
        f'keepjumps { modifiers } { vim_command } { escaped_filename }' )
  # When the file we are trying to jump to has a swap file
  # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  # or KeyboardInterrupt after user selects one of the options.
  except vim.error as e:
    if 'E325' not in str( e ):
      raise
    # Do nothing if the target file is still not opened (user chose (Q)uit).
    if filename != GetCurrentBufferFilepath():
      return False
  # Thrown when user chooses (A)bort in .swp message box.
  except KeyboardInterrupt:
    return False
  return True


# Both |line| and |column| need to be 1-based
def JumpToLocation( filename, line, column, modifiers, command ):
  # Add an entry to the jumplist
  vim.command( "normal! m'" )

  if filename != GetCurrentBufferFilepath():
    # We prefix the command with 'keepjumps' so that opening the file is not
    # recorded in the jumplist. So when we open the file and move the cursor to
    # a location in it, the user can use CTRL-O to jump back to the original
    # location, not to the start of the newly opened file.
    # Sadly this fails on random occasions and the undesired jump remains in the
    # jumplist.
    if command == 'split-or-existing-window':
      if 'tab' in modifiers:
        if TryJumpLocationInTabs( filename, line, column ):
          return
      elif TryJumpLocationInTab( vim.current.tabpage, filename, line, column ):
        return
      command = 'split'

    # This command is kept for backward compatibility. :tab should be used with
    # the 'split-or-existing-window' command instead.
    if command == 'new-or-existing-tab':
      if TryJumpLocationInTabs( filename, line, column ):
        return
      command = 'new-tab'

    if not JumpToFile( filename, command, modifiers ):
      return

  if line is not None and column is not None:
    vim.current.window.cursor = ( line, column - 1 )

    # Open possible folding at location
    vim.command( 'normal! zv' )
    # Center the screen on the jumped-to location
    vim.command( 'normal! zz' )


def NumLinesInBuffer( buffer_object ):
  # This is actually less than obvious, that's why it's wrapped in a function
  return len( buffer_object )


# Calling this function from the non-GUI thread will sometimes crash Vim. At
# the time of writing, YCM only uses the GUI thread inside Vim (this used to
# not be the case).
def PostVimMessage( message, warning = True, truncate = False ):
  """Display a message on the Vim status line. By default, the message is
  highlighted and logged to Vim command-line history (see :h history).
  Unset the |warning| parameter to disable this behavior. Set the |truncate|
  parameter to avoid hit-enter prompts (see :h hit-enter) when the message is
  longer than the window width."""
  echo_command = 'echom' if warning else 'echo'

  # Displaying a new message while previous ones are still on the status line
  # might lead to a hit-enter prompt or the message appearing without a
  # newline so we do a redraw first.
  vim.command( 'redraw' )

  if warning:
    vim.command( 'echohl WarningMsg' )

  message = ToUnicode( message )

  if truncate:
    vim_width = GetIntValue( '&columns' )

    message = message.replace( '\n', ' ' )
    message = message.replace( '\t', ' ' )
    if len( message ) >= vim_width:
      message = message[ : vim_width - 4 ] + '...'

    old_ruler = GetIntValue( '&ruler' )
    old_showcmd = GetIntValue( '&showcmd' )
    vim.command( 'set noruler noshowcmd' )

    vim.command( f"{ echo_command } '{ EscapeForVim( message ) }'" )

    SetVariableValue( '&ruler', old_ruler )
    SetVariableValue( '&showcmd', old_showcmd )
  else:
    for line in message.split( '\n' ):
      vim.command( f"{ echo_command } '{ EscapeForVim( line ) }'" )

  if warning:
    vim.command( 'echohl None' )


def PresentDialog( message, choices, default_choice_index = 0 ):
  """Presents the user with a dialog where a choice can be made.
  This will be a dialog for gvim users or a question in the message buffer
  for vim users or if `set guioptions+=c` was used.

  choices is list of alternatives.
  default_choice_index is the 0-based index of the default element
  that will get choosen if the user hits <CR>. Use -1 for no default.

  PresentDialog will return a 0-based index into the list
  or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.

  If you are presenting a list of options for the user to choose from, such as
  a list of imports, or lines to insert (etc.), SelectFromList is a better
  option.

  See also:
    :help confirm() in vim (Note that vim uses 1-based indexes)

  Example call:
    PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
      Is this a nice example?
      [Y]es, (N)o, May(b)e:"""
  message = EscapeForVim( ToUnicode( message ) )
  choices = EscapeForVim( ToUnicode( '\n'.join( choices ) ) )
  to_eval = ( f"confirm( '{ message }', "
                       f"'{ choices }', "
                       f"{ default_choice_index + 1 } )" )
  try:
    return GetIntValue( to_eval ) - 1
  except KeyboardInterrupt:
    return -1


def Confirm( message ):
  """Display |message| with Ok/Cancel operations. Returns True if the user
  selects Ok"""
  return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )


def SelectFromList( prompt, items ):
  """Ask the user to select an item from the list |items|.

  Presents the user with |prompt| followed by a numbered list of |items|,
  from which they select one. The user is asked to enter the number of an
  item or click it.

  |items| should not contain leading ordinals: they are added automatically.

  Returns the 0-based index in the list |items| that the user selected, or an
  exception if no valid item was selected.

  See also :help inputlist()."""

  vim_items = [ prompt ]
  vim_items.extend( [ f"{ i + 1 }: { item }"
                      for i, item in enumerate( items ) ] )

  # The vim documentation warns not to present lists larger than the number of
  # lines of display. This is sound advice, but there really isn't any sensible
  # thing we can do in that scenario. Testing shows that Vim just pages the
  # message; that behaviour is as good as any, so we don't manipulate the list,
  # or attempt to page it.

  # For an explanation of the purpose of inputsave() / inputrestore(),
  # see :help input(). Briefly, it makes inputlist() work as part of a mapping.
  vim.eval( 'inputsave()' )
  try:
    # Vim returns the number the user entered, or the line number the user
    # clicked. This may be wildly out of range for our list. It might even be
    # negative.
    #
    # The first item is index 0, and this maps to our "prompt", so we subtract 1
    # from the result and return that, assuming it is within the range of the
    # supplied list. If not, we return negative.
    #
    # See :help input() for explanation of the use of inputsave() and inpput
    # restore(). It is done in try/finally in case vim.eval ever throws an
    # exception (such as KeyboardInterrupt)
    selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1
  except KeyboardInterrupt:
    selected = -1
  finally:
    vim.eval( 'inputrestore()' )

  if selected < 0 or selected >= len( items ):
    # User selected something outside of the range
    raise RuntimeError( NO_SELECTION_MADE_MSG )

  return selected


def EscapeForVim( text ):
  return ToUnicode( text.replace( "'", "''" ) )


def AllOpenedFiletypes():
  """Returns a dict mapping filetype to list of buffer numbers for all open
  buffers"""
  filetypes = defaultdict( list )
  for buffer in vim.buffers:
    for filetype in FiletypesForBuffer( buffer ):
      filetypes[ filetype ].append( buffer.number )
  return filetypes


def CurrentFiletypes():
  filetypes = vim.eval( "&filetype" )
  if not filetypes:
    filetypes = 'ycm_nofiletype'
  return ToUnicode( filetypes ).split( '.' )


def CurrentFiletypesEnabled( disabled_filetypes ):
  """Return False if one of the current filetypes is disabled, True otherwise.
  |disabled_filetypes| must be a dictionary where keys are the disabled
  filetypes and values are unimportant. The special key '*' matches all
  filetypes."""
  return ( '*' not in disabled_filetypes and
           not any( x in disabled_filetypes for x in CurrentFiletypes() ) )


def GetBufferFiletypes( bufnr ):
  command = f'getbufvar({ bufnr }, "&ft")'
  filetypes = vim.eval( command )
  if not filetypes:
    filetypes = 'ycm_nofiletype'
  return ToUnicode( filetypes ).split( '.' )


def FiletypesForBuffer( buffer_object ):
  # NOTE: Getting &ft for other buffers only works when the buffer has been
  # visited by the user at least once, which is true for modified buffers

  # We don't use
  #
  #   buffer_object.options[ 'ft' ]
  #
  # to get the filetypes because this causes annoying flickering when the buffer
  # is hidden.
  return GetBufferFiletypes( buffer_object.number )


def VariableExists( variable ):
  return GetBoolValue( f"exists( '{ EscapeForVim( variable ) }' )" )


def SetVariableValue( variable, value ):
  vim.command( f"let { variable } = { json.dumps( value ) }" )


def GetVariableValue( variable ):
  return vim.eval( variable )


def GetBoolValue( variable ):
  return bool( int( vim.eval( variable ) ) )


def GetIntValue( variable ):
  return int( vim.eval( variable ) or 0 )


def _SortChunksByFile( chunks ):
  """Sort the members of the list |chunks| (which must be a list of dictionaries
  conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new
  list in arbitrary order."""

  chunks_by_file = defaultdict( list )

  for chunk in chunks:
    filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ]
    chunks_by_file[ filepath ].append( chunk )

  return chunks_by_file


def _GetNumNonVisibleFiles( file_list ):
  """Returns the number of file in the iterable list of files |file_list| which
  are not curerntly open in visible windows"""
  return len(
      [ f for f in file_list
        if not BufferIsVisible( GetBufferNumberForFilename( f ) ) ] )


def _OpenFileInSplitIfNeeded( filepath ):
  """Ensure that the supplied filepath is open in a visible window, opening a
  new split if required. Returns the buffer number of the file and an indication
  of whether or not a new split was opened.

  If the supplied filename is already open in a visible window, return just
  return its buffer number. If the supplied file is not visible in a window
  in the current tab, opens it in a new vertical split.

  Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer
  number and whether or not this method created a new split. If the user opts
  not to open a file, or if opening fails, this method raises RuntimeError,
  otherwise, guarantees to return a visible buffer number in buffer_num."""

  buffer_num = GetBufferNumberForFilename( filepath )

  # We only apply changes in the current tab page (i.e. "visible" windows).
  # Applying changes in tabs does not lead to a better user experience, as the
  # quickfix list no longer works as you might expect (doesn't jump into other
  # tabs), and the complexity of choosing where to apply edits is significant.
  if BufferIsVisible( buffer_num ):
    # file is already open and visible, just return that buffer number (and an
    # idicator that we *didn't* open a split)
    return ( buffer_num, False )

  # The file is not open in a visible window, so we open it in a split.
  # We open the file with a small, fixed height. This means that we don't
  # make the current buffer the smallest after a series of splits.
  OpenFilename( filepath, {
    'focus': True,
    'fix': True,
    'size': GetIntValue( '&previewheight' ),
  } )

  # OpenFilename returns us to the original cursor location. This is what we
  # want, because we don't want to disorientate the user, but we do need to
  # know the (now open) buffer number for the filename
  buffer_num = GetBufferNumberForFilename( filepath )
  if not BufferIsVisible( buffer_num ):
    # This happens, for example, if there is a swap file and the user
    # selects the "Quit" or "Abort" options. We just raise an exception to
    # make it clear to the user that the abort has left potentially
    # partially-applied changes.
    raise RuntimeError(
        f'Unable to open file: { filepath }\nFixIt/Refactor operation '
        'aborted prior to completion. Your files have not been '
        'fully updated. Please use undo commands to revert the '
        'applied changes.' )

  # We opened this file in a split
  return ( buffer_num, True )


def ReplaceChunks( chunks, silent=False ):
  """Apply the source file deltas supplied in |chunks| to arbitrary files.
  |chunks| is a list of changes defined by ycmd.responses.FixItChunk,
  which may apply arbitrary modifications to arbitrary files.

  If a file specified in a particular chunk is not currently open in a visible
  buffer (i.e., one in a window visible in the current tab), we:
    - issue a warning to the user that we're going to open new files (and offer
      her the option to abort cleanly)
    - open the file in a new split, make the changes, then hide the buffer.

  If for some reason a file could not be opened or changed, raises RuntimeError.
  Otherwise, returns no meaningful value."""

  # We apply the edits file-wise for efficiency.
  chunks_by_file = _SortChunksByFile( chunks )

  # We sort the file list simply to enable repeatable testing.
  sorted_file_list = sorted( chunks_by_file.keys() )

  if not silent:
    # Make sure the user is prepared to have her screen mutilated by the new
    # buffers.
    num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list )

    if num_files_to_open > 0:
      if not Confirm(
            FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ):
        return

  # Store the list of locations where we applied changes. We use this to display
  # the quickfix window showing the user where we applied changes.
  locations = []

  for filepath in sorted_file_list:
    buffer_num, close_window = _OpenFileInSplitIfNeeded( filepath )

    locations.extend( ReplaceChunksInBuffer( chunks_by_file[ filepath ],
                                             vim.buffers[ buffer_num ] ) )

    # When opening tons of files, we don't want to have a split for each new
    # file, as this simply does not scale, so we open the window, make the
    # edits, then hide the window.
    if close_window:
      # Some plugins (I'm looking at you, syntastic) might open a location list
      # for the window we just opened. We don't want that location list hanging
      # around, so we close it. lclose is a no-op if there is no location list.
      vim.command( 'lclose' )

      # Note that this doesn't lose our changes. It simply "hides" the buffer,
      # which can later be re-accessed via the quickfix list or `:ls`
      vim.command( 'hide' )

  # Open the quickfix list, populated with entries for each location we changed.
  if not silent:
    if locations:
      SetQuickFixList( locations )

    PostVimMessage( f'Applied { len( chunks ) } changes', warning = False )


def ReplaceChunksInBuffer( chunks, vim_buffer ):
  """Apply changes in |chunks| to the buffer-like object |buffer| and return the
  locations for that buffer."""

  # We apply the chunks from the bottom to the top of the buffer so that we
  # don't need to adjust the position of the remaining chunks due to text
  # changes. This assumes that chunks are not overlapping. However, we still
  # allow multiple chunks to share the same starting position (because of the
  # language server protocol specs). These chunks must be applied in their order
  # of appareance. Since Python sorting is stable, if we sort the whole list in
  # reverse order of location, these chunks will be reversed. Therefore, we
  # need to fully reverse the list then sort it on the starting position in
  # reverse order.
  chunks.reverse()
  chunks.sort( key = lambda chunk: (
    chunk[ 'range' ][ 'start' ][ 'line_num' ],
    chunk[ 'range' ][ 'start' ][ 'column_num' ]
  ), reverse = True )

  # However, we still want to display the locations from the top of the buffer
  # to its bottom.
  return reversed( [ ReplaceChunk( chunk[ 'range' ][ 'start' ],
                                   chunk[ 'range' ][ 'end' ],
                                   chunk[ 'replacement_text' ],
                                   vim_buffer )
                     for chunk in chunks ] )


def SplitLines( contents ):
  """Return a list of each of the lines in the byte string |contents|.
  Behavior is equivalent to str.splitlines with the following exceptions:
   - empty strings are returned as [ '' ];
   - a trailing newline is not ignored (i.e. SplitLines( '\n' )
     returns [ '', '' ], not [ '' ] )."""
  if contents == b'':
    return [ b'' ]

  lines = contents.splitlines()

  if contents.endswith( b'\r' ) or contents.endswith( b'\n' ):
    lines.append( b'' )

  return lines


# Replace the chunk of text specified by a contiguous range with the supplied
# text and return the location.
# * start and end are objects with line_num and column_num properties
# * the range is inclusive
# * indices are all 1-based
#
# NOTE: Works exclusively with bytes() instances and byte offsets as returned
# by ycmd and used within the Vim buffers
def ReplaceChunk( start, end, replacement_text, vim_buffer ):
  # ycmd's results are all 1-based, but vim's/python's are all 0-based
  # (so we do -1 on all of the values)
  start_line = start[ 'line_num' ] - 1
  end_line = end[ 'line_num' ] - 1

  start_column = start[ 'column_num' ] - 1
  end_column = end[ 'column_num' ] - 1

  # When sending a request to the server, a newline is added to the buffer
  # contents to match what gets saved to disk. If the server generates a chunk
  # containing that newline, this chunk goes past the Vim buffer contents since
  # there is actually no new line. When this happens, recompute the end position
  # of where the chunk is applied and remove all trailing characters in the
  # chunk.
  if end_line >= len( vim_buffer ):
    end_column = len( ToBytes( vim_buffer[ -1 ] ) )
    end_line = len( vim_buffer ) - 1
    replacement_text = replacement_text.rstrip()

  # NOTE: replacement_text is unicode, but all our offsets are byte offsets,
  # so we convert to bytes
  replacement_lines = SplitLines( ToBytes( replacement_text ) )

  # NOTE: Vim buffers are a list of unicode objects on Python 3.
  start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ]
  end_line_text = ToBytes( vim_buffer[ end_line ] )
  end_existing_text = end_line_text[ end_column : ]

  replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
  replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text

  cursor_line, cursor_column = CurrentLineAndColumn()

  vim_buffer[ start_line : end_line + 1 ] = replacement_lines[ : ]

  # When the cursor position is on the last line in the replaced area, and ends
  # up somewhere after the end of the new text, we need to reset the cursor
  # position. This is because Vim doesn't know where to put it, and guesses
  # badly. We put it at the end of the new text.
  if cursor_line == end_line and cursor_column >= end_column:
    cursor_line = start_line + len( replacement_lines ) - 1
    cursor_column += len( replacement_lines[ - 1 ] ) - len( end_line_text )
    SetCurrentLineAndColumn( cursor_line, cursor_column )

  return {
    'bufnr': vim_buffer.number,
    'filename': vim_buffer.name,
    # line and column numbers are 1-based in qflist
    'lnum': start_line + 1,
    'col': start_column + 1,
    'text': replacement_text,
    'type': 'F',
  }


def InsertNamespace( namespace ):
  if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
    expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
    if expr:
      SetVariableValue( "g:ycm_namespace_to_insert", namespace )
      vim.eval( expr )
      return

  pattern = r'^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
  existing_indent = ''
  line = SearchInCurrentBuffer( pattern )
  if line:
    existing_line = LineTextInCurrentBuffer( line )
    existing_indent = re.sub( r'\S.*', '', existing_line )
  new_line = f'{ existing_indent }using { namespace };\n'
  replace_pos = { 'line_num': line + 1, 'column_num': 1 }
  ReplaceChunk( replace_pos, replace_pos, new_line, vim.current.buffer )
  PostVimMessage( f'Add namespace: { namespace }', warning = False )


def SearchInCurrentBuffer( pattern ):
  """ Returns the 1-indexed line on which the pattern matches
  (going UP from the current position) or 0 if not found """
  return GetIntValue( f"search('{ EscapeForVim( pattern ) }', 'Wcnb')" )


def LineTextInCurrentBuffer( line_number ):
  """ Returns the text on the 1-indexed line (NOT 0-indexed) """
  return vim.current.buffer[ line_number - 1 ]


def ClosePreviewWindow():
  """ Close the preview window if it is present, otherwise do nothing """
  vim.command( 'silent! pclose!' )


def JumpToPreviewWindow():
  """ Jump the vim cursor to the preview window, which must be active. Returns
  boolean indicating if the cursor ended up in the preview window """
  vim.command( 'silent! wincmd P' )
  return vim.current.window.options[ 'previewwindow' ]


def JumpToPreviousWindow():
  """ Jump the vim cursor to its previous window position """
  vim.command( 'silent! wincmd p' )


def JumpToTab( tab_number ):
  """Jump to Vim tab with corresponding number """
  vim.command( f'silent! tabn { tab_number }' )


def OpenFileInPreviewWindow( filename, modifiers ):
  """ Open the supplied filename in the preview window """
  if modifiers:
    modifiers = ' ' + modifiers
  vim.command( f'silent!{ modifiers } pedit! { filename }' )


def WriteToPreviewWindow( message, modifiers ):
  """ Display the supplied message in the preview window """

  # This isn't something that comes naturally to Vim. Vim only wants to show
  # tags and/or actual files in the preview window, so we have to hack it a
  # little bit. We generate a temporary file name and "open" that, then write
  # the data to it. We make sure the buffer can't be edited or saved. Other
  # approaches include simply opening a split, but we want to take advantage of
  # the existing Vim options for preview window height, etc.

  ClosePreviewWindow()

  OpenFileInPreviewWindow( vim.eval( 'tempname()' ), modifiers )

  if JumpToPreviewWindow():
    # We actually got to the preview window. By default the preview window can't
    # be changed, so we make it writable, write to it, then make it read only
    # again.
    vim.current.buffer.options[ 'modifiable' ] = True
    vim.current.buffer.options[ 'readonly' ]   = False

    vim.current.buffer[ : ] = message.splitlines()

    vim.current.buffer.options[ 'buftype' ]    = 'nofile'
    vim.current.buffer.options[ 'bufhidden' ]  = 'wipe'
    vim.current.buffer.options[ 'buflisted' ]  = False
    vim.current.buffer.options[ 'swapfile' ]   = False
    vim.current.buffer.options[ 'modifiable' ] = False
    vim.current.buffer.options[ 'readonly' ]   = True

    # We need to prevent closing the window causing a warning about unsaved
    # file, so we pretend to Vim that the buffer has not been changed.
    vim.current.buffer.options[ 'modified' ]   = False

    JumpToPreviousWindow()
  else:
    # We couldn't get to the preview window, but we still want to give the user
    # the information we have. The only remaining option is to echo to the
    # status area.
    PostVimMessage( message, warning = False )


def BufferIsVisibleForFilename( filename ):
  """Check if a buffer exists for a specific file."""
  buffer_number = GetBufferNumberForFilename( filename )
  return BufferIsVisible( buffer_number )


def CloseBuffersForFilename( filename ):
  """Close all buffers for a specific file."""
  buffer_number = GetBufferNumberForFilename( filename )
  while buffer_number != -1:
    vim.command( f'silent! bwipeout! { buffer_number }' )
    new_buffer_number = GetBufferNumberForFilename( filename )
    if buffer_number == new_buffer_number:
      raise RuntimeError( f"Buffer { buffer_number } for filename "
                          f"'{ filename }' should already be wiped out." )
    buffer_number = new_buffer_number


def OpenFilename( filename, options = {} ):
  """Open a file in Vim. Following options are available:
  - command: specify which Vim command is used to open the file. Choices
  are same-buffer, horizontal-split, vertical-split, and new-tab (default:
  horizontal-split);
  - size: set the height of the window for a horizontal split or the width for
  a vertical one (default: '');
  - fix: set the winfixheight option for a horizontal split or winfixwidth for
  a vertical one (default: False). See :h winfix for details;
  - focus: focus the opened file (default: False);
  - watch: automatically watch for changes (default: False). This is useful
  for logs;
  - position: set the position where the file is opened (default: start).
  Choices are 'start' and 'end'.
  - mods: The vim <mods> for the command, such as :vertical"""

  # Set the options.
  command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
                           'horizontal-split' )
  size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
           '' )
  focus = options.get( 'focus', False )

  # There is no command in Vim to return to the previous tab so we need to
  # remember the current tab if needed.
  if not focus and command == 'tabedit':
    previous_tab = GetIntValue( 'tabpagenr()' )
  else:
    previous_tab = None

  # Open the file.
  try:
    vim.command( f'{ options.get( "mods", "" ) }'
                 f'{ size }'
                 f'{ command } '
                 f'{ filename }' )
  # When the file we are trying to jump to has a swap file,
  # Vim opens swap-exists-choices dialog and throws vim.error with E325 error,
  # or KeyboardInterrupt after user selects one of the options which actually
  # opens the file (Open read-only/Edit anyway).
  except vim.error as e:
    if 'E325' not in str( e ):
      raise

    # Otherwise, the user might have chosen Quit. This is detectable by the
    # current file not being the target file
    if filename != GetCurrentBufferFilepath():
      return
  except KeyboardInterrupt:
    # Raised when the user selects "Abort" after swap-exists-choices
    return

  _SetUpLoadedBuffer( command,
                      filename,
                      options.get( 'fix', False ),
                      options.get( 'position', 'start' ),
                      options.get( 'watch', False ) )

  # Vim automatically set the focus to the opened file so we need to get the
  # focus back (if the focus option is disabled) when opening a new tab or
  # window.
  if not focus:
    if command == 'tabedit':
      JumpToTab( previous_tab )
    if command in [ 'split', 'vsplit' ]:
      JumpToPreviousWindow()


def _SetUpLoadedBuffer( command, filename, fix, position, watch ):
  """After opening a buffer, configure it according to the supplied options,
  which are as defined by the OpenFilename method."""

  if command == 'split':
    vim.current.window.options[ 'winfixheight' ] = fix
  if command == 'vsplit':
    vim.current.window.options[ 'winfixwidth' ] = fix

  if watch:
    vim.current.buffer.options[ 'autoread' ] = True
    vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
                 .format( filename ) )

  if position == 'end':
    vim.command( 'silent! normal! Gzz' )


def BuildRange( start_line, end_line ):
  # Vim only returns the starting and ending lines of the range of a command.
  # Check if those lines correspond to a previous visual selection and if they
  # do, use the columns of that selection to build the range.
  start = vim.current.buffer.mark( '<' )
  end = vim.current.buffer.mark( '>' )
  if not start or not end or start_line != start[ 0 ] or end_line != end[ 0 ]:
    start = [ start_line, 0 ]
    end = [ end_line, len( vim.current.buffer[ end_line - 1 ] ) ]
  # Vim Python API returns 1-based lines and 0-based columns while ycmd expects
  # 1-based lines and columns.
  return {
    'range': {
      'start': {
        'line_num': start[ 0 ],
        'column_num': start[ 1 ] + 1
      },
      'end': {
        'line_num': end[ 0 ],
        # Vim returns the maximum 32-bit integer value when a whole line is
        # selected. Use the end of line instead.
        'column_num': min( end[ 1 ],
                           len( vim.current.buffer[ end[ 0 ] - 1 ] ) ) + 1
      }
    }
  }


# Expects version_string in 'MAJOR.MINOR.PATCH' format, e.g. '8.1.278'
def VimVersionAtLeast( version_string ):
  major, minor, patch = ( int( x ) for x in version_string.split( '.' ) )

  # For Vim 8.1.278, v:version is '801'
  actual_major_and_minor = GetIntValue( 'v:version' )
  matching_major_and_minor = major * 100 + minor
  if actual_major_and_minor != matching_major_and_minor:
    return actual_major_and_minor > matching_major_and_minor

  return GetBoolValue( f"has( 'patch{ patch }' )" )


def AutoCloseOnCurrentBuffer( name ):
  """Create an autocommand group with name |name| on the current buffer that
  automatically closes it when leaving its window."""
  vim.command( f'augroup { name }' )
  vim.command( 'autocmd! * <buffer>' )
  vim.command( 'autocmd WinLeave <buffer> '
               'if bufnr( "%" ) == expand( "<abuf>" ) | q | endif '
               f'| autocmd! { name }' )
  vim.command( 'augroup END' )


@memoize()
def VimIsNeovim():
  return GetBoolValue( 'has( "nvim" )' )


@memoize()
def VimSupportsPopupWindows():
  return VimHasFunctions( 'popup_create',
                          'popup_atcursor',
                          'popup_move',
                          'popup_hide',
                          'popup_settext',
                          'popup_show',
                          'popup_close' )


@memoize()
def VimHasFunction( func ):
  return bool( GetIntValue( f"exists( '*{ EscapeForVim( func ) }' )" ) )


def VimHasFunctions( *functions ):
  return all( VimHasFunction( f ) for f in functions )


def WinIDForWindow( window ):
  return GetIntValue( f'win_getid( { window.number }, '
                                 f'{ window.tabpage.number } )' )


def ScreenPositionForLineColumnInWindow( window, line, column ):
  return vim.eval( f'screenpos( { WinIDForWindow( window ) }, '
                              f'{ line }, '
                              f'{ column } )' )


def UsingPreviewPopup():
  return 'popup' in ToUnicode( vim.options[ 'completeopt' ] ).split( ',' )


def DisplayWidth():
  return GetIntValue( '&columns' )


def DisplayWidthOfString( s ):
  return GetIntValue( f"strdisplaywidth( '{ EscapeForVim( s ) }' )" )


def BuildQfListItem( goto_data_item ):
  qf_item = {}
  if 'filepath' in goto_data_item:
    qf_item[ 'filename' ] = ToUnicode( goto_data_item[ 'filepath' ] )
  if 'description' in goto_data_item:
    qf_item[ 'text' ] = ToUnicode( goto_data_item[ 'description' ] )
  if 'line_num' in goto_data_item:
    qf_item[ 'lnum' ] = goto_data_item[ 'line_num' ]
  if 'column_num' in goto_data_item:
    # ycmd returns columns 1-based, and QuickFix lists require "byte offsets".
    # See :help getqflist and equivalent comment in
    # vimsupport.ConvertDiagnosticsToQfList.
    #
    # When the Vim help says "byte index", it really means "1-based column
    # number" (which is somewhat confusing). :help getqflist states "first
    # column is 1".
    qf_item[ 'col' ] = goto_data_item[ 'column_num' ]

  return qf_item



File: python/ycm/paths.py

# Copyright (C) 2015-2017 YouCompleteMe contributors.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import vim
import re

# Can't import these from setup.py because it makes nosetests go crazy.
DIR_OF_CURRENT_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_YCMD = os.path.join( DIR_OF_CURRENT_SCRIPT, '..', '..', 'third_party',
                            'ycmd' )
WIN_PYTHON_PATH = os.path.join( sys.exec_prefix, 'python.exe' )
PYTHON_BINARY_REGEX = re.compile(
  r'python(3(\.[6-9])?)?(.exe)?$', re.IGNORECASE )


# Not caching the result of this function; users shouldn't have to restart Vim
# after running the install script or setting the
# `g:ycm_server_python_interpreter` option.
def PathToPythonInterpreter():
  # Not calling the Python interpreter to check its version as it significantly
  # impacts startup time.
  from ycmd import utils

  python_interpreter = vim.eval( 'g:ycm_server_python_interpreter' )
  if python_interpreter:
    python_interpreter = utils.FindExecutable( python_interpreter )
    if python_interpreter:
      return python_interpreter

    raise RuntimeError( "Path in 'g:ycm_server_python_interpreter' option "
                        "does not point to a valid Python 3.6+." )

  python_interpreter = _PathToPythonUsedDuringBuild()
  if python_interpreter and utils.GetExecutable( python_interpreter ):
    return python_interpreter

  # On UNIX platforms, we use sys.executable as the Python interpreter path.
  # We cannot use sys.executable on Windows because for unknown reasons, it
  # returns the Vim executable. Instead, we use sys.exec_prefix to deduce the
  # interpreter path.
  python_interpreter = ( WIN_PYTHON_PATH if utils.OnWindows() else
                         sys.executable )
  if _EndsWithPython( python_interpreter ):
    return python_interpreter

  python_interpreter = utils.PathToFirstExistingExecutable( [ 'python3',
                                                              'python' ] )
  if python_interpreter:
    return python_interpreter

  raise RuntimeError( "Cannot find Python 3.6+. "
                      "Set the 'g:ycm_server_python_interpreter' option "
                      "to a Python interpreter path." )


def _PathToPythonUsedDuringBuild():
  from ycmd import utils

  try:
    filepath = os.path.join( DIR_OF_YCMD, 'PYTHON_USED_DURING_BUILDING' )
    return utils.ReadFile( filepath ).strip()
  except OSError:
    return None


def _EndsWithPython( path ):
  """Check if given path ends with a python 3.6+ name."""
  return path and PYTHON_BINARY_REGEX.search( path ) is not None


def PathToServerScript():
  return os.path.join( DIR_OF_YCMD, 'ycmd' )



File: python/ycm/diagnostic_filter.py

# Copyright (C) 2016  YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import re


class DiagnosticFilter:
  def __init__( self, config_or_filters ):
    self._filters : list = config_or_filters


  def IsAllowed( self, diagnostic ):
    return not any( filterMatches( diagnostic )
                    for filterMatches in self._filters )


  @staticmethod
  def CreateFromOptions( user_options ):
    all_filters = user_options[ 'filter_diagnostics' ]
    compiled_by_type = {}
    for type_spec, filter_value in all_filters.items():
      filetypes = type_spec.split( ',' )
      for filetype in filetypes:
        compiled_by_type[ filetype ] = _CompileFilters( filter_value )

    return _MasterDiagnosticFilter( compiled_by_type )


class _MasterDiagnosticFilter:

  def __init__( self, all_filters ):
    self._all_filters = all_filters
    self._cache = {}


  def SubsetForTypes( self, filetypes ):
    # check cache
    cache_key = ','.join( filetypes )
    cached = self._cache.get( cache_key )
    if cached is not None:
      return cached

    # build a new DiagnosticFilter merging all filters
    #  for the provided filetypes
    spec = []
    for filetype in filetypes:
      type_specific = self._all_filters.get( filetype, [] )
      spec.extend( type_specific )

    new_filter = DiagnosticFilter( spec )
    self._cache[ cache_key ] = new_filter
    return new_filter


def _ListOf( config_entry ):
  if isinstance( config_entry, list ):
    return config_entry

  return [ config_entry ]


def CompileRegex( raw_regex ):
  pattern = re.compile( raw_regex, re.IGNORECASE )

  def FilterRegex( diagnostic ):
    return pattern.search( diagnostic[ 'text' ] ) is not None

  return FilterRegex


def CompileLevel( level ):
  # valid kinds are WARNING and ERROR;
  #  expected input levels are `warning` and `error`
  # NOTE: we don't validate the input...
  expected_kind = level.upper()

  def FilterLevel( diagnostic ):
    return diagnostic[ 'kind' ] == expected_kind

  return FilterLevel


FILTER_COMPILERS = { 'regex' : CompileRegex,
                     'level' : CompileLevel }


def _CompileFilters( config ):
  """Given a filter config dictionary, return a list of compiled filters"""
  filters = []

  for filter_type, filter_pattern in config.items():
    compiler = FILTER_COMPILERS.get( filter_type )

    if compiler is not None:
      for filter_config in _ListOf( filter_pattern ):
        compiledFilter = compiler( filter_config )
        filters.append( compiledFilter )

  return filters



File: python/ycm/hierarchy_tree.py

# Copyright (C) 2024 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from typing import Optional, List
from ycm import vimsupport
import os


class HierarchyNode:
  def __init__( self, data, distance : int ):
    self._references : Optional[ List[ int ] ] = None
    self._data = data
    self._distance_from_root = distance


  def ToRootLocation( self, subindex : int ):
    location = self._data.get( 'root_location' )
    if location:
      file = location[ 'filepath' ]
      line = location[ 'line_num' ]
      column = location[ 'column_num' ]
      return file, line, column
    else:
      return self.ToLocation( subindex )


  def ToLocation( self, subindex : int ):
    location = self._data[ 'locations' ][ subindex ]
    line = location[ 'line_num' ]
    column = location[ 'column_num' ]
    file = location[ 'filepath' ]
    return file, line, column


MAX_HANDLES_PER_INDEX = 1000000


def handle_to_index( handle : int ):
  return abs( handle ) // MAX_HANDLES_PER_INDEX


def handle_to_location_index( handle : int ):
  return abs( handle ) % MAX_HANDLES_PER_INDEX


def make_handle( index : int, location_index : int ):
  return index * MAX_HANDLES_PER_INDEX + location_index


class HierarchyTree:
  def __init__( self ):
    self._up_nodes : List[ HierarchyNode ] = []
    self._down_nodes : List[ HierarchyNode ] = []
    self._kind : str = ''

  def SetRootNode( self, items, kind : str ):
    if items:
      assert len( items ) == 1
      self._root_node_indices = [ 0 ]
      self._down_nodes.append( HierarchyNode( items[ 0 ], 0 ) )
      self._up_nodes.append( HierarchyNode( items[ 0 ], 0 ) )
      self._kind = kind
      return self.HierarchyToLines()
    return []


  def UpdateHierarchy( self, handle : int, items, direction : str ):
    current_index = handle_to_index( handle )
    nodes = self._down_nodes if direction == 'down' else self._up_nodes
    if items:
      nodes.extend( [
        HierarchyNode( item,
                       nodes[ current_index ]._distance_from_root + 1 )
        for item in items ] )
      nodes[ current_index ]._references = list(
          range( len( nodes ) - len( items ), len( nodes ) ) )
    else:
      nodes[ current_index ]._references = []


  def Reset( self ):
    self._down_nodes = []
    self._up_nodes = []
    self._kind = ''


  def _HierarchyToLinesHelper( self, refs, use_down_nodes ):
    partial_result = []
    nodes = self._down_nodes if use_down_nodes else self._up_nodes
    for index in refs:
      next_node = nodes[ index ]
      indent = 2 * next_node._distance_from_root
      if index == 0:
        can_expand = ( self._down_nodes[ 0 ]._references is None or
                       self._up_nodes[ 0 ]._references is None )
      else:
        can_expand = next_node._references is None
      symbol = '+' if can_expand else '-'
      name = next_node._data[ 'name' ]
      kind = next_node._data[ 'kind' ]
      if use_down_nodes:
        partial_result.extend( [
          (
            {
              'indent': indent,
              'icon': symbol,
              'symbol': name,
              'kind': kind,
              'filepath': os.path.split( l[ 'filepath' ] )[ 1 ],
              'line_num': str( l[ 'line_num' ] ),
              'description': l.get( 'description', '' ).strip(),
            },
            make_handle( index, location_index )
          )
          for location_index, l in enumerate( next_node._data[ 'locations' ] )
        ] )
      else:
        partial_result.extend( [
          (
            {
              'indent': indent,
              'icon': symbol,
              'symbol': name,
              'kind': kind,
              'filepath': os.path.split( l[ 'filepath' ] )[ 1 ],
              'line_num': str( l[ 'line_num' ] ),
              'description': l.get( 'description', '' ).strip(),
            },
            make_handle( index, location_index ) * -1
          )
          for location_index, l in enumerate( next_node._data[ 'locations' ] )
        ] )
      if next_node._references:
        partial_result.extend(
          self._HierarchyToLinesHelper(
            next_node._references, use_down_nodes ) )
    return partial_result

  def HierarchyToLines( self ):
    down_lines = self._HierarchyToLinesHelper( [ 0 ], True )
    up_lines = self._HierarchyToLinesHelper( [ 0 ], False )
    up_lines.reverse()
    return up_lines + down_lines[ 1: ]


  def JumpToItem( self, handle : int, command ):
    node_index = handle_to_index( handle )
    location_index = handle_to_location_index( handle )
    if handle >= 0:
      node = self._down_nodes[ node_index ]
    else:
      node = self._up_nodes[ node_index ]
    file, line, column = node.ToLocation( location_index )
    vimsupport.JumpToLocation( file, line, column, '', command )


  def ShouldResolveItem( self, handle : int, direction : str ):
    node_index = handle_to_index( handle )
    if ( ( handle >= 0 and direction == 'down' ) or
         ( handle <= 0 and direction == 'up' ) ):
      if direction == 'down':
        node = self._down_nodes[ node_index ]
      else:
        node = self._up_nodes[ node_index ]
      return node._references is None
    return True


  def ResolveArguments( self, handle : int, direction : str ):
    node_index = handle_to_index( handle )
    if self._kind == 'call':
      direction = 'outgoing' if direction == 'up' else 'incoming'
    else:
      direction = 'supertypes' if direction == 'up' else 'subtypes'
    if handle >= 0:
      node = self._down_nodes[ node_index ]
    else:
      node = self._up_nodes[ node_index ]
    return [
      f'Resolve{ self._kind.title() }HierarchyItem',
      node._data,
      direction
    ]


  def HandleToRootLocation( self, handle : int ):
    node_index = handle_to_index( handle )

    if handle >= 0:
      node = self._down_nodes[ node_index ]
    else:
      node = self._up_nodes[ node_index ]

    location_index = handle_to_location_index( handle )
    return node.ToRootLocation( location_index )


  def UpdateChangesRoot( self, handle : int, direction : str ):
    return ( ( handle < 0 and direction == 'down' ) or
             ( handle > 0 and direction == 'up' ) )



File: python/ycm/__init__.py




File: python/ycm/diagnostic_interface.py

# Copyright (C) 2013-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from collections import defaultdict
from ycm import vimsupport
from ycm.diagnostic_filter import DiagnosticFilter, CompileLevel
from ycm import text_properties as tp
import vim
YCM_VIM_PROPERTY_ID = 1


class DiagnosticInterface:
  def __init__( self, bufnr, user_options ):
    self._bufnr = bufnr
    self._user_options = user_options
    self._diagnostics = []
    self._diag_filter = DiagnosticFilter.CreateFromOptions( user_options )
    # Line and column numbers are 1-based
    self._line_to_diags = defaultdict( list )
    self._previous_diag_line_number = -1
    self._diag_message_needs_clearing = False


  def ShouldUpdateDiagnosticsUINow( self ):
    return ( self._user_options[ 'update_diagnostics_in_insert_mode' ] or
             'i' not in vim.eval( 'mode()' ) )


  def OnCursorMoved( self ):
    if self._user_options[ 'echo_current_diagnostic' ]:
      line, _ = vimsupport.CurrentLineAndColumn()
      line += 1  # Convert to 1-based
      if not self.ShouldUpdateDiagnosticsUINow():
        # Clear any previously echo'd diagnostic in insert mode
        self._EchoDiagnosticText( line, None, None )
      elif line != self._previous_diag_line_number:
        self._EchoDiagnosticForLine( line )


  def GetErrorCount( self ):
    return self._DiagnosticsCount( _DiagnosticIsError )


  def GetWarningCount( self ):
    return self._DiagnosticsCount( _DiagnosticIsWarning )


  def PopulateLocationList( self, open_on_edit = False ):
    # Do nothing if loc list is already populated by diag_interface
    if not self._user_options[ 'always_populate_location_list' ]:
      self._UpdateLocationLists( open_on_edit )
    return bool( self._diagnostics )


  def UpdateWithNewDiagnostics( self, diags, open_on_edit = False ):
    self._diagnostics = [ _NormalizeDiagnostic( x ) for x in
                            self._ApplyDiagnosticFilter( diags ) ]
    self._ConvertDiagListToDict()

    if self.ShouldUpdateDiagnosticsUINow():
      self.RefreshDiagnosticsUI( open_on_edit )


  def RefreshDiagnosticsUI( self, open_on_edit = False ):
    if self._user_options[ 'echo_current_diagnostic' ]:
      self._EchoDiagnostic()

    if self._user_options[ 'enable_diagnostic_signs' ]:
      self._UpdateSigns()

    self.UpdateMatches()

    if self._user_options[ 'always_populate_location_list' ]:
      self._UpdateLocationLists( open_on_edit )


  def ClearDiagnosticsUI( self ):
    if self._user_options[ 'echo_current_diagnostic' ]:
      self._ClearCurrentDiagnostic()

    if self._user_options[ 'enable_diagnostic_signs' ]:
      self._ClearSigns()

    self._ClearMatches()


  def DiagnosticsForLine( self, line_number ):
    return self._line_to_diags[ line_number ]


  def _ApplyDiagnosticFilter( self, diags ):
    filetypes = vimsupport.GetBufferFiletypes( self._bufnr )
    diag_filter = self._diag_filter.SubsetForTypes( filetypes )
    return filter( diag_filter.IsAllowed, diags )


  def _EchoDiagnostic( self ):
    line, _ = vimsupport.CurrentLineAndColumn()
    line += 1  # Convert to 1-based
    self._EchoDiagnosticForLine( line )


  def _EchoDiagnosticForLine( self, line_num ):
    self._previous_diag_line_number = line_num

    diags = self._line_to_diags[ line_num ]
    text = None
    first_diag = None
    if diags:
      first_diag = diags[ 0 ]
      text = first_diag[ 'text' ]
      if first_diag.get( 'fixit_available', False ):
        text += ' (FixIt)'

    self._EchoDiagnosticText( line_num, first_diag, text )


  def _ClearCurrentDiagnostic( self, will_be_replaced=False ):
    if not self._diag_message_needs_clearing:
      return

    if ( not vimsupport.VimIsNeovim() and
         self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text' ):
      tp.ClearTextProperties( self._bufnr,
                              prop_types = [ 'YcmVirtDiagPadding',
                                             'YcmVirtDiagError',
                                             'YcmVirtDiagWarning' ] )
    else:
      if not will_be_replaced:
        vimsupport.PostVimMessage( '', warning = False )

    self._diag_message_needs_clearing = False


  def _EchoDiagnosticText( self, line_num, first_diag, text ):
    self._ClearCurrentDiagnostic( bool( text ) )

    if ( not vimsupport.VimIsNeovim() and
         self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text' ):
      if not text:
        return

      def MakeVritualTextProperty( prop_type, text, position='after' ):
        vimsupport.AddTextProperty( self._bufnr,
                                    line_num,
                                    0,
                                    prop_type,
                                    {
                                      'text': text,
                                      'text_align': position,
                                      'text_wrap': 'wrap'
                                    } )

      if vim.options[ 'ambiwidth' ] != 'double':
        marker = '⚠'
      else:
        marker = '>'

      MakeVritualTextProperty(
        'YcmVirtDiagPadding',
        ' ' * vim.buffers[ self._bufnr ].options[ 'shiftwidth' ] ),
      MakeVritualTextProperty(
        'YcmVirtDiagError' if _DiagnosticIsError( first_diag )
                       else 'YcmVirtDiagWarning',
        marker + ' ' + [ line for line in text.splitlines() if line ][ 0 ] )
    else:
      if not text:
        # We already cleared it
        return

      vimsupport.PostVimMessage( text, warning = False, truncate = True )

    self._diag_message_needs_clearing = True


  def _DiagnosticsCount( self, predicate ):
    count = 0
    for diags in self._line_to_diags.values():
      count += sum( 1 for d in diags if predicate( d ) )
    return count


  def _UpdateLocationLists( self, open_on_edit = False ):
    vimsupport.SetLocationListsForBuffer(
      self._bufnr,
      vimsupport.ConvertDiagnosticsToQfList( self._diagnostics ),
      open_on_edit )


  def _ClearMatches( self ):
    props_to_remove = vimsupport.GetTextProperties( self._bufnr )
    for prop in props_to_remove:
      vimsupport.RemoveDiagnosticProperty( self._bufnr, prop )


  def UpdateMatches( self ):
    if not self._user_options[ 'enable_diagnostic_highlighting' ]:
      return

    props_to_remove = vimsupport.GetTextProperties( self._bufnr )
    for diags in self._line_to_diags.values():
      # Insert squiggles in reverse order so that errors overlap warnings.
      for diag in reversed( diags ):
        for line, column, name, extras in _ConvertDiagnosticToTextProperties(
            self._bufnr,
            diag ):
          global YCM_VIM_PROPERTY_ID

          # Note the following .remove() works because the __eq__ on
          # DiagnosticProperty does not actually check the IDs match...
          diag_prop = vimsupport.DiagnosticProperty(
              YCM_VIM_PROPERTY_ID,
              name,
              line,
              column,
              extras[ 'end_col' ] - column if 'end_col' in extras else column )
          try:
            props_to_remove.remove( diag_prop )
          except ValueError:
            extras.update( {
              'id': YCM_VIM_PROPERTY_ID
            } )
            vimsupport.AddTextProperty( self._bufnr,
                                        line,
                                        column,
                                        name,
                                        extras )
          YCM_VIM_PROPERTY_ID += 1
    for prop in props_to_remove:
      vimsupport.RemoveDiagnosticProperty( self._bufnr, prop )


  def _ClearSigns( self ):
    signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
    vim.eval( f'sign_unplacelist( { signs_to_unplace } )' )


  def _UpdateSigns( self ):
    signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
    signs_to_place = []
    for line, diags in self._line_to_diags.items():
      if not diags:
        continue

      # We always go for the first diagnostic on the line because diagnostics
      # are sorted by errors in priority and Vim can only display one sign by
      # line.
      name = 'YcmError' if _DiagnosticIsError( diags[ 0 ] ) else 'YcmWarning'
      sign = {
          'lnum': line,
          'name': name,
          'buffer': self._bufnr,
          'group': 'ycm_signs'
      }
      try:
        signs_to_unplace.remove( sign )
      except ValueError:
        signs_to_place.append( sign )
    vim.eval( f'sign_placelist( { signs_to_place } )' )
    vim.eval( f'sign_unplacelist( { signs_to_unplace } )' )


  def _ConvertDiagListToDict( self ):
    self._line_to_diags = defaultdict( list )
    for diag in self._diagnostics:
      location_extent = diag[ 'location_extent' ]
      start = location_extent[ 'start' ]
      end = location_extent[ 'end' ]
      bufnr = vimsupport.GetBufferNumberForFilename( start[ 'filepath' ] )
      if bufnr == self._bufnr:
        for line_number in range( start[ 'line_num' ], end[ 'line_num' ] + 1 ):
          self._line_to_diags[ line_number ].append( diag )

    for diags in self._line_to_diags.values():
      # We also want errors to be listed before warnings so that errors aren't
      # hidden by the warnings; Vim won't place a sign over an existing one.
      diags.sort( key = lambda diag: ( diag[ 'kind' ],
                                       diag[ 'location' ][ 'column_num' ] ) )


_DiagnosticIsError = CompileLevel( 'error' )
_DiagnosticIsWarning = CompileLevel( 'warning' )


def _NormalizeDiagnostic( diag ):
  def ClampToOne( value ):
    return value if value > 0 else 1

  location = diag[ 'location' ]
  location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] )
  location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] )
  return diag


def _ConvertDiagnosticToTextProperties( bufnr, diagnostic ):
  properties = []

  name = ( 'YcmErrorProperty' if _DiagnosticIsError( diagnostic ) else
            'YcmWarningProperty' )
  if vimsupport.VimIsNeovim():
    name = name.replace( 'Property', 'Section' )

  location_extent = diagnostic[ 'location_extent' ]
  if location_extent[ 'start' ][ 'line_num' ] <= 0:
    location = diagnostic[ 'location' ]
    line, column = vimsupport.LineAndColumnNumbersClamped(
      bufnr,
      location[ 'line_num' ],
      location[ 'column_num' ]
    )
    properties.append( ( line, column, name, {} ) )
  else:
    start_line, start_column = vimsupport.LineAndColumnNumbersClamped(
      bufnr,
      location_extent[ 'start' ][ 'line_num' ],
      location_extent[ 'start' ][ 'column_num' ]
    )
    end_line, end_column = vimsupport.LineAndColumnNumbersClamped(
      bufnr,
      location_extent[ 'end' ][ 'line_num' ],
      location_extent[ 'end' ][ 'column_num' ]
    )
    properties.append( (
      start_line,
      start_column,
      name,
      { 'end_lnum': end_line,
        'end_col': end_column } ) )

  for diagnostic_range in diagnostic[ 'ranges' ]:
    if ( diagnostic_range[ 'start' ][ 'line_num' ] == 0 or
         diagnostic_range[ 'end' ][ 'line_num' ] == 0 ):
      continue
    start_line, start_column = vimsupport.LineAndColumnNumbersClamped(
      bufnr,
      diagnostic_range[ 'start' ][ 'line_num' ],
      diagnostic_range[ 'start' ][ 'column_num' ]
    )
    end_line, end_column = vimsupport.LineAndColumnNumbersClamped(
      bufnr,
      diagnostic_range[ 'end' ][ 'line_num' ],
      diagnostic_range[ 'end' ][ 'column_num' ]
    )

    if not _IsValidRange( start_line, start_column, end_line, end_column ):
      continue

    properties.append( (
      start_line,
      start_column,
      name,
      { 'end_lnum': end_line,
        'end_col': end_column } ) )

  return properties


def _IsValidRange( start_line, start_column, end_line, end_column ):
  # End line before start line - invalid
  if start_line > end_line:
    return False

  # End line after start line - valid
  if start_line < end_line:
    return True

  # Same line, start colum after end column - invalid
  if start_column > end_column:
    return False

  # Same line, start column before or equal to end column - valid
  return True



File: python/ycm/inlay_hints.py

# Copyright (C) 2022, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.


from ycm.client.inlay_hints_request import InlayHintsRequest
from ycm.client.base_request import BuildRequestData
from ycm import vimsupport
from ycm import text_properties as tp
from ycm import scrolling_range as sr


HIGHLIGHT_GROUP = {
  'Type':      'YcmInlayHint',
  'Parameter': 'YcmInlayHint',
  'Enum':      'YcmInlayHint',
}
REPORTED_MISSING_TYPES = set()


def Initialise():
  if vimsupport.VimIsNeovim():
    return False

  props = tp.GetTextPropertyTypes()
  if 'YCM_INLAY_UNKNOWN' not in props:
    tp.AddTextPropertyType( 'YCM_INLAY_UNKNOWN',
                            highlight = 'YcmInlayHint',
                            start_incl = 1 )
  if 'YCM_INLAY_PADDING' not in props:
    tp.AddTextPropertyType( 'YCM_INLAY_PADDING',
                            highlight = 'YcmInvisible',
                            start_incl = 1 )

  for token_type, group in HIGHLIGHT_GROUP.items():
    prop = f'YCM_INLAY_{ token_type }'
    if prop not in props and vimsupport.GetIntValue(
        f"hlexists( '{ vimsupport.EscapeForVim( group ) }' )" ):
      tp.AddTextPropertyType( prop,
                              highlight = group,
                              start_incl = 1 )

  return True


class InlayHints( sr.ScrollingBufferRange ):
  """Stores the inlay hints state for a Vim buffer"""


  def _NewRequest( self, request_range ):
    request_data = BuildRequestData( self._bufnr )
    request_data[ 'range' ] = request_range
    return InlayHintsRequest( request_data )


  def Clear( self ):
    types = [ 'YCM_INLAY_UNKNOWN', 'YCM_INLAY_PADDING' ] + [
      f'YCM_INLAY_{ prop_type }' for prop_type in HIGHLIGHT_GROUP.keys()
    ]

    tp.ClearTextProperties( self._bufnr, prop_types = types )


  def _Draw( self ):
    self.Clear()

    for inlay_hint in self._latest_response:
      if 'kind' not in inlay_hint:
        prop_type = 'YCM_INLAY_UNKNOWN'
      elif inlay_hint[ 'kind' ] not in HIGHLIGHT_GROUP:
        prop_type = 'YCM_INLAY_UNKNOWN'
      else:
        prop_type = 'YCM_INLAY_' + inlay_hint[ 'kind' ]

      self.GrowRangeIfNeeded( {
        'start': inlay_hint[ 'position' ],
        'end': {
          'line_num': inlay_hint[ 'position' ][ 'line_num' ],
          'column_num': inlay_hint[ 'position' ][ 'column_num' ] + len(
            inlay_hint[ 'label' ] )
        }
      } )

      if inlay_hint.get( 'paddingLeft', False ):
        tp.AddTextProperty( self._bufnr,
                            None,
                            'YCM_INLAY_PADDING',
                            {
                              'start': inlay_hint[ 'position' ],
                            },
                            {
                              'text': ' '
                            } )

      tp.AddTextProperty( self._bufnr,
                          None,
                          prop_type,
                          {
                            'start': inlay_hint[ 'position' ],
                          },
                          {
                            'text': inlay_hint[ 'label' ]
                          } )

      if inlay_hint.get( 'paddingRight', False ):
        tp.AddTextProperty( self._bufnr,
                            None,
                            'YCM_INLAY_PADDING',
                            {
                              'start': inlay_hint[ 'position' ],
                            },
                            {
                              'text': ' '
                            } )



File: python/ycm/syntax_parse.py

# Copyright (C) 2013  Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import re
from ycm import vimsupport

SYNTAX_GROUP_REGEX = re.compile(
  r"""^
      (?P<group_name>\w+)
      \s+
      xxx
      \s+
      (?P<content>.+?)
      $""",
  re.VERBOSE )

KEYWORD_REGEX = re.compile( r'^(\w+),?$' )

SYNTAX_ARGUMENT_REGEX = re.compile(
  r"^\w+=.*$" )

SYNTAX_REGION_ARGUMENT_REGEX = re.compile(
  r"^(?:matchgroup|start)=.*$" )

# See ":h syn-nextgroup".
SYNTAX_NEXTGROUP_ARGUMENTS = {
  'skipwhite',
  'skipnl',
  'skipempty'
}

# These are the parent groups from which we want to extract keywords.
ROOT_GROUPS = {
  'Boolean',
  'Identifier',
  'Statement',
  'PreProc',
  'Type'
}


class SyntaxGroup:
  def __init__( self, name, lines = None ):
    self.name     = name
    self.lines    = lines if lines else []
    self.children = []


def SyntaxKeywordsForCurrentBuffer():
  syntax_output = vimsupport.CaptureVimCommand( 'syntax list' )
  return _KeywordsFromSyntaxListOutput( syntax_output )


def _KeywordsFromSyntaxListOutput( syntax_output ):
  group_name_to_group = _SyntaxGroupsFromOutput( syntax_output )
  _ConnectGroupChildren( group_name_to_group )

  groups_with_keywords = []
  for root_group in ROOT_GROUPS:
    groups_with_keywords.extend(
      _GetAllDescendentats( group_name_to_group[ root_group ] ) )

  keywords = []
  for group in groups_with_keywords:
    keywords.extend( _ExtractKeywordsFromGroup( group ) )
  return set( keywords )


def _SyntaxGroupsFromOutput( syntax_output ):
  group_name_to_group = _CreateInitialGroupMap()
  lines               = syntax_output.split( '\n' )
  looking_for_group   = True

  current_group = None
  for line in lines:
    if not line:
      continue

    match = SYNTAX_GROUP_REGEX.search( line )
    if match:
      if looking_for_group:
        looking_for_group = False
      else:
        group_name_to_group[ current_group.name ] = current_group

      current_group = SyntaxGroup( match.group( 'group_name' ),
                                   [ match.group( 'content' ).strip() ] )
    else:
      if looking_for_group:
        continue

      if line[ 0 ] == ' ' or line[ 0 ] == '\t':
        current_group.lines.append( line.strip() )

  if current_group:
    group_name_to_group[ current_group.name ] = current_group
  return group_name_to_group


def _CreateInitialGroupMap():
  def AddToGroupMap( name, parent ):
    new_group = SyntaxGroup( name )
    group_name_to_group[ name ] = new_group
    parent.children.append( new_group )

  identifier_group = SyntaxGroup( 'Identifier' )
  statement_group  = SyntaxGroup( 'Statement' )
  type_group       = SyntaxGroup( 'Type' )
  preproc_group    = SyntaxGroup( 'PreProc' )

  # See ":h group-name" for details on how the initial group hierarchy is built.
  group_name_to_group = {
    'Boolean': SyntaxGroup( 'Boolean' ),
    'Identifier': identifier_group,
    'Statement': statement_group,
    'PreProc': preproc_group,
    'Type': type_group
  }

  AddToGroupMap( 'Function', identifier_group )

  AddToGroupMap( 'Conditional', statement_group )
  AddToGroupMap( 'Repeat'     , statement_group )
  AddToGroupMap( 'Label'      , statement_group )
  AddToGroupMap( 'Operator'   , statement_group )
  AddToGroupMap( 'Keyword'    , statement_group )
  AddToGroupMap( 'Exception'  , statement_group )

  AddToGroupMap( 'StorageClass', type_group )
  AddToGroupMap( 'Structure'   , type_group )
  AddToGroupMap( 'Typedef'     , type_group )

  AddToGroupMap( 'Include'  , preproc_group )
  AddToGroupMap( 'Define'   , preproc_group )
  AddToGroupMap( 'Macro'    , preproc_group )
  AddToGroupMap( 'PreCondit', preproc_group )

  return group_name_to_group


def _ConnectGroupChildren( group_name_to_group ):
  def GetParentNames( group ):
    links_to     = 'links to '
    parent_names = []
    for line in group.lines:
      if line.startswith( links_to ):
        parent_names.append( line[ len( links_to ): ] )
    return parent_names

  for group in group_name_to_group.values():
    parent_names = GetParentNames( group )

    for parent_name in parent_names:
      try:
        parent_group = group_name_to_group[ parent_name ]
      except KeyError:
        continue
      parent_group.children.append( group )


def _GetAllDescendentats( root_group ):
  descendants = []
  for child in root_group.children:
    descendants.append( child )
    descendants.extend( _GetAllDescendentats( child ) )
  return descendants


def _ExtractKeywordsFromLine( line ):
  if line.startswith( 'links to ' ):
    return []

  # Ignore "syntax match" lines (see ":h syn-match").
  if line.startswith( 'match ' ):
    return []

  words = line.split()
  if not words:
    return []

  # Ignore "syntax region" lines (see ":h syn-region"). They always start
  # with matchgroup= or start= in the syntax list.
  if SYNTAX_REGION_ARGUMENT_REGEX.match( words[ 0 ] ):
    return []

  # Ignore "nextgroup=" argument in first position and the arguments
  # "skipwhite", "skipnl", and "skipempty" that immediately come after.
  nextgroup_at_start = False
  if words[ 0 ].startswith( 'nextgroup=' ):
    nextgroup_at_start = True
    words = words[ 1: ]

  # Ignore "contained" argument in first position.
  if words[ 0 ] == 'contained':
    words = words[ 1: ]

  keywords = []
  for word in words:
    if nextgroup_at_start and word in SYNTAX_NEXTGROUP_ARGUMENTS:
      continue

    nextgroup_at_start = False

    keyword_matched = KEYWORD_REGEX.match( word )
    if keyword_matched:
      keywords.append( keyword_matched.group( 1 ) )
  return keywords


def _ExtractKeywordsFromGroup( group ):
  keywords = []
  for line in group.lines:
    keywords.extend( _ExtractKeywordsFromLine( line ) )
  return keywords



File: python/ycm/text_properties.py

# Copyright (C) 2020, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.


from ycm import vimsupport
from ycm.vimsupport import GetIntValue
from ycmd import utils

import vim
import json
import typing


# FIXME/TODO: Merge this with vimsupport funcitons, added after these were
# written. It's not trivial, as those vimsupport functions are a bit fiddly.
# They also support neovim, but we don't.
def AddTextPropertyType( name, **kwargs ):
  props = {
    'highlight': 'Ignore',
    'combine': 0,
    'override': 0,
    'start_incl': 0,
    'end_incl': 0,
    'priority': 10
  }
  props.update( kwargs )

  vim.eval( f"prop_type_add( '{ vimsupport.EscapeForVim( name ) }', "
            f"               { json.dumps( props ) } )" )


def GetTextPropertyTypes( *args, **kwargs ):
  return [ utils.ToUnicode( p ) for p in vim.eval( 'prop_type_list()' ) ]


def AddTextProperty( bufnr,
                     prop_id,
                     prop_type,
                     range,
                     extra_args: dict = None ):
  props = {
    'bufnr': bufnr,
    'type': prop_type
  }
  if prop_id is not None:
    props[ 'id' ] = prop_id
  if extra_args:
    props.update( extra_args )
  if 'end' in range:
    props.update( {
      'end_lnum': range[ 'end' ][ 'line_num' ],
      'end_col':  range[ 'end' ][ 'column_num' ],
    } )
  return vim.eval( f"prop_add( { range[ 'start' ][ 'line_num' ] },"
                   f"          { range[ 'start' ][ 'column_num' ] },"
                   f"          { json.dumps( props ) } )" )


def ClearTextProperties(
  bufnr,
  prop_id = None,
  prop_types: typing.Union[ typing.List[ str ], str ] = None,
  first_line = None,
  last_line = None ):

  props = {
    'bufnr': bufnr,
    'all': 1,
  }
  if prop_id is not None:
    props[ 'id' ] = prop_id

  if prop_id is not None and prop_types is not None:
    props[ 'both' ] = 1

  def prop_remove():
    if last_line is not None:
      return GetIntValue( f"prop_remove( { json.dumps( props ) },"
                                      f" { first_line },"
                                      f" { last_line } )" )
    elif first_line is not None:
      return GetIntValue( f"prop_remove( { json.dumps( props ) },"
                                      f" { first_line } )" )
    else:
      return GetIntValue( f"prop_remove( { json.dumps( props ) } )" )

  if prop_types is None:
    return prop_remove()

  if not isinstance( prop_types, list ):
    prop_types = [ prop_types ]

  props[ 'types' ] = prop_types
  return prop_remove()



File: python/ycm/semantic_highlighting.py

# Copyright (C) 2020, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.


from ycm.client.semantic_tokens_request import SemanticTokensRequest
from ycm.client.base_request import BuildRequestData
from ycm import vimsupport
from ycm import text_properties as tp
from ycm import scrolling_range as sr

import vim


HIGHLIGHT_GROUP = {
  'namespace': 'Type',
  'type': 'Type',
  'class': 'Structure',
  'enum': 'Structure',
  'interface': 'Structure',
  'struct': 'Structure',
  'typeParameter': 'Identifier',
  'parameter': 'Identifier',
  'variable': 'Identifier',
  'property': 'Identifier',
  'enumMember': 'Identifier',
  'enumConstant': 'Constant',
  'event': 'Identifier',
  'function': 'Function',
  'member': 'Identifier',
  'macro': 'Macro',
  'method': 'Function',
  'keyword': 'Keyword',
  'modifier': 'Keyword',
  'comment': 'Comment',
  'string': 'String',
  'number': 'Number',
  'regexp': 'String',
  'operator': 'Operator',
  'decorator': 'Special',
  'unknown': 'Normal',

  # These are not part of the spec, but are used by clangd
  'bracket': 'Normal',
  'concept': 'Type',
  # These are not part of the spec, but are used by jdt.ls
  'annotation': 'Macro',
}
REPORTED_MISSING_TYPES = set()


def Initialise():
  if vimsupport.VimIsNeovim():
    return

  props = tp.GetTextPropertyTypes()
  if 'YCM_HL_UNKNOWN' not in props:
    tp.AddTextPropertyType( 'YCM_HL_UNKNOWN',
                            highlight = 'WarningMsg',
                            priority = 0 )

  for token_type, group in HIGHLIGHT_GROUP.items():
    prop = f'YCM_HL_{ token_type }'
    if prop not in props and vimsupport.GetIntValue(
        f"hlexists( '{ vimsupport.EscapeForVim( group ) }' )" ):
      tp.AddTextPropertyType( prop,
                              highlight = group,
                              priority = 0 )


# "arbitrary" base id
NEXT_TEXT_PROP_ID = 70784


def NextPropID():
  global NEXT_TEXT_PROP_ID
  try:
    return NEXT_TEXT_PROP_ID
  finally:
    NEXT_TEXT_PROP_ID += 1



class SemanticHighlighting( sr.ScrollingBufferRange ):
  """Stores the semantic highlighting state for a Vim buffer"""

  def __init__( self, bufnr ):
    self._prop_id = NextPropID()
    super().__init__( bufnr )


  def _NewRequest( self, request_range ):
    request: dict = BuildRequestData( self._bufnr )
    request[ 'range' ] = request_range
    return SemanticTokensRequest( request )


  def _Draw( self ):
    # We requested a snapshot
    tokens = self._latest_response.get( 'tokens', [] )

    prev_prop_id = self._prop_id
    self._prop_id = NextPropID()

    for token in tokens:
      prop_type = f"YCM_HL_{ token[ 'type' ] }"
      rng = token[ 'range' ]
      self.GrowRangeIfNeeded( rng )

      try:
        tp.AddTextProperty( self._bufnr, self._prop_id, prop_type, rng )
      except vim.error as e:
        if 'E971:' in str( e ): # Text property doesn't exist
          if token[ 'type' ] not in REPORTED_MISSING_TYPES:
            REPORTED_MISSING_TYPES.add( token[ 'type' ] )
            vimsupport.PostVimMessage(
              f"Token type { token[ 'type' ] } not supported. "
              f"Define property type { prop_type }. "
              f"See :help youcompleteme-customising-highlight-groups" )
        else:
          raise e

    tp.ClearTextProperties( self._bufnr, prop_id = prev_prop_id )



File: python/ycm/buffer.py

# Copyright (C) 2016, Davit Samvelyan
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm import vimsupport
from ycm.client.event_notification import EventNotification
from ycm.diagnostic_interface import DiagnosticInterface
from ycm.semantic_highlighting import SemanticHighlighting
from ycm.inlay_hints import InlayHints


# Emulates Vim buffer
# Used to store buffer related information like diagnostics, latest parse
# request. Stores buffer change tick at the parse request moment, allowing
# to effectively determine whether reparse is needed for the buffer.
class Buffer:

  def __init__( self, bufnr, user_options, filetypes ):
    self._number = bufnr
    self._parse_tick = 0
    self._handled_tick = 0
    self._parse_request = None
    self._should_resend = False
    self._diag_interface = DiagnosticInterface( bufnr, user_options )
    self._open_loclist_on_ycm_diags = user_options[
                                        'open_loclist_on_ycm_diags' ]
    self.semantic_highlighting = SemanticHighlighting( bufnr )
    self.inlay_hints = InlayHints( bufnr )
    self.UpdateFromFileTypes( filetypes )


  def FileParseRequestReady( self, block = False ):
    return ( bool( self._parse_request ) and
             ( block or self._parse_request.Done() ) )


  def SendParseRequest( self, extra_data ):
    # Don't send a parse request if one is in progress
    if self._parse_request is not None and not self._parse_request.Done():
      self._should_resend = True
      return

    self._should_resend = False

    self._parse_request = EventNotification( 'FileReadyToParse',
                                             extra_data = extra_data )
    self._parse_request.Start()
    # Decrement handled tick to ensure correct handling when we are forcing
    # reparse on buffer visit and changed tick remains the same.
    self._handled_tick -= 1
    self._parse_tick = self._ChangedTick()


  def ParseRequestPending( self ):
    return bool( self._parse_request ) and not self._parse_request.Done()


  def NeedsReparse( self ):
    return self._parse_tick != self._ChangedTick()


  def ShouldResendParseRequest( self ):
    return ( self._should_resend
             or ( bool( self._parse_request )
                  and self._parse_request.ShouldResend() ) )


  def UpdateDiagnostics( self, force = False ):
    if force or not self._async_diags:
      self.UpdateWithNewDiagnostics( self._parse_request.Response(), False )
    else:
      # We need to call the response method, because it might throw an exception
      # or require extra config confirmation, even if we don't actually use the
      # diagnostics.
      self._parse_request.Response()


  def UpdateWithNewDiagnostics( self, diagnostics, async_message ):
    self._async_diags = async_message
    self._diag_interface.UpdateWithNewDiagnostics(
        diagnostics,
        not self._async_diags and self._open_loclist_on_ycm_diags )


  def UpdateMatches( self ):
    self._diag_interface.UpdateMatches()


  def PopulateLocationList( self, open_on_edit = False ):
    return self._diag_interface.PopulateLocationList( open_on_edit )


  def GetResponse( self ):
    return self._parse_request.Response()


  def IsResponseHandled( self ):
    return self._handled_tick == self._parse_tick


  def MarkResponseHandled( self ):
    self._handled_tick = self._parse_tick


  def OnCursorMoved( self ):
    self._diag_interface.OnCursorMoved()


  def GetErrorCount( self ):
    return self._diag_interface.GetErrorCount()


  def GetWarningCount( self ):
    return self._diag_interface.GetWarningCount()


  def RefreshDiagnosticsUI( self ):
    return self._diag_interface.RefreshDiagnosticsUI()


  def ClearDiagnosticsUI( self ):
    return self._diag_interface.ClearDiagnosticsUI()


  def DiagnosticsForLine( self, line_number ):
    return self._diag_interface.DiagnosticsForLine( line_number )


  def UpdateFromFileTypes( self, filetypes ):
    self._filetypes = filetypes
    # We will set this to true if we ever receive any diagnostics asyncronously.
    self._async_diags = False


  def _ChangedTick( self ):
    return vimsupport.GetBufferChangedTick( self._number )


class BufferDict( dict ):

  def __init__( self, user_options ):
    self._user_options = user_options


  def __missing__( self, key ):
    # Python does not allow to return assignment operation result directly
    new_value = self[ key ] = Buffer(
      key,
      self._user_options,
      vimsupport.GetBufferFiletypes( key ) )

    return new_value



File: python/ycm/base.py

# Copyright (C) 2011, 2012  Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import os
import json

from ycm import vimsupport, paths
from ycmd import identifier_utils

YCM_VAR_PREFIX = 'ycm_'


def GetUserOptions( default_options = {} ):
  """Builds a dictionary mapping YCM Vim user options to values. Option names
  don't have the 'ycm_' prefix."""

  user_options = {}

  # First load the default settings from ycmd. We do this to ensure that any
  # client-side code that assumes all options are loaded (such as the
  # omnicompleter) don't have to constantly check for values being present, and
  # so that we don't jave to dulicate the list of server settings in
  # youcomplete.vim
  defaults_file =  os.path.join( paths.DIR_OF_YCMD,
                                 'ycmd',
                                 'default_settings.json' )
  if os.path.exists( defaults_file ):
    with open( defaults_file ) as defaults_file_handle:
      user_options = json.load( defaults_file_handle )

  # Override the server defaults with any client-generated defaults
  user_options.update( default_options )

  # Finally, override with any user-specified values in the g: dict

  # We only evaluate the keys of the vim globals and not the whole dictionary
  # to avoid unicode issues.
  # See https://github.com/Valloric/YouCompleteMe/pull/2151 for details.
  keys = vimsupport.GetVimGlobalsKeys()
  for key in keys:
    if not key.startswith( YCM_VAR_PREFIX ):
      continue
    new_key = key[ len( YCM_VAR_PREFIX ): ]
    new_value = vimsupport.VimExpressionToPythonType( 'g:' + key )
    user_options[ new_key ] = new_value

  return user_options


def CurrentIdentifierFinished():
  line, current_column = vimsupport.CurrentLineContentsAndCodepointColumn()
  previous_char_index = current_column - 1
  if previous_char_index < 0:
    return True
  filetype = vimsupport.CurrentFiletypes()[ 0 ]
  regex = identifier_utils.IdentifierRegexForFiletype( filetype )

  for match in regex.finditer( line ):
    if match.end() == previous_char_index:
      return True
  # If the whole line is whitespace, that means the user probably finished an
  # identifier on the previous line.
  return line[ : current_column ].isspace()


def LastEnteredCharIsIdentifierChar():
  line, current_column = vimsupport.CurrentLineContentsAndCodepointColumn()
  if current_column - 1 < 0:
    return False
  filetype = vimsupport.CurrentFiletypes()[ 0 ]
  return (
    identifier_utils.StartOfLongestIdentifierEndingAtIndex(
        line, current_column, filetype ) != current_column )


def AdjustCandidateInsertionText( candidates ):
  """This function adjusts the candidate insertion text to take into account the
  text that's currently in front of the cursor.

  For instance ('|' represents the cursor):
    1. Buffer state: 'foo.|bar'
    2. A completion candidate of 'zoobar' is shown and the user selects it.
    3. Buffer state: 'foo.zoobar|bar' instead of 'foo.zoo|bar' which is what the
    user wanted.

  This function changes candidates to resolve that issue.

  It could be argued that the user actually wants the final buffer state to be
  'foo.zoobar|' (the cursor at the end), but that would be much more difficult
  to implement and is probably not worth doing.
  """

  def NewCandidateInsertionText( to_insert, text_after_cursor ):
    overlap_len = OverlapLength( to_insert, text_after_cursor )
    if overlap_len:
      return to_insert[ :-overlap_len ]
    return to_insert

  text_after_cursor = vimsupport.TextAfterCursor()
  if not text_after_cursor:
    return candidates

  new_candidates = []
  for candidate in candidates:
    new_candidate = candidate.copy()

    if not new_candidate.get( 'abbr' ):
      new_candidate[ 'abbr' ] = new_candidate[ 'word' ]

    new_candidate[ 'word' ] = NewCandidateInsertionText(
      new_candidate[ 'word' ],
      text_after_cursor )

    new_candidates.append( new_candidate )
  return new_candidates


def OverlapLength( left_string, right_string ):
  """Returns the length of the overlap between two strings.
  Example: "foo baro" and "baro zoo" -> 4
  """
  left_string_length = len( left_string )
  right_string_length = len( right_string )

  if not left_string_length or not right_string_length:
    return 0

  # Truncate the longer string.
  if left_string_length > right_string_length:
    left_string = left_string[ -right_string_length: ]
  elif left_string_length < right_string_length:
    right_string = right_string[ :left_string_length ]

  if left_string == right_string:
    return min( left_string_length, right_string_length )

  # Start by looking for a single character match
  # and increase length until no match is found.
  best = 0
  length = 1
  while True:
    pattern = left_string[ -length: ]
    found = right_string.find( pattern )
    if found < 0:
      return best
    length += found
    if left_string[ -length: ] == right_string[ :length ]:
      best = length
      length += 1



File: python/ycm/unsafe_thread_pool_executor.py

# Copyright 2009 Brian Quinlan. All Rights Reserved.
#   Licensed to PSF under a Contributor Agreement.
#
# Copyright (C) 2013  Google Inc.
#   Changes to this file are licensed under the same terms as the original file
#   (the Python Software Foundation License).


import threading
import weakref
import sys

from concurrent.futures import _base

try:
  import queue
except ImportError:
  import Queue as queue


# This file provides an UnsafeThreadPoolExecutor, which operates exactly like
# the upstream Python version of ThreadPoolExecutor with one exception: it
# doesn't wait for worker threads to finish before shutting down the Python
# interpreter.
#
# This is dangerous for many workloads, but fine for some (like when threads
# only send network requests). The YCM workload is one of those workloads where
# it's safe (the aforementioned network requests case).

class _WorkItem:
  def __init__( self, future, fn, args, kwargs ):
    self.future = future
    self.fn = fn
    self.args = args
    self.kwargs = kwargs

  def run( self ):
    if not self.future.set_running_or_notify_cancel():
      return

    try:
      result = self.fn( *self.args, **self.kwargs )
    except BaseException:
      e = sys.exc_info()[ 1 ]
      self.future.set_exception( e )
    else:
      self.future.set_result( result )


def _worker( executor_reference, work_queue ):
  try:
    while True:
      work_item = work_queue.get( block=True )
      if work_item is not None:
        work_item.run()
        continue
      executor = executor_reference()
      # Exit if:
      #   - The executor that owns the worker has been collected OR
      #   - The executor that owns the worker has been shutdown.
      if executor is None or executor._shutdown:
        # Notice other workers
        work_queue.put( None )
        return
      del executor
  except BaseException:
    _base.LOGGER.critical( 'Exception in worker', exc_info=True )


class UnsafeThreadPoolExecutor( _base.Executor ):
  def __init__( self, max_workers ):
    """Initializes a new ThreadPoolExecutor instance.

    Args:
        max_workers: The maximum number of threads that can be used to
            execute the given calls.
    """
    self._max_workers = max_workers
    self._work_queue = queue.Queue()
    self._threads = set()
    self._shutdown = False
    self._shutdown_lock = threading.Lock()

  def submit( self, fn, *args, **kwargs ):
    with self._shutdown_lock:
      if self._shutdown:
        raise RuntimeError( 'cannot schedule new futures after shutdown' )

      f = _base.Future()
      w = _WorkItem( f, fn, args, kwargs )

      self._work_queue.put( w )
      self._adjust_thread_count()
      return f
  submit.__doc__ = _base.Executor.submit.__doc__

  def _adjust_thread_count( self ):
    # When the executor gets lost, the weakref callback will wake up
    # the worker threads.
    def weakref_cb( _, q=self._work_queue ):
      q.put( None )
    # TODO(bquinlan): Should avoid creating new threads if there are more
    # idle threads than items in the work queue.
    if len( self._threads ) < self._max_workers:
      t = threading.Thread( target=_worker,
                            args=( weakref.ref( self, weakref_cb ),
                                   self._work_queue ) )
      t.daemon = True
      t.start()
      self._threads.add( t )

  def shutdown( self, wait=True ):
    with self._shutdown_lock:
      self._shutdown = True
      self._work_queue.put( None )
    if wait:
      for t in self._threads:
        t.join()
  shutdown.__doc__ = _base.Executor.shutdown.__doc__



File: python/ycm/omni_completer.py

# Copyright (C) 2011-2019 ycmd contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import vim
from ycm import vimsupport
from ycmd import utils
from ycmd.completers.completer import Completer
from ycm.client.base_request import BaseRequest

OMNIFUNC_RETURNED_BAD_VALUE = 'Omnifunc returned bad value to YCM!'
OMNIFUNC_NOT_LIST = ( 'Omnifunc did not return a list or a dict with a "words" '
                     ' list when expected.' )


class OmniCompleter( Completer ):
  def __init__( self, user_options ):
    super( OmniCompleter, self ).__init__( user_options )
    self._omnifunc = None


  def SupportedFiletypes( self ):
    return []


  def ShouldUseCache( self ):
    return bool( self.user_options[ 'cache_omnifunc' ] )


  def ShouldUseNow( self, request_data ):
    self._omnifunc = utils.ToUnicode( vim.eval( '&omnifunc' ) )
    if not self._omnifunc:
      return False
    if self.ShouldUseCache():
      return super( OmniCompleter, self ).ShouldUseNow( request_data )
    return self.ShouldUseNowInner( request_data )


  def ShouldUseNowInner( self, request_data ):
    if request_data[ 'force_semantic' ]:
      return True
    disabled_filetypes = self.user_options[
      'filetype_specific_completion_to_disable' ]
    if not vimsupport.CurrentFiletypesEnabled( disabled_filetypes ):
      return False
    return super( OmniCompleter, self ).ShouldUseNowInner( request_data )


  def ComputeCandidates( self, request_data ):
    if self.ShouldUseCache():
      return super( OmniCompleter, self ).ComputeCandidates( request_data )
    if self.ShouldUseNowInner( request_data ):
      return self.ComputeCandidatesInner( request_data )
    return []


  def ComputeCandidatesInner( self, request_data ):
    if not self._omnifunc:
      return []

    # Calling directly the omnifunc may move the cursor position. This is the
    # case with the default Vim omnifunc for C-family languages
    # (ccomplete#Complete) which calls searchdecl to find a declaration. This
    # function is supposed to move the cursor to the found declaration but it
    # doesn't when called through the omni completion mapping (CTRL-X CTRL-O).
    # So, we restore the cursor position after the omnifunc calls.
    line, column = vimsupport.CurrentLineAndColumn()

    try:
      start_column = vimsupport.GetIntValue( self._omnifunc + '(1,"")' )

      # Vim only stops completion if the value returned by the omnifunc is -3 or
      # -2. In other cases, if the value is negative or greater than the current
      # column, the start column is set to the current column; otherwise, the
      # value is used as the start column.
      if start_column in ( -3, -2 ):
        return []
      if start_column < 0 or start_column > column:
        start_column = column

      # Use the start column calculated by the omnifunc, rather than our own
      # interpretation. This is important for certain languages where our
      # identifier detection is either incorrect or not compatible with the
      # behaviour of the omnifunc. Note: do this before calling the omnifunc
      # because it affects the value returned by 'query'.
      request_data[ 'start_column' ] = start_column + 1

      # Vim internally moves the cursor to the start column before calling again
      # the omnifunc. Some omnifuncs like the one defined by the
      # LanguageClient-neovim plugin depend on this behavior to compute the list
      # of candidates.
      vimsupport.SetCurrentLineAndColumn( line, start_column )

      omnifunc_call = [ self._omnifunc,
                        "(0,'",
                        vimsupport.EscapeForVim( request_data[ 'query' ] ),
                        "')" ]
      items = vim.eval( ''.join( omnifunc_call ) )

      if isinstance( items, dict ) and 'words' in items:
        items = items[ 'words' ]

      if not hasattr( items, '__iter__' ):
        raise TypeError( OMNIFUNC_NOT_LIST )

      # Vim allows each item of the list to be either a string or a dictionary
      # but ycmd only supports lists where items are all strings or all
      # dictionaries. Convert all strings into dictionaries.
      for index, item in enumerate( items ):
        # Set the 'equal' field to 1 to disable Vim filtering.
        if not isinstance( item, dict ):
          items[ index ] = {
            'word': item,
            'equal': 1
          }
        else:
          item[ 'equal' ] = 1

      return items

    except ( TypeError, ValueError, vim.error ) as error:
      vimsupport.PostVimMessage(
        OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) )
      return []

    finally:
      vimsupport.SetCurrentLineAndColumn( line, column )


  def FilterAndSortCandidatesInner( self, candidates, sort_property, query ):
    request_data = {
      'candidates': candidates,
      'sort_property': sort_property,
      'query': query
    }

    response = BaseRequest().PostDataToHandler( request_data,
                                                'filter_and_sort_candidates' )
    return response if response is not None else []



File: python/ycm/scrolling_range.py

# Copyright (C) 2023, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import abc

from ycm import vimsupport


class ScrollingBufferRange( object ):
  """Abstraction used by inlay hints and semantic tokens to only request visible
  ranges"""

  # FIXME: Send a request per-disjoint range for this buffer rather than the
  # maximal range. then collaate the results when all responses are returned
  def __init__( self, bufnr ):
    self._bufnr = bufnr
    self._tick = -1
    self._request = None
    self._last_requested_range = None


  def Ready( self ):
    return self._request is not None and self._request.Done()


  def Request( self, force=False ):
    if self._request and not self.Ready():
      return True

    # Check to see if the buffer ranges would actually change anything visible.
    # This avoids a round-trip for every single line scroll event
    if ( not force and
         self._tick == vimsupport.GetBufferChangedTick( self._bufnr ) and
         vimsupport.VisibleRangeOfBufferOverlaps(
           self._bufnr,
           self._last_requested_range ) ):
      return False # don't poll

    # FIXME: This call is duplicated in the call to VisibleRangeOfBufferOverlaps
    #  - remove the expansion param
    #  - look up the actual visible range, then call this function
    #  - if not overlapping, do the factor expansion and request
    self._last_requested_range = vimsupport.RangeVisibleInBuffer( self._bufnr )
    # If this is false, either the self._bufnr is not a valid buffer number or
    # the buffer is not visible in any window.
    # Since this is called asynchronously, a user may bwipeout a buffer with
    # self._bufnr number between polls.
    if self._last_requested_range is None:
      return False

    self._tick = vimsupport.GetBufferChangedTick( self._bufnr )

    # We'll never use the last response again, so clear it
    self._latest_response = None
    self._request = self._NewRequest( self._last_requested_range )
    self._request.Start()
    return True


  def Update( self ):
    if not self._request:
      # Nothing to update
      return True

    assert self.Ready()

    # We're ready to use this response. Clear the request (to avoid repeatedly
    # re-polling).
    self._latest_response = self._request.Response()
    self._request = None

    if self._tick != vimsupport.GetBufferChangedTick( self._bufnr ):
      # Buffer has changed, we should ignore the data and retry
      self.Request( force=True )
      return False # poll again

    self._Draw()

    # No need to re-poll
    return True


  def Refresh( self ):
    if self._tick != vimsupport.GetBufferChangedTick( self._bufnr ):
      # stale data
      return

    if self._request is not None:
      # request in progress; we''l handle refreshing when it's done.
      return

    self._Draw()


  def GrowRangeIfNeeded( self, rng ):
    """When processing results, we may receive a wider range than requested. In
    that case, grow our 'last requested' range to minimise requesting more
    frequently than we need to."""
    # Note: references (pointers) so no need to re-assign
    rmin = self._last_requested_range[ 'start' ]
    rmax = self._last_requested_range[ 'end' ]

    start = rng[ 'start' ]
    end = rng[ 'end' ]

    if rmin[ 'line_num' ] is None or start[ 'line_num' ] < rmin[ 'line_num' ]:
      rmin[ 'line_num' ] = start[ 'line_num' ]
      rmin[ 'column_num' ] = start[ 'column_num' ]
    elif start[ 'line_num' ] == rmin[ 'line_num' ]:
      rmin[ 'column_num' ] = min( start[ 'column_num' ],
                                  rmin[ 'column_num' ] )

    if rmax[ 'line_num' ] is None or end[ 'line_num' ] > rmax[ 'line_num' ]:
      rmax[ 'line_num' ] = end[ 'line_num' ]
      rmax[ 'column_num' ] = end[ 'column_num' ]
    elif end[ 'line_num' ] == rmax[ 'line_num' ]:
      rmax[ 'column_num' ] = max( end[ 'column_num' ], rmax[ 'column_num' ] )


  # API; just implement the following, using self._bufnr and
  # self._latest_response as required

  @abc.abstractmethod
  def _NewRequest( self, request_range ):
    # prepare a new request_data and return it
    pass


  @abc.abstractmethod
  def _Draw( self ):
    # actuall paint the properties
    pass



File: python/ycm/client/event_notification.py

# Copyright (C) 2013-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import BaseRequest, BuildRequestData


class EventNotification( BaseRequest ):
  def __init__( self, event_name, buffer_number = None, extra_data = None ):
    super( EventNotification, self ).__init__()
    self._event_name = event_name
    self._buffer_number = buffer_number
    self._extra_data = extra_data
    self._response_future = None
    self._cached_response = None


  def Start( self ):
    request_data = BuildRequestData( self._buffer_number )
    if self._extra_data:
      request_data.update( self._extra_data )
    request_data[ 'event_name' ] = self._event_name

    self._response_future = self.PostDataToHandlerAsync( request_data,
                                                         'event_notification' )


  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def Response( self ):
    if self._cached_response:
      return self._cached_response

    if not self._response_future or self._event_name != 'FileReadyToParse':
      return []

    self._cached_response = self.HandleFuture( self._response_future,
                                               truncate_message = True )

    return self._cached_response if self._cached_response else []


def SendEventNotificationAsync( event_name,
                                buffer_number = None,
                                extra_data = None ):
  event = EventNotification( event_name, buffer_number, extra_data )
  event.Start()



File: python/ycm/client/ycmd_keepalive.py

# Copyright (C) 2013  Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import time
from threading import Thread
from ycm.client.base_request import BaseRequest


# This class can be used to keep the ycmd server alive for the duration of the
# life of the client. By default, ycmd shuts down if it doesn't see a request in
# a while.
class YcmdKeepalive:
  def __init__( self, ping_interval_seconds = 60 * 10 ):
    self._keepalive_thread = Thread( target = self._ThreadMain )
    self._keepalive_thread.daemon = True
    self._ping_interval_seconds = ping_interval_seconds


  def Start( self ):
    self._keepalive_thread.start()


  def _ThreadMain( self ):
    while True:
      time.sleep( self._ping_interval_seconds )

      BaseRequest().GetDataFromHandler( 'healthy', display_message = False )



File: python/ycm/client/debug_info_request.py

# Copyright (C) 2016-2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import BaseRequest, BuildRequestData


class DebugInfoRequest( BaseRequest ):
  def __init__( self, extra_data = None ):
    super( DebugInfoRequest, self ).__init__()
    self._extra_data = extra_data
    self._response = None


  def Start( self ):
    request_data = BuildRequestData()
    if self._extra_data:
      request_data.update( self._extra_data )
    self._response = self.PostDataToHandler( request_data,
                                             'debug_info',
                                             display_message = False )


  def Response( self ):
    return self._response


def FormatDebugInfoResponse( response ):
  if not response:
    return 'Server errored, no debug info from server\n'
  message = _FormatYcmdDebugInfo( response )
  completer = response[ 'completer' ]
  if completer:
    message += _FormatCompleterDebugInfo( completer )
  return message


def _FormatYcmdDebugInfo( ycmd ):
  python = ycmd[ 'python' ]
  clang = ycmd[ 'clang' ]
  message = (
    f'Server Python interpreter: { python[ "executable" ] }\n'
    f'Server Python version: { python[ "version" ] }\n'
    f'Server has Clang support compiled in: { clang[ "has_support" ] }\n'
    f'Clang version: { clang[ "version" ] }\n' )
  extra_conf = ycmd[ 'extra_conf' ]
  extra_conf_path = extra_conf[ 'path' ]
  if not extra_conf_path:
    message += 'No extra configuration file found\n'
  elif not extra_conf[ 'is_loaded' ]:
    message += ( 'Extra configuration file found but not loaded\n'
                 f'Extra configuration path: { extra_conf_path }\n' )
  else:
    message += ( 'Extra configuration file found and loaded\n'
                 f'Extra configuration path: { extra_conf_path }\n' )
  return message


def _FormatCompleterDebugInfo( completer ):
  message = f'{ completer[ "name" ] } completer debug information:\n'
  for server in completer[ 'servers' ]:
    name = server[ 'name' ]
    if server[ 'is_running' ]:
      address = server[ 'address' ]
      port = server[ 'port' ]
      if address and port:
        message += f'  { name } running at: http://{ address }:{ port }\n'
      else:
        message += f'  { name } running\n'
      message += f'  { name } process ID: { server[ "pid" ] }\n'
    else:
      message += f'  { name } not running\n'
    message += f'  { name } executable: { server[ "executable" ] }\n'
    logfiles = server[ 'logfiles' ]
    if logfiles:
      message += f'  { name } logfiles:\n'
      for logfile in logfiles:
        message += f'    { logfile }\n'
    else:
      message += '  No logfiles available\n'
    if 'extras' in server:
      for extra in server[ 'extras' ]:
        message += f'  { name } { extra[ "key" ] }: { extra[ "value" ] }\n'
  for item in completer[ 'items' ]:
    message += f'  { item[ "key" ].capitalize() }: { item[ "value" ] }\n'
  return message


def SendDebugInfoRequest( extra_data = None ):
  request = DebugInfoRequest( extra_data )
  # This is a blocking call.
  request.Start()
  return request.Response()



File: python/ycm/client/shutdown_request.py

# Copyright (C) 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import BaseRequest

TIMEOUT_SECONDS = 0.1


class ShutdownRequest( BaseRequest ):
  def __init__( self ):
    super( ShutdownRequest, self ).__init__()


  def Start( self ):
    self.PostDataToHandler( {},
                            'shutdown',
                            TIMEOUT_SECONDS,
                            display_message = False )


def SendShutdownRequest():
  request = ShutdownRequest()
  # This is a blocking call.
  request.Start()



File: python/ycm/client/__init__.py




File: python/ycm/client/command_request.py

# Copyright (C) 2013  Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import ( BaseRequest,
                                      BuildRequestData,
                                      BuildRequestDataForLocation )
from ycm import vimsupport

DEFAULT_BUFFER_COMMAND = 'same-buffer'


def _EnsureBackwardsCompatibility( arguments ):
  if arguments and arguments[ 0 ] == 'GoToDefinitionElseDeclaration':
    arguments[ 0 ] = 'GoTo'
  return arguments


class CommandRequest( BaseRequest ):
  def __init__( self,
                arguments,
                extra_data = None,
                silent = False,
                location = None ):
    super( CommandRequest, self ).__init__()
    self._arguments = _EnsureBackwardsCompatibility( arguments )
    self._command = arguments and arguments[ 0 ]
    self._extra_data = extra_data
    self._response = None
    self._request_data = None
    self._response_future = None
    self._silent = silent
    self._bufnr = extra_data.pop( 'bufnr', None ) if extra_data else None
    self._location = location


  def Start( self ):
    if self._location is not None:
      self._request_data = BuildRequestDataForLocation( *self._location )
    elif self._bufnr is not None:
      self._request_data = BuildRequestData( self._bufnr )
    else:
      self._request_data = BuildRequestData()

    if self._extra_data:
      self._request_data.update( self._extra_data )
    self._request_data.update( {
      'command_arguments': self._arguments
    } )
    self._response_future = self.PostDataToHandlerAsync(
      self._request_data,
      'run_completer_command' )


  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def Response( self ):
    if self._response is None and self._response_future is not None:
      # Block
      self._response = self.HandleFuture( self._response_future,
                                          display_message = not self._silent )

    return self._response


  def RunPostCommandActionsIfNeeded( self,
                                     modifiers,
                                     buffer_command = DEFAULT_BUFFER_COMMAND ):

    # This is a blocking call if not Done()
    self.Response()

    if self._response is None:
      # An exception was raised and handled.
      return

    # If not a dictionary or a list, the response is necessarily a
    # scalar: boolean, number, string, etc. In this case, we print
    # it to the user.
    if not isinstance( self._response, ( dict, list ) ):
      return self._HandleBasicResponse()

    if 'fixits' in self._response:
      return self._HandleFixitResponse()

    if 'message' in self._response:
      return self._HandleMessageResponse()

    if 'detailed_info' in self._response:
      return self._HandleDetailedInfoResponse( modifiers )

    # The only other type of response we understand is GoTo, and that is the
    # only one that we can't detect just by inspecting the response (it should
    # either be a single location or a list)
    return self._HandleGotoResponse( buffer_command, modifiers )


  def StringResponse( self ):
    # Retuns a supporable public API version of the response. The reason this
    # exists is that the ycmd API here is wonky as it originally only supported
    # text-responses and now has things like fixits and such.
    #
    # The supportable public API is basically any text-only response. All other
    # response types are returned as empty strings

    # This is a blocking call if not Done()
    self.Response()

    # Completer threw an error ?
    if self._response is None:
      return ""

    # If not a dictionary or a list, the response is necessarily a
    # scalar: boolean, number, string, etc. In this case, we print
    # it to the user.
    if not isinstance( self._response, ( dict, list ) ):
      return str( self._response )

    if 'message' in self._response:
      return self._response[ 'message' ]

    if 'detailed_info' in self._response:
      return self._response[ 'detailed_info' ]

    # The only other type of response we understand is 'fixits' and GoTo. We
    # don't provide string versions of them.
    return ""


  def _HandleGotoResponse( self, buffer_command, modifiers ):
    if isinstance( self._response, list ):
      vimsupport.SetQuickFixList(
        [ vimsupport.BuildQfListItem( x ) for x in self._response ] )
      vimsupport.OpenQuickFixList( focus = True, autoclose = True )
    elif self._response.get( 'file_only' ):
      vimsupport.JumpToLocation( self._response[ 'filepath' ],
                                 None,
                                 None,
                                 modifiers,
                                 buffer_command )
    else:
      vimsupport.JumpToLocation( self._response[ 'filepath' ],
                                 self._response[ 'line_num' ],
                                 self._response[ 'column_num' ],
                                 modifiers,
                                 buffer_command )


  def _HandleFixitResponse( self ):
    if not len( self._response[ 'fixits' ] ):
      vimsupport.PostVimMessage( 'No fixits found for current line',
                                 warning = False )
    else:
      try:
        fixit_index = 0

        # If there is more than one fixit, we need to ask the user which one
        # should be applied.
        #
        # If there's only one, triggered by the FixIt subcommand (as opposed to
        # `RefactorRename`, for example) and whose `kind` is not `quicfix`, we
        # still need to as the user for confirmation.
        fixits = self._response[ 'fixits' ]
        if ( len( fixits ) > 1 or
             ( len( fixits ) == 1 and
               self._command == 'FixIt' and
               fixits[ 0 ].get( 'kind' ) != 'quickfix' ) ):
          fixit_index = vimsupport.SelectFromList(
            "FixIt suggestion(s) available at this location. "
            "Which one would you like to apply?",
            [ fixit[ 'text' ] for fixit in fixits ] )
        chosen_fixit = fixits[ fixit_index ]
        if chosen_fixit[ 'resolve' ]:
          self._request_data.update( { 'fixit': chosen_fixit } )
          response = self.PostDataToHandler( self._request_data,
                                             'resolve_fixit' )
          if response is None:
            return
          fixits = response[ 'fixits' ]
          assert len( fixits ) == 1
          chosen_fixit = fixits[ 0 ]

        vimsupport.ReplaceChunks(
          chosen_fixit[ 'chunks' ],
          silent = self._command == 'Format' )
      except RuntimeError as e:
        vimsupport.PostVimMessage( str( e ) )


  def _HandleBasicResponse( self ):
    vimsupport.PostVimMessage( self._response, warning = False )


  def _HandleMessageResponse( self ):
    vimsupport.PostVimMessage( self._response[ 'message' ], warning = False )


  def _HandleDetailedInfoResponse( self, modifiers ):
    vimsupport.WriteToPreviewWindow( self._response[ 'detailed_info' ],
                                     modifiers )


def SendCommandRequestAsync( arguments,
                             extra_data = None,
                             silent = True,
                             location = None ):
  request = CommandRequest( arguments,
                            extra_data = extra_data,
                            silent = silent,
                            location = location )
  request.Start()
  # Don't block
  return request


def SendCommandRequest( arguments,
                        modifiers,
                        buffer_command = DEFAULT_BUFFER_COMMAND,
                        extra_data = None,
                        skip_post_command_action = False ):
  request = SendCommandRequestAsync( arguments,
                                     extra_data = extra_data,
                                     silent = False )
  # Block here to get the response
  if not skip_post_command_action:
    request.RunPostCommandActionsIfNeeded( modifiers, buffer_command )
  return request.Response()


def GetCommandResponse( arguments, extra_data = None ):
  request = SendCommandRequestAsync( arguments,
                                     extra_data = extra_data,
                                     silent = True )
  # Block here to get the response
  return request.StringResponse()


def GetRawCommandResponse( arguments, silent, location = None ):
  request = SendCommandRequestAsync( arguments,
                                     extra_data = None,
                                     silent = silent,
                                     location = location )
  return request.Response()



File: python/ycm/client/inlay_hints_request.py

# Copyright (C) 2022, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.


import logging
from ycm.client.base_request import ( BaseRequest, DisplayServerException,
                                      MakeServerException )

_logger = logging.getLogger( __name__ )


# FIXME: This is copy/pasta from SemanticTokensRequest - abstract a
# SimpleAsyncRequest base that does all of this generically
class InlayHintsRequest( BaseRequest ):
  def __init__( self, request_data ):
    super().__init__()
    self.request_data = request_data
    self._response_future = None


  def Start( self ):
    self._response_future = self.PostDataToHandlerAsync( self.request_data,
                                                         'inlay_hints' )

  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def Reset( self ):
    self._response_future = None

  def Response( self ):
    if not self._response_future:
      return []

    response = self.HandleFuture( self._response_future,
                                  truncate_message = True )

    if not response:
      return []

    # Vim may not be able to convert the 'errors' entry to its internal format
    # so we remove it from the response.
    errors = response.pop( 'errors', [] )
    for e in errors:
      exception = MakeServerException( e )
      _logger.error( exception )
      DisplayServerException( exception, truncate_message = True )

    return response.get( 'inlay_hints' ) or []



File: python/ycm/client/completion_request.py

# Copyright (C) 2013-2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import json
import logging
from ycmd.utils import ToUnicode
from ycm.client.base_request import ( BaseRequest,
                                      DisplayServerException,
                                      MakeServerException )
from ycm import vimsupport, base
from ycm.vimsupport import NO_COMPLETIONS

_logger = logging.getLogger( __name__ )


class CompletionRequest( BaseRequest ):
  def __init__( self, request_data ):
    super().__init__()
    self.request_data = request_data
    self._response_future = None


  def Start( self ):
    self._response_future = self.PostDataToHandlerAsync( self.request_data,
                                                         'completions' )


  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def _RawResponse( self ):
    if not self._response_future:
      return NO_COMPLETIONS

    response = self.HandleFuture( self._response_future,
                                  truncate_message = True )
    if not response:
      return NO_COMPLETIONS

    # Vim may not be able to convert the 'errors' entry to its internal format
    # so we remove it from the response.
    errors = response.pop( 'errors', [] )
    for e in errors:
      exception = MakeServerException( e )
      _logger.error( exception )
      DisplayServerException( exception, truncate_message = True )

    response[ 'line' ] = self.request_data[ 'line_num' ]
    response[ 'column' ] = self.request_data[ 'column_num' ]
    return response


  def Response( self ):
    response = self._RawResponse()
    response[ 'completions' ] = _ConvertCompletionDatasToVimDatas(
        response[ 'completions' ] )
    # FIXME: Do we really need to do this AdjustCandidateInsertionText ? I feel
    # like Vim should do that for us
    response[ 'completions' ] = base.AdjustCandidateInsertionText(
        response[ 'completions' ] )
    return response


  def OnCompleteDone( self ):
    if not self.Done():
      return

    if 'cs' in vimsupport.CurrentFiletypes():
      self._OnCompleteDone_Csharp()
    else:
      self._OnCompleteDone_FixIt()


  def _GetExtraDataUserMayHaveCompleted( self ):
    completed_item = vimsupport.GetVariableValue( 'v:completed_item' )

    # If Vim supports user_data (8.0.1493 or later), we actually know the
    # _exact_ element that was selected, having put its extra_data in the
    # user_data field. Otherwise, we have to guess by matching the values in the
    # completed item and the list of completions. Sometimes this returns
    # multiple possibilities, which is essentially unresolvable.
    if 'user_data' not in completed_item:
      completions = self._RawResponse()[ 'completions' ]
      return _FilterToMatchingCompletions( completed_item, completions )

    if completed_item[ 'user_data' ]:
      return [ json.loads( completed_item[ 'user_data' ] ) ]

    return []


  def _OnCompleteDone_Csharp( self ):
    extra_datas = self._GetExtraDataUserMayHaveCompleted()
    namespaces = [ _GetRequiredNamespaceImport( c ) for c in extra_datas ]
    namespaces = [ n for n in namespaces if n ]
    if not namespaces:
      return

    if len( namespaces ) > 1:
      choices = [ f"{ i + 1 } { n }" for i, n in enumerate( namespaces ) ]
      choice = vimsupport.PresentDialog( "Insert which namespace:", choices )
      if choice < 0:
        return
      namespace = namespaces[ choice ]
    else:
      namespace = namespaces[ 0 ]

    vimsupport.InsertNamespace( namespace )


  def _OnCompleteDone_FixIt( self ):
    extra_datas = self._GetExtraDataUserMayHaveCompleted()
    fixit_completions = [ _GetFixItCompletion( c ) for c in extra_datas ]
    fixit_completions = [ f for f in fixit_completions if f ]
    if not fixit_completions:
      return

    # If we have user_data in completions (8.0.1493 or later), then we would
    # only ever return max. 1 completion here. However, if we had to guess, it
    # is possible that we matched multiple completion items (e.g. for overloads,
    # or similar classes in multiple packages). In any case, rather than
    # prompting the user and disturbing her workflow, we just apply the first
    # one. This might be wrong, but the solution is to use a (very) new version
    # of Vim which supports user_data on completion items
    fixit_completion = fixit_completions[ 0 ]

    for fixit in fixit_completion:
      vimsupport.ReplaceChunks( fixit[ 'chunks' ], silent=True )


def _GetRequiredNamespaceImport( extra_data ):
  return extra_data.get( 'required_namespace_import' )


def _GetFixItCompletion( extra_data ):
  return extra_data.get( 'fixits' )


def _FilterToMatchingCompletions( completed_item, completions ):
  """Filter to completions matching the item Vim said was completed"""
  match_keys = [ 'word', 'abbr', 'menu', 'info' ]
  matched_completions = []
  for completion in completions:
    item = ConvertCompletionDataToVimData( completion )

    def matcher( key ):
      return ( ToUnicode( completed_item.get( key, "" ) ) ==
               ToUnicode( item.get( key, "" ) ) )

    if all( matcher( i ) for i in match_keys ):
      matched_completions.append( completion.get( 'extra_data', {} ) )
  return matched_completions


def _GetCompletionInfoField( completion_data ):
  info = completion_data.get( 'detailed_info', '' )

  if 'extra_data' in completion_data:
    docstring = completion_data[ 'extra_data' ].get( 'doc_string', '' )
    if docstring:
      if info:
        info += '\n' + docstring
      else:
        info = docstring

  # This field may contain null characters e.g. \x00 in Python docstrings. Vim
  # cannot evaluate such characters so they are removed.
  return info.replace( '\x00', '' )


def ConvertCompletionDataToVimData( completion_data ):
  # See :h complete-items for a description of the dictionary fields.
  extra_menu_info = completion_data.get( 'extra_menu_info', '' )
  preview_info = _GetCompletionInfoField( completion_data )

  # When we are using a popup for the preview_info, it needs to fit on the
  # screen alongside the extra_menu_info. Let's use some heuristics.  If the
  # length of the extra_menu_info is more than, say, 1/3 of screen, truncate it
  # and stick it in the preview_info.
  if vimsupport.UsingPreviewPopup():
    max_width = max( int( vimsupport.DisplayWidth() / 3 ), 3 )
    extra_menu_info_width = vimsupport.DisplayWidthOfString( extra_menu_info )
    if extra_menu_info_width > max_width:
      if not preview_info.startswith( extra_menu_info ):
        preview_info = extra_menu_info + '\n\n' + preview_info
      extra_menu_info = extra_menu_info[ : ( max_width - 3 ) ] + '...'

  return {
    'word'     : completion_data[ 'insertion_text' ],
    'abbr'     : completion_data.get( 'menu_text', '' ),
    'menu'     : extra_menu_info,
    'info'     : preview_info,
    'kind'     : ToUnicode( completion_data.get( 'kind', '' ) )[ :1 ].lower(),
    # Disable Vim filtering.
    'equal'    : 1,
    'dup'      : 1,
    'empty'    : 1,
    # We store the completion item extra_data as a string in the completion
    # user_data. This allows us to identify the _exact_ item that was completed
    # in the CompleteDone handler, by inspecting this item from v:completed_item
    #
    # We convert to string because completion user data items must be strings.
    #
    # Note: Not all versions of Vim support this (added in 8.0.1483), but adding
    # the item to the dictionary is harmless in earlier Vims.
    # Note: Since 8.2.0084 we don't need to use json.dumps() here.
    'user_data': json.dumps( completion_data.get( 'extra_data', {} ) )
  }


def _ConvertCompletionDatasToVimDatas( response_data ):
  return [ ConvertCompletionDataToVimData( x ) for x in response_data ]



File: python/ycm/client/omni_completion_request.py

# Copyright (C) 2013  Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.completion_request import CompletionRequest


class OmniCompletionRequest( CompletionRequest ):
  def __init__( self, omni_completer, request_data ):
    super( OmniCompletionRequest, self ).__init__( request_data )
    self._omni_completer = omni_completer


  def Start( self ):
    self._results = self._omni_completer.ComputeCandidates( self.request_data )


  def Done( self ):
    return True


  def Response( self ):
    return {
      'line': self.request_data[ 'line_num' ],
      'column': self.request_data[ 'column_num' ],
      'completion_start_column': self.request_data[ 'start_column' ],
      'completions': self._results
    }


  def OnCompleteDone( self ):
    pass



File: python/ycm/client/messages_request.py

# Copyright (C) 2017 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import BaseRequest, BuildRequestData
from ycm.vimsupport import PostVimMessage

import logging

_logger = logging.getLogger( __name__ )

# Looooong poll
TIMEOUT_SECONDS = 60


class MessagesPoll( BaseRequest ):
  def __init__( self, buff ):
    super( MessagesPoll, self ).__init__()
    self._request_data = BuildRequestData( buff.number )
    self._response_future = None


  def _SendRequest( self ):
    self._response_future = self.PostDataToHandlerAsync(
      self._request_data,
      'receive_messages',
      timeout = TIMEOUT_SECONDS )
    return


  def Poll( self, diagnostics_handler ):
    """This should be called regularly to check for new messages in this buffer.
    Returns True if Poll should be called again in a while. Returns False when
    the completer or server indicated that further polling should not be done
    for the requested file."""

    if self._response_future is None:
      # First poll
      self._SendRequest()
      return True

    if not self._response_future.done():
      # Nothing yet...
      return True

    response = self.HandleFuture( self._response_future,
                                  display_message = False )
    if response is None:
      # Server returned an exception.
      return False

    poll_again = _HandlePollResponse( response, diagnostics_handler )
    if poll_again:
      self._SendRequest()
      return True

    return False


def _HandlePollResponse( response, diagnostics_handler ):
  if isinstance( response, list ):
    for notification in response:
      if 'message' in notification:
        PostVimMessage( notification[ 'message' ],
                        warning = False,
                        truncate = True )
      elif 'diagnostics' in notification:
        diagnostics_handler.UpdateWithNewDiagnosticsForFile(
          notification[ 'filepath' ],
          notification[ 'diagnostics' ] )
  elif response is False:
    # Don't keep polling for this file
    return False
  # else any truthy response means "nothing to see here; poll again in a
  # while"

  # Start the next poll (only if the last poll didn't raise an exception)
  return True



File: python/ycm/client/signature_help_request.py

# Copyright (C) 2019 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import logging
from ycm.client.base_request import ( BaseRequest, DisplayServerException,
                                      MakeServerException )

_logger = logging.getLogger( __name__ )


class SigHelpAvailableByFileType( dict ):
  def __missing__( self, filetype ):
    request = SignatureHelpAvailableRequest( filetype )
    self[ filetype ] = request
    return request


class SignatureHelpRequest( BaseRequest ):
  def __init__( self, request_data ):
    super( SignatureHelpRequest, self ).__init__()
    self.request_data = request_data
    self._response_future = None
    self._response = None


  def Start( self ):
    self._response_future = self.PostDataToHandlerAsync( self.request_data,
                                                         'signature_help' )


  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def Reset( self ):
    self._response_future = None


  def Response( self ):
    if self._response is None:
      self._response = self._Response()
    return self._response


  def _Response( self ):
    if not self._response_future:
      return {}

    response = self.HandleFuture( self._response_future,
                                  truncate_message = True )
    if not response:
      return {}

    # Vim may not be able to convert the 'errors' entry to its internal format
    # so we remove it from the response.
    errors = response.pop( 'errors', [] )
    for e in errors:
      exception = MakeServerException( e )
      _logger.error( exception )
      DisplayServerException( exception, truncate_message = True )

    return response.get( 'signature_help' ) or {}


class SignatureHelpAvailableRequest( BaseRequest ):
  def __init__( self, filetype ):
    super( SignatureHelpAvailableRequest, self ).__init__()
    self._response_future = None
    self.Start( filetype )


  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def Response( self ):
    if not self._response_future:
      return None

    response = self.HandleFuture( self._response_future,
                                  truncate_message = True )

    if not response:
      return None

    return response[ 'available' ]


  def Start( self, filetype ):
    self._response_future = self.GetDataFromHandlerAsync(
      'signature_help_available',
      payload = { 'subserver': filetype } )



File: python/ycm/client/completer_available_request.py

# Copyright (C) 2013  Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import BaseRequest, BuildRequestData


class CompleterAvailableRequest( BaseRequest ):
  def __init__( self, filetypes ):
    super( CompleterAvailableRequest, self ).__init__()
    self.filetypes = filetypes
    self._response = None


  def Start( self ):
    request_data = BuildRequestData()
    request_data.update( { 'filetypes': self.filetypes } )
    self._response = self.PostDataToHandler( request_data,
                                             'semantic_completion_available' )


  def Response( self ):
    return self._response


def SendCompleterAvailableRequest( filetypes ):
  request = CompleterAvailableRequest( filetypes )
  # This is a blocking call.
  request.Start()
  return request.Response()



File: python/ycm/client/resolve_completion_request.py

# Copyright (C) 2020 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

from ycm.client.base_request import ( BaseRequest,
                                      DisplayServerException,
                                      MakeServerException )
from ycm.client.completion_request import ( CompletionRequest,
                                            ConvertCompletionDataToVimData )

import logging
import json
_logger = logging.getLogger( __name__ )


class ResolveCompletionRequest( BaseRequest ):
  def __init__( self,
                completion_request: CompletionRequest,
                request_data ):
    super().__init__()
    self.request_data = request_data
    self.completion_request = completion_request

  def Start( self ):
    self._response_future = self.PostDataToHandlerAsync( self.request_data,
                                                         'resolve_completion' )

  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def OnCompleteDone( self ):
    # This is required to be compatible with the "CompletionRequest" API. We're
    # not really a CompletionRequest, but we are mutually exclusive with
    # completion requests, so we implement this API by delegating to the
    # original completion request, which contains all of the code for actually
    # handling things like automatic imports etc.
    self.completion_request.OnCompleteDone()


  def Response( self ):
    response = self.HandleFuture( self._response_future,
                                  truncate_message = True,
                                  display_message = True )

    if not response or not response[ 'completion' ]:
      return { 'completion': [] }

    # Vim may not be able to convert the 'errors' entry to its internal format
    # so we remove it from the response.
    errors = response.pop( 'errors', [] )
    for e in errors:
      exception = MakeServerException( e )
      _logger.error( exception )
      DisplayServerException( exception, truncate_message = True )

    response[ 'completion' ] = ConvertCompletionDataToVimData(
        response[ 'completion' ] )
    return response


def ResolveCompletionItem( completion_request, item ):
  if not completion_request.Done():
    return None
  try:
    completion_extra_data = json.loads( item[ 'user_data' ] )
  except KeyError:
    return None
  except ( TypeError, json.JSONDecodeError ):
    # Can happen with the omni completer
    return None

  request_data = completion_request.request_data
  try:
    # Note: We mutate the request_data inside the original completion request
    # and pass it into the new request object. this is just a big efficiency
    # saving. The request_data for a Done() request is almost certainly no
    # longer needed.
    request_data[ 'resolve' ] = completion_extra_data[ 'resolve' ]
  except KeyError:
    return None

  resolve_request = ResolveCompletionRequest( completion_request, request_data )
  resolve_request.Start()
  return resolve_request



File: python/ycm/client/semantic_tokens_request.py

# Copyright (C) 2020, YouCompleteMe Contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.


import logging
from ycm.client.base_request import ( BaseRequest, DisplayServerException,
                                      MakeServerException )

_logger = logging.getLogger( __name__ )


# FIXME: This is copy/pasta from SignatureHelpRequest - abstract a
# SimpleAsyncRequest base that does all of this generically
class SemanticTokensRequest( BaseRequest ):
  def __init__( self, request_data ):
    super().__init__()
    self.request_data = request_data
    self._response_future = None


  def Start( self ):
    self._response_future = self.PostDataToHandlerAsync( self.request_data,
                                                         'semantic_tokens' )

  def Done( self ):
    return bool( self._response_future ) and self._response_future.done()


  def Reset( self ):
    self._response_future = None

  def Response( self ):
    if not self._response_future:
      return {}

    response = self.HandleFuture( self._response_future,
                                  truncate_message = True )

    if not response:
      return {}

    # Vim may not be able to convert the 'errors' entry to its internal format
    # so we remove it from the response.
    errors = response.pop( 'errors', [] )
    for e in errors:
      exception = MakeServerException( e )
      _logger.error( exception )
      DisplayServerException( exception, truncate_message = True )

    return response.get( 'semantic_tokens' ) or {}



File: python/ycm/client/base_request.py

# Copyright (C) 2013-2018 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# YouCompleteMe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import logging
import json
import vim
from base64 import b64decode, b64encode
from hmac import compare_digest
from urllib.parse import urljoin, urlparse, urlencode
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from ycm import vimsupport
from ycmd.utils import ToBytes, GetCurrentDirectory, ToUnicode
from ycmd.hmac_utils import CreateRequestHmac, CreateHmac
from ycmd.responses import ServerError, UnknownExtraConf

HTTP_SERVER_ERROR = 500

_HEADERS = { 'content-type': 'application/json' }
_CONNECT_TIMEOUT_SEC = 0.01
# Setting this to None seems to screw up the Requests/urllib3 libs.
_READ_TIMEOUT_SEC = 30
_HMAC_HEADER = 'x-ycm-hmac'
_logger = logging.getLogger( __name__ )


class BaseRequest:

  def __init__( self ):
    self._should_resend = False


  def Start( self ):
    pass


  def Done( self ):
    return True


  def Response( self ):
    return {}


  def ShouldResend( self ):
    return self._should_resend


  def HandleFuture( self,
                    future,
                    display_message = True,
                    truncate_message = False ):
    """Get the server response from a |future| object and catch any exception
    while doing so. If an exception is raised because of a unknown
    .ycm_extra_conf.py file, load the file or ignore it after asking the user.
    An identical request should be sent again to the server. For other
    exceptions, log the exception and display its message to the user on the Vim
    status line. Unset the |display_message| parameter to hide the message from
    the user. Set the |truncate_message| parameter to avoid hit-enter prompts
    from this message."""
    try:
      try:
        return _JsonFromFuture( future )
      except UnknownExtraConf as e:
        if vimsupport.Confirm( str( e ) ):
          _LoadExtraConfFile( e.extra_conf_file )
        else:
          _IgnoreExtraConfFile( e.extra_conf_file )
        self._should_resend = True
    except URLError as e:
      # We don't display this exception to the user since it is likely to happen
      # for each subsequent request (typically if the server crashed) and we
      # don't want to spam the user with it.
      _logger.error( e )

    except Exception as e:
      _logger.exception( 'Error while handling server response' )
      if display_message:
        DisplayServerException( e, truncate_message )

    return None


  # This method blocks
  # |timeout| is num seconds to tolerate no response from server before giving
  # up; see Requests docs for details (we just pass the param along).
  # See the HandleFuture method for the |display_message| and |truncate_message|
  # parameters.
  def GetDataFromHandler( self,
                          handler,
                          timeout = _READ_TIMEOUT_SEC,
                          display_message = True,
                          truncate_message = False,
                          payload = None ):
    return self.HandleFuture(
        self.GetDataFromHandlerAsync( handler, timeout, payload ),
        display_message,
        truncate_message )


  def GetDataFromHandlerAsync( self,
                               handler,
                               timeout = _READ_TIMEOUT_SEC,
                               payload = None ):
    return BaseRequest._TalkToHandlerAsync(
        '', handler, 'GET', timeout, payload )


  # This is the blocking version of the method. See below for async.
  # |timeout| is num seconds to tolerate no response from server before giving
  # up; see Requests docs for details (we just pass the param along).
  # See the HandleFuture method for the |display_message| and |truncate_message|
  # parameters.
  def PostDataToHandler( self,
                         data,
                         handler,
                         timeout = _READ_TIMEOUT_SEC,
                         display_message = True,
                         truncate_message = False ):
    return self.HandleFuture(
        BaseRequest.PostDataToHandlerAsync( data, handler, timeout ),
        display_message,
        truncate_message )


  # This returns a future! Use HandleFuture to get the value.
  # |timeout| is num seconds to tolerate no response from server before giving
  # up; see Requests docs for details (we just pass the param along).
  @staticmethod
  def PostDataToHandlerAsync( data, handler, timeout = _READ_TIMEOUT_SEC ):
    return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout )


  # This returns a future! Use HandleFuture to get the value.
  # |method| is either 'POST' or 'GET'.
  # |timeout| is num seconds to tolerate no response from server before giving
  # up; see Requests docs for details (we just pass the param along).
  @staticmethod
  def _TalkToHandlerAsync( data,
                           handler,
                           method,
                           timeout = _READ_TIMEOUT_SEC,
                           payload = None ):
    def _MakeRequest( data, handler, method, timeout, payload ):
      request_uri = _BuildUri( handler )

      if method == 'POST':
        sent_data = _ToUtf8Json( data )
        headers = BaseRequest._ExtraHeaders( method,
                                             request_uri,
                                             sent_data )
        _logger.debug( 'POST %s\n%s\n%s', request_uri, headers, sent_data )
      else:
        headers = BaseRequest._ExtraHeaders( method, request_uri )
        if payload:
          request_uri += ToBytes( f'?{ urlencode( payload ) }' )

        _logger.debug( 'GET %s (%s)\n%s', request_uri, payload, headers )
      return urlopen(
        Request(
          ToUnicode( request_uri ),
          data = sent_data if data else None,
          headers = headers,
          method = method ),
        timeout = max( _CONNECT_TIMEOUT_SEC, timeout ) )


    return BaseRequest.Executor().submit(
      _MakeRequest,
      data,
      handler,
      method,
      timeout,
      payload )


  @staticmethod
  def _ExtraHeaders( method, request_uri, request_body = None ):
    if not request_body:
      request_body = bytes( b'' )
    headers = dict( _HEADERS )
    headers[ _HMAC_HEADER ] = b64encode(
        CreateRequestHmac( ToBytes( method ),
                           ToBytes( urlparse( request_uri ).path ),
                           request_body,
                           BaseRequest.hmac_secret ) )
    return headers


  # This method exists to avoid importing the requests module at startup;
  # reducing loading time since this module is slow to import.
  @classmethod
  def Executor( cls ):
    try:
      return cls.executor
    except AttributeError:
      from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor
      cls.executor = UnsafeThreadPoolExecutor( max_workers = 30 )
      return cls.executor


  server_location = ''
  hmac_secret = ''


def BuildRequestData( buffer_number = None ):
  """Build request for the current buffer or the buffer with number
  |buffer_number| if specified."""
  working_dir = GetCurrentDirectory()
  current_buffer = vim.current.buffer

  if buffer_number and current_buffer.number != buffer_number:
    # Cursor position is irrelevant when filepath is not the current buffer.
    buffer_object = vim.buffers[ buffer_number ]
    filepath = vimsupport.GetBufferFilepath( buffer_object )
    return {
      'filepath': filepath,
      'line_num': 1,
      'column_num': 1,
      'working_dir': working_dir,
      'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( buffer_object,
                                                                filepath )
    }

  current_filepath = vimsupport.GetBufferFilepath( current_buffer )
  line, column = vimsupport.CurrentLineAndColumn()

  return {
    'filepath': current_filepath,
    'line_num': line + 1,
    'column_num': column + 1,
    'working_dir': working_dir,
    'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_buffer,
                                                              current_filepath )
  }


def BuildRequestDataForLocation( file : str, line : int, column : int ):
  buffer_number = vimsupport.GetBufferNumberForFilename(
      file,
      create_buffer_if_needed = True )
  try:
    vim.eval( f'bufload( "{ file }" )' )
  except vim.error as e:
    if 'E325' not in str( e ):
      raise
  buffer = vim.buffers[ buffer_number ]
  file_data = vimsupport.GetUnsavedAndSpecifiedBufferData( buffer, file )
  return {
    'filepath': file,
    'line_num': line,
    'column_num': column,
    'working_dir': GetCurrentDirectory(),
    'file_data': file_data
  }


def _JsonFromFuture( future ):
  try:
    response = future.result()
    response_text = response.read()
    _ValidateResponseObject( response, response_text )
    response.close()

    if response_text:
      return json.loads( response_text )
    return None
  except HTTPError as response:
    if response.code == HTTP_SERVER_ERROR:
      response_text = response.read()
      response.close()
      if response_text:
        raise MakeServerException( json.loads( response_text ) )
      else:
        return None
    raise


def _LoadExtraConfFile( filepath ):
  BaseRequest().PostDataToHandler( { 'filepath': filepath },
                                   'load_extra_conf_file' )


def _IgnoreExtraConfFile( filepath ):
  BaseRequest().PostDataToHandler( { 'filepath': filepath },
                                   'ignore_extra_conf_file' )


def DisplayServerException( exception, truncate_message = False ):
  serialized_exception = str( exception )

  # We ignore the exception about the file already being parsed since it comes
  # up often and isn't something that's actionable by the user.
  if 'already being parsed' in serialized_exception:
    return
  vimsupport.PostVimMessage( serialized_exception, truncate = truncate_message )


def _ToUtf8Json( data ):
  return ToBytes( json.dumps( data ) if data else None )


def _ValidateResponseObject( response, response_text ):
  if not response_text:
    return
  our_hmac = CreateHmac( response_text, BaseRequest.hmac_secret )
  their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
  if not compare_digest( our_hmac, their_hmac ):
    raise RuntimeError( 'Received invalid HMAC for response!' )


def _BuildUri( handler ):
  return ToBytes( urljoin( BaseRequest.server_location, handler ) )


def MakeServerException( data ):
  _logger.debug( 'Server exception: %s', data )
  if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__:
    return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] )

  return ServerError( f'{ data[ "exception" ][ "TYPE" ] }: '
                      f'{ data[ "message" ] }' )



YouCompleteMe: a code-completion engine for Vim
===============================================

[![Gitter room](https://img.shields.io/gitter/room/Valloric/YouCompleteMe.svg)](https://gitter.im/Valloric/YouCompleteMe)
[![Build status](https://dev.azure.com/YouCompleteMe/YCM/_apis/build/status/ycm-core.YouCompleteMe?branchName=master)](https://dev.azure.com/YouCompleteMe/YCM/_build?definitionId=3&branchName=master)
[![Coverage status](https://img.shields.io/codecov/c/github/ycm-core/YouCompleteMe/master.svg)](https://codecov.io/gh/ycm-core/YouCompleteMe)

Help, Advice, Support
---------------------

Looking for help, advice, or support? Having problems getting YCM to work?

First carefully read the [installation instructions](#installation) for your OS.
We recommend you use the supplied `install.py` - the "full" installation guide
is for rare, advanced use cases and most users should use `install.py`.

If the server isn't starting and you're getting a "YouCompleteMe unavailable"
error, check the [Troubleshooting][wiki-troubleshooting] guide.

Next, check the [User Guide](#user-guide) section on the semantic completer that
you are using. For C/C++/Objective-C/Objective-C++/CUDA, you  _must_ read [this
section](#c-family-semantic-completion).

Finally, check the [FAQ][wiki-faq].

If, after reading the installation and user guides, and checking the FAQ, you're
still having trouble, check the [contacts](#contact) section below for how to
get in touch.

Please do **NOT** go to #vim on Freenode for support. Please contact the
YouCompleteMe maintainers directly using the [contact details](#contact) below.

# Vundle

Please note that the below instructions suggest using Vundle. Currently there
are problems with Vundle, so here are some [alternative instructions](https://github.com/ycm-core/YouCompleteMe/issues/4134#issuecomment-1446235584) using Vim packages.

Contents
--------

- [Intro](#intro)
- [Installation](#installation)
    - [Requirements](#requirements)
    - [macOS](#macos)
    - [Linux 64-bit](#linux-64-bit)
    - [Windows](#windows)
    - [Full Installation Guide](#full-installation-guide)
- [Quick Feature Summary](#quick-feature-summary)
- [User Guide](#user-guide)
    - [General Usage](#general-usage)
    - [Client-Server Architecture](#client-server-architecture)
    - [Completion String Ranking](#completion-string-ranking)
    - [General Semantic Completion](#general-semantic-completion)
    - [Signature Help](#signature-help)
    - [Semantic Highlighting](#semantic-highlighting)
    - [Inlay Hints](#inlay-hints)
    - [C-family Semantic Completion](#c-family-semantic-completion)
    - [Java Semantic Completion](#java-semantic-completion)
    - [C# Semantic Completion](#c-semantic-completion)
    - [Python Semantic Completion](#python-semantic-completion)
    - [Rust Semantic Completion](#rust-semantic-completion)
    - [Go Semantic Completion](#go-semantic-completion)
    - [JavaScript and TypeScript Semantic Completion](#javascript-and-typescript-semantic-completion)
    - [Semantic Completion for Other Languages](#semantic-completion-for-other-languages)
    - [LSP Configuration](#lsp-configuration)
    - [Writing New Semantic Completers](#writing-new-semantic-completers)
    - [Diagnostic Display](#diagnostic-display)
        - [Diagnostic Highlighting Groups](#diagnostic-highlighting-groups)
    - [Symbol Search](#symbol-search)
    - [Type/Call Hierarchy](#typecall-hierarchy)
- [Commands](#commands)
    - [YcmCompleter subcommands](#ycmcompleter-subcommands)
        - [GoTo Commands](#goto-commands)
        - [Semantic Information Commands](#semantic-information-commands)
        - [Refactoring Commands](#refactoring-commands)
        - [Miscellaneous Commands](#miscellaneous-commands)
- [Functions](#functions)
- [Autocommands](#autocommands)
- [Options](#options)
- [FAQ](#faq)
- [Contributor Code of Conduct](#contributor-code-of-conduct)
- [Contact](#contact)
- [License](#license)
- [Sponsorship](#sponsorship)


Intro
-----

YouCompleteMe is a fast, as-you-type, fuzzy-search code completion,
comprehension and refactoring engine for [Vim][].

It has several completion engines built-in and supports any protocol-compliant
Language Server, so can work with practically any language. YouCompleteMe
contains:

- an identifier-based engine that works with every programming language,
- a powerful [clangd][]-based engine that provides native semantic code
  completion for C/C++/Objective-C/Objective-C++/CUDA (from now on referred to
  as "the C-family languages"),
- a [Jedi][]-based completion engine for Python 2 and 3,
- an [OmniSharp-Roslyn][]-based completion engine for C#,
- a [Gopls][]-based completion engine for Go,
- a [TSServer][]-based completion engine for JavaScript and TypeScript,
- a [rust-analyzer][]-based completion engine for Rust,
- a [jdt.ls][]-based completion engine for Java.
- a [generic Language Server Protocol implementation for any language](#plugging-an-arbitrary-lsp-server)
- and an omnifunc-based completer that uses data from Vim's omnicomplete system
  to provide semantic completions for many other languages (Ruby, PHP, etc.).

![YouCompleteMe GIF completion demo](https://i.imgur.com/0OP4ood.gif)

Here's an explanation of what happened in the last GIF demo above.

First, realize that **no keyboard shortcuts had to be pressed** to get the list
of completion candidates at any point in the demo. The user just types and the
suggestions pop up by themselves. If the user doesn't find the completion
suggestions relevant and/or just wants to type, they can do so; the completion
engine will not interfere.

When the user sees a useful completion string being offered, they press the TAB
key to accept it. This inserts the completion string. Repeated presses of the
TAB key cycle through the offered completions.

If the offered completions are not relevant enough, the user can continue typing
to further filter out unwanted completions.

A critical thing to notice is that the completion **filtering is NOT based on
the input being a string prefix of the completion** (but that works too). The
input needs to be a _[subsequence][] match_ of a completion. This is a fancy way
of saying that any input characters need to be present in a completion string in
the order in which they appear in the input. So `abc` is a subsequence of
`xaybgc`, but not of `xbyxaxxc`. After the filter, a complicated sorting system
ranks the completion strings so that the most relevant ones rise to the top of
the menu (so you usually need to press TAB just once).

**All of the above works with any programming language** because of the
identifier-based completion engine. It collects all of the identifiers in the
current file and other files you visit (and your tags files) and searches them
when you type (identifiers are put into per-filetype groups).

The demo also shows the semantic engine in use. When the user presses `.`, `->`
or `::` while typing in insert mode (for C++; different triggers are used for
other languages), the semantic engine is triggered (it can also be triggered
with a keyboard shortcut; see the rest of the docs).

The last thing that you can see in the demo is YCM's diagnostic display features
(the little red X that shows up in the left gutter; inspired by [Syntastic][])
if you are editing a C-family file. As the completer engine compiles your file
and detects warnings or errors, they will be presented in various ways. You
don't need to save your file or press any keyboard shortcut to trigger this, it
"just happens" in the background.

**And that's not all...**

YCM might be the only Vim completion engine with the correct Unicode support.
Though we do assume UTF-8 everywhere.

![YouCompleteMe GIF unicode demo](https://user-images.githubusercontent.com/10026824/34471853-af9cf32a-ef53-11e7-8229-de534058ddc4.gif)

YCM also provides [semantic IDE-like features](#quick-feature-summary) in a
number of languages, including:

- displaying signature help (argument hints) when entering the arguments to a
  function call (Vim only)
- [finding declarations, definitions, usages](#goto-commands), etc.
  of identifiers, and an [interactive symbol finder](#symbol-search)
- [displaying type information](#the-gettype-subcommand) for classes,
  variables, functions etc.,
- displaying documentation for methods, members, etc. in the [preview
  window](#the-getdoc-subcommand), or in a
  [popup next to the cursor](#the-gycm_auto_hover-option) (Vim only)
- [fixing common coding errors](#the-fixit-subcommand), like missing
  semi-colons, typos, etc.,
- [semantic renaming](#the-refactorrename-subcommand) of variables across files,
- formatting code,
- removing unused imports, sorting imports, etc.

For example, here's a demo of signature help:

![Signature Help Early Demo](https://user-images.githubusercontent.com/10584846/58738348-5060da80-83fd-11e9-9537-d07fdbf4554c.gif)

Below we can see YCM being able to do a few things:

- Retrieve references across files
- Go to declaration/definition
- Expand `auto` in C++
- Fix some common errors, and provide refactorings, with `FixIt`
- Not shown in the GIF are `GoToImplementation` and `GoToType`
  for servers that support it.

![YouCompleteMe GIF subcommands demo](https://i.imgur.com/nmUUbdl.gif)

And here's some documentation being shown in a hover popup, automatically and
manually:

![hover demo](https://user-images.githubusercontent.com/10584846/80312146-91af6500-87db-11ea-996b-7396f3134d1f.gif)

Features vary by file type, so make sure to check out the [file type feature
summary](#quick-feature-summary) and the
[full list of completer subcommands](#ycmcompleter-subcommands) to
find out what's available for your favourite languages.

You'll also find that YCM has filepath completers (try typing `./` in a file)
and a completer that integrates with [UltiSnips][].

Installation
------------

### Requirements

| Runtime | Min Version | Recommended Version (full support) | Python |
|---------|-------------|------------------------------------|--------|
| Vim     | 9.1.0016    | 9.1.0016                           | 3.8    |
| Neovim  | 0.5         | Vim 9.1.0016                       | 3.8    |

#### Supported Vim Versions

Our policy is to support the Vim version that's in the latest LTS of Ubuntu.

Vim must have a [working Python 3 runtime](#supported-python-runtime).

For Neovim users, our policy is to require the latest released version.
Currently, Neovim 0.5.0 is required.  Please note that some features are not
available in Neovim, and Neovim is not officially supported.

#### Supported Python runtime

YCM has two components: A server and a client. Both the server and client
require Python 3.8 or later 3.x release. 

For the Vim client, Vim must be, compiled with `--enable-shared` (or
`--enable-framework` on macOS). You can check if this is working with `:py3
import sys; print( sys.version)`. It should say something like `3.8.2 (...)`.

For Neovim, you must have a python 3.8 runtime and the Neovim python
extensions. See Neovim's `:help provider-python` for how to set that up.

For the server, you must run the `install.py` script with a python 3.8 (or
later) runtime. Anaconda etc. are not supported. YCM will remember the runtime
you used to run `install.py` and will use that when launching the server, so if
you usually use anaconda, then make sure to use the full path to a real cpython3,
e.g. `/usr/bin/python3 install.py --all` etc.

Our policy is to support the python3 version that's available in the latest
Ubuntu LTS (similar to our Vim version policy). We don't increase the Python
runtime version without a reason, though. Typically, we do this when the current
python version we're using goes out of support. At that time we will typically
pick a version that will be supported for a number of years.

#### Supported Compilers

In order to provide the best possible performance and stability, ycmd has
updated its code to C++17. This requires a version bump of the minimum
supported compilers. The new requirements are:

| Compiler | Current Min    |
|----------|----------------|
| GCC      | 8              |
| Clang    | 7              |
| MSVC     | 15.7 (VS 2017) |

YCM requires CMake 3.13 or greater. If your CMake is too old, you may be able to
simply `pip install --user cmake` to get a really new version.

#### Individual completer requirements

When enabling language support for a particular language, there may be runtime
requirements, such as needing a very recent Java Development Kit for Java
support. In general, YCM is not in control of the required versions for the
downstream compilers, though we do our best to signal where we know them.

### macOS

#### Quick start, installing all completers

- Install YCM plugin via [Vundle][]
- Install CMake, MacVim and Python 3; Note that the pre-installed *macOS system*
  Vim is not supported (due to it having broken Python integration).

```
$ brew install cmake python go nodejs
```

- Install mono from [Mono Project](mono-install-macos) (NOTE: on Intel Macs you
  can also `brew install mono`. On arm Macs, you may require Rosetta)

- For Java support you must install a JDK, one way to do this is with Homebrew:

```
$ brew install java
$ sudo ln -sfn $(brew --prefix java)/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
```

- Pre-installed macOS *system* Vim does not support Python 3. So you need to
  install either a Vim that supports Python 3 OR [MacVim][] with
  [Homebrew][brew]:

  - Option 1: Installing a Vim that supports Python 3
  
  ```
  brew install vim
  ```

  - Option 2: Installing [MacVim][]
  
  ```
  brew install macvim
  ```

- Compile YCM.

  - For Intel and arm64 Macs, the bundled libclang/clangd work:

    ```
    cd ~/.vim/bundle/YouCompleteMe
    python3 install.py --all
    ```

  - If you have troubles with finding system frameworks or C++ standard library,
    try using the homebrew llvm:

    ```
    brew install llvm
    cd ~/.vim/bundle/YouCompleteMe
    python3 install.py --system-libclang --all
    ```

    And edit your vimrc to add the following line to use the Homebrew llvm's
    clangd:

    ```viml
    " Use homebrew's clangd
    let g:ycm_clangd_binary_path = trim(system('brew --prefix llvm')).'/bin/clangd'
    ```


- For using an arbitrary LSP server, check [the relevant
  section](#plugging-an-arbitrary-lsp-server)

#### Explanation for the quick start

These instructions (using `install.py`) are the quickest way to install
YouCompleteMe, however they may not work for everyone. If the following
instructions don't work for you, check out the [full installation
guide](#full-installation-guide).

A supported Vim version with Python 3 is required. [MacVim][] is a good option,
even if you only use the terminal. YCM won't work with the pre-installed Vim
from Apple as its Python support is broken. If you don't already use a Vim
that supports Python 3 or [MacVim][], install it with [Homebrew][brew]. Install
CMake as well:

    brew install vim cmake     
    
   OR

    brew install macvim cmake

Install YouCompleteMe with [Vundle][].

**Remember:** YCM is a plugin with a compiled component. If you **update** YCM
using Vundle and the `ycm_core` library APIs have changed (happens
rarely), YCM will notify you to recompile it. You should then rerun the install
process.

**NOTE:** If you want C-family completion, you MUST have the latest Xcode
installed along with the latest Command Line Tools (they are installed
automatically when you run `clang` for the first time, or manually by running
`xcode-select --install`)

Compiling YCM **with** semantic support for C-family languages through
**clangd**:

```
cd ~/.vim/bundle/YouCompleteMe
./install.py --clangd-completer
```

Compiling YCM **without** semantic support for C-family languages:

```
cd ~/.vim/bundle/YouCompleteMe
./install.py
```


The following additional language support options are available:

- C# support: install by downloading the [Mono macOS package][mono-install-macos]
  and add `--cs-completer` when calling `install.py`.
- Go support: install [Go][go-install] and add `--go-completer` when calling
  `install.py`.
- JavaScript and TypeScript support: install [Node.js 18+ and npm][npm-install] and
  add `--ts-completer` when calling `install.py`.
- Rust support: add `--rust-completer` when calling `install.py`.
- Java support: install [JDK 17][jdk-install] and add
  `--java-completer` when calling `install.py`.

To simply compile with everything enabled, there's a `--all` flag. So, to
install with all language features, ensure `xbuild`, `go`, `node` and `npm`
tools are installed and in your `PATH`, then simply run:

```
cd ~/.vim/bundle/YouCompleteMe
./install.py --all
```

That's it. You're done. Refer to the _User Guide_ section on how to use YCM.
Don't forget that if you want the C-family semantic completion engine to work,
you will need to provide the compilation flags for your project to YCM. It's all
in the User Guide.

YCM comes with sane defaults for its options, but you still may want to take a
look at what's available for configuration. There are a few interesting options
that are conservatively turned off by default that you may want to turn on.

### Linux 64-bit

The following assume you're using Ubuntu 24.04.

#### Quick start, installing all completers

- Install YCM plugin via [Vundle][]
- Install CMake, Vim and Python

```
apt install build-essential cmake vim-nox python3-dev
```

- Install mono-complete, go, node, java, and npm

```
apt install mono-complete golang nodejs openjdk-17-jdk openjdk-17-jre npm
```

- Compile YCM

```
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all
```

- For plugging an arbitrary LSP server, check [the relevant section](#plugging-an-arbitrary-lsp-server)

#### Explanation for the quick start

These instructions (using `install.py`) are the quickest way to install
YouCompleteMe, however they may not work for everyone. If the following
instructions don't work for you, check out the [full installation
guide](#full-installation-guide).

Make sure you have a supported version of Vim with Python 3 support and a
supported compiler. The latest LTS of Ubuntu is the minimum platform for simple
installation. For earlier releases or other distributions, you may have to do
some work to acquire the dependencies.

If your Vim version is too old, you may need to [compile Vim from
source][vim-build] (don't worry, it's easy).

Install YouCompleteMe with [Vundle][].

**Remember:** YCM is a plugin with a compiled component. If you **update** YCM
using Vundle and the `ycm_core` library APIs have changed (which happens rarely), YCM
will notify you to recompile it. You should then rerun the installation process.

Install development tools, CMake, and Python headers:

- Fedora-like distributions:

```
sudo dnf install cmake gcc-c++ make python3-devel
```

- Ubuntu LTS:

```
sudo apt install build-essential cmake3 python3-dev
```

Compiling YCM **with** semantic support for C-family languages through
**clangd**:

```
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --clangd-completer
```

Compiling YCM **without** semantic support for C-family languages:

```
cd ~/.vim/bundle/YouCompleteMe
python3 install.py
```

The following additional language support options are available:

- C# support: install [Mono][mono-install-linux] and add `--cs-completer`
  when calling `install.py`.
- Go support: install [Go][go-install] and add `--go-completer` when calling
  `install.py`.
- JavaScript and TypeScript support: install [Node.js 18+ and npm][npm-install] and
  add `--ts-completer` when calling `install.py`.
- Rust support: add `--rust-completer` when calling `install.py`.
- Java support: install [JDK 17][jdk-install] and add
  `--java-completer` when calling `install.py`.

To simply compile with everything enabled, there's a `--all` flag. So, to
install with all language features, ensure `xbuild`, `go`, `node`, and `npm`
tools are installed and in your `PATH`, then simply run:

```
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all
```

That's it. You're done. Refer to the _User Guide_ section on how to use YCM.
Don't forget that if you want the C-family semantic completion engine to work,
you will need to provide the compilation flags for your project to YCM. It's all
in the User Guide.

YCM comes with sane defaults for its options, but you still may want to take a
look at what's available for configuration. There are a few interesting options
that are conservatively turned off by default that you may want to turn on.

### Windows

#### Quick start, installing all completers

- Install YCM plugin via [Vundle][]
- Install [Visual Studio Build Tools 2019][visual-studio-download]
- Install CMake, Vim and Python
- Install go, node and npm
- Compile YCM

```
cd YouCompleteMe
python3 install.py --all
```

- Add `set encoding=utf-8` to your [vimrc][]
- For plugging an arbitrary LSP server, check [the relevant section](#plugging-an-arbitrary-lsp-server)

#### Explanation for the quick start

These instructions (using `install.py`) are the quickest way to install
YouCompleteMe, however they may not work for everyone. If the following
instructions don't work for you, check out the [full installation
guide](#full-installation-guide).

**Important:** we assume that you are using the `cmd.exe` command prompt and
that you know how to add an executable to the PATH environment variable.

Make sure you have a supported Vim version with Python 3 support. You
can check the version and which Python is supported by typing `:version` inside
Vim. Look at the features included: `+python3/dyn` for Python 3.
Take note of the Vim architecture, i.e. 32 or
64-bit. It will be important when choosing the Python installer. We recommend
using a 64-bit client. [Daily updated installers of 32-bit and 64-bit Vim with
Python 3 support][vim-win-download] are available.

Add the following line to your [vimrc][] if not already present.:

```viml
set encoding=utf-8
```

This option is required by YCM. Note that it does not prevent you from editing a
file in another encoding than UTF-8.  You can do that by specifying [the `++enc`
argument][++enc] to the `:e` command.

Install YouCompleteMe with [Vundle][].

**Remember:** YCM is a plugin with a compiled component. If you **update** YCM
using Vundle and the `ycm_core` library APIs have changed (happens
rarely), YCM will notify you to recompile it. You should then rerun the install
process.

Download and install the following software:

- [Python 3][python-win-download]. Be sure to pick the version
  corresponding to your Vim architecture. It is _Windows x86_ for a 32-bit Vim
  and _Windows x86-64_ for a 64-bit Vim. We recommend installing Python 3.
  Additionally, the version of Python you install must match up exactly with
  the version of Python that Vim is looking for. Type `:version` and look at the
  bottom of the page at the list of compiler flags. Look for flags that look
  similar to `-DDYNAMIC_PYTHON3_DLL=\"python36.dll\"`. This indicates
  that Vim is looking for Python 3.6. You'll need one or the other installed,
  matching the version number exactly.
- [CMake][cmake-download]. Add CMake executable to the PATH environment
  variable.
- [Build Tools for Visual Studio 2019][visual-studio-download]. During setup,
  select _C++ build tools_ in _Workloads_.

Compiling YCM **with** semantic support for C-family languages through
**clangd**:

```
cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe
python install.py --clangd-completer
```

Compiling YCM **without** semantic support for C-family languages:

```
cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe
python install.py
```

The following additional language support options are available:

- C# support: add `--cs-completer` when calling `install.py`.
  Be sure that [the build utility `msbuild` is in your PATH][add-msbuild-to-path].
- Go support: install [Go][go-install] and add `--go-completer` when calling
  `install.py`.
- JavaScript and TypeScript support: install [Node.js 18+ and npm][npm-install] and
  add `--ts-completer` when calling `install.py`.
- Rust support: add `--rust-completer` when calling `install.py`.
- Java support: install [JDK 17][jdk-install] and add
  `--java-completer` when calling `install.py`.

To simply compile with everything enabled, there's a `--all` flag. So, to
install with all language features, ensure `msbuild`, `go`, `node` and `npm`
tools are installed and in your `PATH`, then simply run:

```
cd %USERPROFILE%/vimfiles/bundle/YouCompleteMe
python install.py --all
```

You can specify the Microsoft Visual C++ (MSVC) version using the `--msvc`
option. YCM officially supports MSVC 15 (2017), MSVC 16 (Visual Studio 2019) 
and MSVC 17 (Visual Studio 17 2022).

That's it. You're done. Refer to the _User Guide_ section on how to use YCM.
Don't forget that if you want the C-family semantic completion engine to work,
you will need to provide the compilation flags for your project to YCM. It's all
in the User Guide.

YCM comes with sane defaults for its options, but you still may want to take a
look at what's available for configuration. There are a few interesting options
that are conservatively turned off by default that you may want to turn on.

### Full Installation Guide

The [full installation guide][wiki-full-install] has been moved to the wiki.

Quick Feature Summary
-----

### General (all languages)

* Super-fast identifier completer including tags files and syntax elements
* Intelligent suggestion ranking and filtering
* File and path suggestions
* Suggestions from Vim's omnifunc
* UltiSnips snippet suggestions

### C-family languages (C, C++, Objective C, Objective C++, CUDA)

* Semantic auto-completion with automatic fixes
* Signature help
* Real-time diagnostic display
* Go to include/declaration/definition (`GoTo`, etc.)
* Go to alternate file (e.g. associated header `GoToAlternateFile`)
* Find Symbol (`GoToSymbol`), with interactive search
* Document outline (`GoToDocumentOutline`), with interactive search
* View documentation comments for identifiers (`GetDoc`)
* Type information for identifiers (`GetType`)
* Automatically fix certain errors (`FixIt`)
* Perform refactoring (`FixIt`)
* Reference finding (`GoToReferences`)
* Renaming symbols (`RefactorRename <new name>`)
* Code formatting (`Format`)
* Semantic highlighting
* Inlay hints
* Type hierarchy
* Call hierarchy

### C♯

* Semantic auto-completion
* Signature help
* Real-time diagnostic display
* Go to declaration/definition (`GoTo`, etc.)
* Go to implementation (`GoToImplementation`)
* Find Symbol (`GoToSymbol`), with interactive search
* View documentation comments for identifiers (`GetDoc`)
* Type information for identifiers (`GetType`)
* Automatically fix certain errors (`FixIt`)
* Perform refactoring (`FixIt`)
* Management of OmniSharp-Roslyn server instance
* Renaming symbols (`RefactorRename <new name>`)
* Code formatting (`Format`)

### Python

* Semantic auto-completion
* Signature help
* Go to definition (`GoTo`)
* Find Symbol (`GoToSymbol`), with interactive search
* Reference finding (`GoToReferences`)
* View documentation comments for identifiers (`GetDoc`)
* Type information for identifiers (`GetType`)
* Renaming symbols (`RefactorRename <new name>`)

### Go

* Semantic auto-completion
* Signature help
* Real-time diagnostic display
* Go to declaration/definition (`GoTo`, etc.)
* Go to type definition (`GoToType`)
* Go to implementation (`GoToImplementation`)
* Document outline (`GoToDocumentOutline`), with interactive search
* Automatically fix certain errors (`FixIt`)
* Perform refactoring (`FixIt`)
* View documentation comments for identifiers (`GetDoc`)
* Type information for identifiers (`GetType`)
* Code formatting (`Format`)
* Management of `gopls` server instance
* Inlay hints
* Call hierarchy

### JavaScript and TypeScript

* Semantic auto-completion with automatic import insertion
* Signature help
* Real-time diagnostic display
* Go to definition (`GoTo`, `GoToDefinition`, and `GoToDeclaration` are
  identical)
* Go to type definition (`GoToType`)
* Go to implementation (`GoToImplementation`)
* Find Symbol (`GoToSymbol`), with interactive search
* Reference finding (`GoToReferences`)
* View documentation comments for identifiers (`GetDoc`)
* Type information for identifiers (`GetType`)
* Automatically fix certain errors and perform refactoring (`FixIt`)
* Perform refactoring (`FixIt`)
* Renaming symbols (`RefactorRename <new name>`)
* Code formatting (`Format`)
* Organize imports (`OrganizeImports`)
* Management of `TSServer` server instance
* Inlay hints
* Call hierarchy

### Rust

* Semantic auto-completion
* Real-time diagnostic display
* Go to declaration/definition (`GoTo`, etc.)
* Go to implementation (`GoToImplementation`)
* Reference finding (`GoToReferences`)
* Document outline (`GoToDocumentOutline`), with interactive search
* View documentation comments for identifiers (`GetDoc`)
* Automatically fix certain errors (`FixIt`)
* Perform refactoring (`FixIt`)
* Type information for identifiers (`GetType`)
* Renaming symbols (`RefactorRename <new name>`)
* Code formatting (`Format`)
* Management of `rust-analyzer` server instance
* Semantic highlighting
* Inlay hints
* Call hierarchy

### Java

* Semantic auto-completion with automatic import insertion
* Signature help
* Real-time diagnostic display
* Go to definition (`GoTo`, `GoToDefinition`, and `GoToDeclaration` are
  identical)
* Go to type definition (`GoToType`)
* Go to implementation (`GoToImplementation`)
* Find Symbol (`GoToSymbol`), with interactive search
* Reference finding (`GoToReferences`)
* Document outline (`GoToDocumentOutline`), with interactive search
* View documentation comments for identifiers (`GetDoc`)
* Type information for identifiers (`GetType`)
* Automatically fix certain errors including code generation (`FixIt`)
* Renaming symbols (`RefactorRename <new name>`)
* Code formatting (`Format`)
* Organize imports (`OrganizeImports`)
* Detection of Java projects
* Execute custom server command (`ExecuteCommand <args>`)
* Management of `jdt.ls` server instance
* Semantic highlighting
* Inlay hints
* Type hierarchy
* Call hierarchy

User Guide
----------

### General Usage

If the offered completions are too broad, keep typing characters; YCM will
continue refining the offered completions based on your input.

Filtering is "smart-case" and "smart-[diacritic][]" sensitive; if you are
typing only lowercase letters, then it's case-insensitive. If your input
contains uppercase letters, then the uppercase letters in your query must
match uppercase letters in the completion strings (the lowercase letters still
match both). On top of that, a letter with no diacritic marks will match that
letter with or without marks:

<table>
<tbody>
<tr>
  <th>matches</th>
  <th>foo</th>
  <th>fôo</th>
  <th>fOo</th>
  <th>fÔo</th>
</tr>
<tr>
  <th>foo</th>
  <td>✔️</td>
  <td>✔️</td>
  <td>✔️</td>
  <td>✔️</td>
</tr>
<tr>
  <th>fôo</th>
  <td>❌</td>
  <td>✔️</td>
  <td>❌</td>
  <td>✔️</td>
</tr>
<tr>
  <th>fOo</th>
  <td>❌</td>
  <td>❌</td>
  <td>✔️</td>
  <td>✔️</td>
</tr>
<tr>
  <th>fÔo</th>
  <td>❌</td>
  <td>❌</td>
  <td>❌</td>
  <td>✔️</td>
</tr>
</tbody>
</table>

Use the TAB key to accept a completion and continue pressing TAB to cycle
through the completions. Use Shift-TAB to cycle backward. Note that if you're
using console Vim (that is, not gvim or MacVim) then it's likely that the
Shift-TAB binding will not work because the console will not pass it to Vim.
You can remap the keys; see the [Options](#options) section below.

Knowing a little bit about how YCM works internally will prevent confusion. YCM
has several completion engines: an identifier-based completer that collects all
of the identifiers in the current file and other files you visit (and your tags
files) and searches them when you type (identifiers are put into per-filetype
groups).

There are also several semantic engines in YCM. There are libclang-based and
clangd-based completers that provide semantic completion for C-family languages.
There's a Jedi-based completer for semantic completion for Python. There's also
an omnifunc-based completer that uses data from Vim's omnicomplete system to
provide semantic completions when no native completer exists for that language
in YCM.

There are also other completion engines, like the UltiSnips completer and the
filepath completer.

YCM automatically detects which completion engine would be the best in any
situation. On occasion, it queries several of them at once, merges the
outputs and presents the results to you.

### Client-Server Architecture

YCM has a client-server architecture; the Vim part of YCM is only a thin client
that talks to the [ycmd HTTP+JSON server][ycmd] that has the vast majority of
YCM logic and functionality. The server is started and stopped automatically as
you start and stop Vim.

### Completion String Ranking

The subsequence filter removes any completions that do not match the input, but
then the sorting system kicks in. It's actually very complicated and uses lots
of factors, but suffice it to say that "word boundary" (WB) subsequence
character matches are "worth" more than non-WB matches. In effect, this means
that given an input of "gua", the completion "getUserAccount" would be ranked higher
in the list than the "Fooguxa" completion (both of which are subsequence
matches). Word-boundary characters are all capital characters, characters
preceded by an underscore, and the first letter character in the completion
string.

### Signature Help

Valid signatures are displayed in a second popup menu and the current signature
is highlighted along with the current argument.

Signature help is triggered in insert mode automatically when
`g:ycm_auto_trigger` is enabled and is not supported when it is not enabled.

The signatures popup is hidden when there are no matching signatures or when you
leave insert mode. If you want to manually control when it is visible, you can
map something to `<plug>YCMToggleSignatureHelp` (see below).

For more details on this feature and a few demos, check out the
[PR that proposed it][signature-help-pr].

#### Dismiss signature help

The signature help popup sometimes gets in the way. You can toggle its
visibility with a mapping. YCM provides the "Plug" mapping
`<Plug>(YCMToggleSignatureHelp)` for this.

For example, to hide/show the signature help popup by pressing Ctrl+l in insert
mode: `imap <silent> <C-l> <Plug>(YCMToggleSignatureHelp)`.

_NOTE_: No default mapping is provided because insert mappings are very
difficult to create without breaking or overriding some existing functionality.
Ctrl-l is not a suggestion, just an example.

### Semantic highlighting

Semantic highlighting is the process where the buffer text is coloured according
to the underlying semantic type of the word, rather than classic syntax
highlighting based on regular expressions. This can be powerful additional data
that we can process very quickly.

This feature is only supported in Vim.

For example, here is a function with classic highlighting:

![highliting-classic](https://user-images.githubusercontent.com/10584846/173137003-a265e8b0-84db-4993-98f0-03ee81b9de94.png)

And here is the same function with semantic highlighting:

![highliting-semantic](https://user-images.githubusercontent.com/10584846/173137012-7547de0b-145f-45fa-ace3-18943acd2141.png)

As you can see, the function calls, macros, etc. are correctly identified. 

This can be enabled globally with `let g:ycm_enable_semantic_highlighting=1` or
per buffer, by setting `b:ycm_enable_semantic_highlighting`.

#### Customising the highlight groups

YCM uses text properties (see `:help text-prop-intro`) for semantic
highlighting. In order to customise the coloring, you can define the text
properties that are used.

If you define a text property named `YCM_HL_<token type>`, then it will be used
in place of the defaults. The `<token type>` is defined as the Language Server
Protocol semantic token type, defined in the [LSP Spec](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens).

Some servers also use custom values. In this case, YCM prints a warning
including the token type name that you can customise.

For example, to render `parameter` tokens using the `Normal` highlight group,
you can do this:

```viml
call prop_type_add( 'YCM_HL_parameter', { 'highlight': 'Normal' } )
```

More generally, this pattern can be useful for customising the groups:

```viml
let MY_YCM_HIGHLIGHT_GROUP = {
      \   'typeParameter': 'PreProc',
      \   'parameter': 'Normal',
      \   'variable': 'Normal',
      \   'property': 'Normal',
      \   'enumMember': 'Normal',
      \   'event': 'Special',
      \   'member': 'Normal',
      \   'method': 'Normal',
      \   'class': 'Special',
      \   'namespace': 'Special',
      \ }

for tokenType in keys( MY_YCM_HIGHLIGHT_GROUP )
  call prop_type_add( 'YCM_HL_' . tokenType,
                    \ { 'highlight': MY_YCM_HIGHLIGHT_GROUP[ tokenType ] } )
endfor
```

## Inlay hints

**NOTE**: Highly experimental feature, requiring Vim 9.0.214 or later (not
supported in NeoVim).

When `g:ycm_enable_inlay_hints` (globally) or `b:ycm_enable_inlay_hints` (for a
specific buffer) is set to `1`, then YCM will insert inlay hints as supported by
the language semantic engine.

An inlay hint is text that is rendered on the screen that is not part of the buffer and
is often used to mark up the type or name of arguments, parameters, etc. which
help the developer understand the semantics of the code.

Here are some examples:

* C

![c-inlay](https://user-images.githubusercontent.com/10584846/185708054-68074fc0-e50c-4a65-887c-da6f372b8982.png)

* TypeScript

![ts-inlay](https://user-images.githubusercontent.com/10584846/185708156-b52970ce-005f-4f0b-97e7-bdf8feeefedc.png)

* Go

![go-inlay](https://user-images.githubusercontent.com/10584846/185708242-e42dab6f-1847-46f1-8585-2d9f2c8a76dc.png)

### Highlight groups

By default, YCM renders the inlay hints with the `NonText` highlight group. To
override this, define the `YcmInlayHint` highlight yourself, e.g. in your
`.vimrc`:

```viml
hi link YcmInlayHint Comment
```

Similar to semantic highlighting above, you can override specific highlighting
for different inlay hint types by defining text properties named after the kind
of inlay hint, for example:

```viml
call prop_type_add( 'YCM_INLAY_Type', #{ highlight: 'Comment' } )
```

The list of inlay hint kinds can be found in `python/ycm/inlay_hints.py`

### Options

* `g:ycm_enable_inlay_hints` or `b:ycm_enable_inlay_hints` - enable/disable
  globally or for local buffer
* `g:ycm_clear_inlay_hints_in_insert_mode` - set to `1` to remove all inlay
  hints when entering insert mode and reinstate them when leaving insert mode

### Toggling

Inlay hints can add a lot of text to the screen and may be distracting. You can
toggle them on/off instantly, by mapping something to
`<Plug>(YCMToggleInlayHints)`, for example:

```viml
nnoremap <silent> <localleader>h <Plug>(YCMToggleInlayHints)
```

No default mapping is provided for this due to the personal nature of mappings.

### General Semantic Completion

You can use Ctrl+Space to trigger the completion suggestions anywhere, even
without a string prefix. This is useful to see which top-level functions are
available for use.

### C-family Semantic Completion

**NOTE:** YCM originally used the `libclang` based engine for C-family, but
users should migrate to clangd, as it provides more features and better
performance. Users who rely on `override_filename` in their `.ycm_extra_conf.py`
will need to stay on the old `libclang` engine. Instructions on how to stay on
the old engine are available on [the wiki][libclang-instructions].

Some of the features of clangd:

- **Project wide indexing**: Clangd has both dynamic and static index support.
  The dynamic index stores up-to-date symbols coming from any files you are
  currently editing, whereas static index contains project-wide symbol
  information. This symbol information is used for code completion and code
  navigation. Whereas libclang is limited to the current translation unit(TU).
- **Code navigation**: Clangd provides all the GoTo requests libclang provides and it
  improves those using the above-mentioned index information to contain
  project-wide information rather than just the current TU.
- **Rename**: Clangd can perform semantic rename operations on the current
  file, whereas libclang doesn't support such functionality.
- **Code Completion**: Clangd can perform code completions at a lower latency
  than libclang; also, it has information about all the symbols in your
  project so it can suggest items outside your current TU and also provides
  proper `#include` insertions for those items.
- **Signature help**: Clangd provides signature help so that you can see the
  names and types of arguments when calling functions.
- **Format Code**: Clangd provides code formatting either for the selected
  lines or the whole file, whereas libclang doesn't have such functionality.
- **Performance**: Clangd has faster re-parse and code completion times
  compared to libclang.

#### Installation

On supported architectures, the `install.py` script will download a suitable
clangd (`--clangd-completer`) or libclang (`--clang-completer`) for you.
Supported architectures are:

* Linux glibc >= 2.39 (Intel, armv7-a, aarch64) - built on ubuntu 24.04
* MacOS >=10.15 (Intel, arm64)
  - For Intel, compatibility per clang.llvm.org downloads
  - For arm64, macOS 10.15+
* Windows (Intel) - compatibility per clang.llvm.org downloads

***clangd***:

Typically, clangd is installed by the YCM installer (either with `--all` or with
`--clangd-completer`). This downloads a pre-built `clangd` binary for your
architecture. If your OS or architecture is not supported or is too old, you can
install a compatible `clangd` and use [`g:ycm_clangd_binary_path`]() to point to
it.

***libclang***:

`libclang` can be enabled also with `--all` or `--clang-completer`. As with
`clangd`, YCM will try and download a version of `libclang` that is suitable for
your environment, but again if your environment can't be supported, you can
build or acquire `libclang` for yourself and specify it when building, as:

```
$ EXTRA_CMAKE_ARGS='-DPATH_TO_LLVM_ROOT=/path/to/your/llvm' ./install.py --clang-completer --system-libclang
```

Please note that if using custom `clangd` or `libclang` it _must_ match the
version that YCM requires. Currently YCM requires ***clang 17.0.1***.

#### Compile flags

In order to perform semantic analysis such as code completion, `GoTo`, and
diagnostics, YouCompleteMe uses `clangd`, which makes use of
clang compiler, sometimes also referred to as LLVM. Like any compiler,
clang also requires a set of compile flags in order to parse your code. Simply
put: If clang can't parse your code, YouCompleteMe can't provide semantic
analysis.

There are 2 methods that can be used to provide compile flags to clang:

#### Option 1: Use a [compilation database][compdb]

The easiest way to get YCM to compile your code is to use a compilation
database.  A compilation database is usually generated by your build system
(e.g. `CMake`) and contains the compiler invocation for each compilation unit in
your project.

For information on how to generate a compilation database, see the [clang
documentation][compdb]. In short:

- If using CMake, add `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` when configuring (or
  add `set( CMAKE_EXPORT_COMPILE_COMMANDS ON )` to `CMakeLists.txt`) and copy or
  symlink the generated database to the root of your project.
- If using Ninja, check out the `compdb` tool (`-t compdb`) in its
  [docs][ninja-compdb].
- If using GNU make, check out [compiledb][] or [Bear][].
- For other build systems, check out
  [`.ycm_extra_conf.py`](#option-2-provide-the-flags-manually) below.

If no [`.ycm_extra_conf.py`](#option-2-provide-the-flags-manually) is found,
YouCompleteMe automatically tries to load a compilation database if there is
one.

YCM looks for a file named `compile_commands.json` in the directory of the
opened file or in any directory above it in the hierarchy (recursively); when
the file is found before a local `.ycm_extra_conf.py`, YouCompleteMe stops
searching the directories and lets clangd take over and handle the flags.

#### Option 2: Provide the flags manually

If you don't have a compilation database or aren't able to generate one,
you have to tell YouCompleteMe how to compile your code some other way.

Every C-family project is different. It is not possible for YCM to guess what
compiler flags to supply for your project. Fortunately, YCM provides a mechanism
for you to generate the flags for a particular file with _arbitrary complexity_.
This is achieved by requiring you to provide a Python module that implements a
trivial function that, given the file name as an argument, returns a list of
compiler flags to use to compile that file.

YCM looks for a `.ycm_extra_conf.py` file in the directory of the opened file or
in any directory above it in the hierarchy (recursively); when the file is
found, it is loaded (only once!) as a Python module. YCM calls a `Settings`
method in that module which should provide it with the information necessary to
compile the current file. You can also provide a path to a global configuration
file with the
[`g:ycm_global_ycm_extra_conf`](#the-gycm_global_ycm_extra_conf-option) option,
which will be used as a fallback. To prevent the execution of malicious code
from a file you didn't write YCM will ask you once per `.ycm_extra_conf.py` if
it is safe to load. This can be disabled and you can white-/blacklist files. See
the [`g:ycm_confirm_extra_conf`](#the-gycm_confirm_extra_conf-option) and
[`g:ycm_extra_conf_globlist`](#the-gycm_extra_conf_globlist-option) options
respectively.

This system was designed this way so that the user can perform any arbitrary
sequence of operations to produce a list of compilation flags YCM should hand
to Clang.

**NOTE**: It is highly recommended to include `-x <language>` flag to libclang.
This is so that the correct language is detected, particularly for header files.
Common values are `-x c` for C, `-x c++` for C++, `-x objc` for Objective-C, and
`-x cuda` for CUDA.

To give you an impression, if your C++ project is trivial, and your usual
compilation command is: `g++ -Wall -Wextra -Werror -o FILE.o FILE.cc`, then the
following `.ycm_extra_conf.py` is enough to get semantic analysis from
YouCompleteMe:

```python
def Settings( **kwargs ):
  return {
    'flags': [ '-x', 'c++', '-Wall', '-Wextra', '-Werror' ],
  }
```

As you can see from the trivial example, YCM calls the `Settings` method which
returns a dictionary with a single element `'flags'`. This element is a `list`
of compiler flags to pass to libclang for the current file. The absolute path of
that file is accessible under the `filename` key of the `kwargs` dictionary.
That's it! This is actually enough for most projects, but for complex projects
it is not uncommon to integrate directly with an existing build system using the
full power of the Python language.

For a more elaborate example,
[see ycmd's own `.ycm_extra_conf.py`][ycmd_flags_example]. You should be able to
use it _as a starting point_. **Don't** just copy/paste that file somewhere and
expect things to magically work; **your project needs different flags**. Hint:
just replace the strings in the `flags` variable with compilation flags
necessary for your project. That should be enough for 99% of projects.

You could also consider using [YCM-Generator][ygen] to generate the
`ycm_extra_conf.py` file.

#### Errors during compilation

If Clang encounters errors when compiling the header files that your file
includes, then it's probably going to take a long time to get completions.  When
the completion menu finally appears, it's going to have a large number of
unrelated completion strings (type/function names that are not actually
members). This is because Clang fails to build a precompiled preamble for your
file if there are any errors in the included headers and that preamble is key to
getting fast completions.

Call the `:YcmDiags` command to see if any errors or warnings were detected in
your file.

### Java Semantic Completion

#### Java Quick Start

1. Ensure that you have enabled the Java completer. See the
   [installation guide](#installation) for details.

2. Create a project file (gradle or maven) file in the root directory of your
   Java project, by following the instructions below.

3. (Optional) [Configure the LSP server](#lsp-configuration). The [jdt.ls
   configuration options][jdtls-preferences] can be found in their codebase.

4. If you previously used Eclim or Syntastic for Java, disable them for Java.

5. Edit a Java file from your project.

#### Java Project Files

In order to provide semantic analysis, the Java completion engine requires
knowledge of your project structure. In particular, it needs to know the class
path to use, when compiling your code. Fortunately [jdt.ls][]
supports [eclipse project files][eclipse-project],
[maven projects][mvn-project] and [gradle projects][gradle-project].

**NOTE:** Our recommendation is to use either Maven or Gradle projects.

#### Diagnostic display - Syntastic

The native support for Java includes YCM's native real-time diagnostics display.
This can conflict with other diagnostics plugins like Syntastic, so when
enabling Java support, please **manually disable Syntastic Java diagnostics**.

Add the following to your `vimrc`:

```viml
let g:syntastic_java_checkers = []
```

#### Diagnostic display - Eclim

The native support for Java includes YCM's native real-time diagnostics display.
This can conflict with other diagnostics plugins like Eclim, so when enabling
Java support, please **manually disable Eclim Java diagnostics**.

Add the following to your `vimrc`:

```viml
let g:EclimFileTypeValidate = 0
```

**NOTE**: We recommend disabling Eclim entirely when editing Java with YCM's
native Java support. This can be done temporarily with `:EclimDisable`.

#### Eclipse Projects

Eclipse-style projects require two files: [.project][eclipse-dot-project] and
[.classpath][eclipse-dot-classpath].

If your project already has these files due to previously being set up within
Eclipse, then no setup is required. [jdt.ls][] should load the project just
fine (it's basically eclipse after all).

However, if not, it is possible (easy in fact) to craft them manually, though it
is not recommended. You're better off using Gradle or Maven (see below).

[A simple eclipse style project example][ycmd-eclipse-project] can be found in
the ycmd test directory. Normally all that is required is to copy these files to
the root of your project and to edit the `.classpath` to add additional
libraries, such as:

```xml
  <classpathentry kind="lib" path="/path/to/external/jar" />
  <classpathentry kind="lib" path="/path/to/external/java/source" />
```

It may also be necessary to change the directory in which your source files are
located (paths are relative to the .project file itself):

```xml
  <classpathentry kind="src" output="target/classes" path="path/to/src/" />
```

**NOTE**: The eclipse project and classpath files are not a public interface
and it is highly recommended to use Maven or Gradle project definitions if you
don't already use Eclipse to manage your projects.

#### Maven Projects

Maven needs a file named [pom.xml][mvn-project] in the root of the project.
Once again a simple [pom.xml][ycmd-mvn-pom-xml] can be found in the ycmd source.

The format of [pom.xml][mvn-project] files is way beyond the scope of this
document, but we do recommend using the various tools that can generate them for
you, if you're not familiar with them already.

#### Gradle Projects

Gradle projects require a [build.gradle][gradle-project]. Again, there is a
[trivial example in ycmd's tests][ycmd-gradle-project].

The format of [build.gradle][gradle-project] files are way beyond the scope of
this document, but we do recommend using the various tools that can generate
them for you if you're not familiar with them already.

Some users have experienced issues with their jdt.ls  when using the Groovy
language for their build.gradle. As such, try using
[Kotlin](https://github.com/ycm-core/lsp-examples#kotlin) instead.

#### Troubleshooting

If you're not getting completions or diagnostics, check the server health:

* The Java completion engine takes a while to start up and parse your project.
  You should be able to see its progress in the command line, and
  `:YcmDebugInfo`. Ensure that the following lines are present:

```
--   jdt.ls Java Language Server running
--   jdt.ls Java Language Server Startup Status: Ready
```

* If the above lines don't appear after a few minutes, check the jdt.ls and ycmd
  log files using [`:YcmToggleLogs` ](#the-ycmtogglelogs-command). The jdt.ls
  log file is called `.log` (for some reason).

If you get a message about "classpath is incomplete", then make sure you have
correctly configured the [project files](#java-project-files).

If you get messages about unresolved imports, then make sure you have
correctly configured the [project files](#java-project-files), in particular
check that the classpath is set correctly.

### C# Semantic Completion

YCM relies on [OmniSharp-Roslyn][] to provide completion and code navigation.
OmniSharp-Roslyn needs a solution file for a C# project and there are two ways
of letting YCM know about your solution files.

#### Automatically discovered solution files

YCM will scan all parent directories of the file currently being edited and look
for a file with `.sln` extension.

#### Manually specified solution files

If YCM loads `.ycm_extra_conf.py` which contains `CSharpSolutionFile` function,
YCM will try to use that to determine the solution file. This is useful when one
wants to override the default behaviour and specify a solution file that is not
in any of the parent directories of the currently edited file. Example:

```python
def CSharpSolutionFile( filepath ):
  # `filepath` is the path of the file user is editing
  return '/path/to/solution/file' # Can be relative to the `.ycm_extra_conf.py`
```

If the path returned by `CSharpSolutionFile` is not an actual file, YCM will
fall back to the other way of finding the file.

#### Use with .NET 6.0 and .NET SDKs

YCM ships with older version of OmniSharp-Roslyn based on Mono runtime.
It is possible to use it with .NET 6.0 and newer, but it requires manual setup.

1. Download NET 6.0 version of the OmniSharp server for your system from
[releases](https://github.com/OmniSharp/omnisharp-roslyn/releases/)
1. Set `g:ycm_roslyn_binary_path` to the unpacked executable `OmniSharp`
1. Create a solution file if one doesn't already exist, it is currently required
by YCM for internal bookkeeping
    1. Run `dotnet new sln` at the root of your project
    1. Run `dotnet sln add <project1.csproj> <project2.csproj> ...`
    for all of your projects
1. Run `:YcmRestartServer`

### Python Semantic Completion

YCM relies on the [Jedi][] engine to provide completion and code navigation. By
default, it will pick the version of Python running the [ycmd server][ycmd] and
use its `sys.path`. While this is fine for simple projects, this needs to be
configurable when working with virtual environments or in a project with
third-party packages. The next sections explain how to do that.

#### Working with virtual environments

A common practice when working on a Python project is to install its
dependencies in a virtual environment and develop the project inside that
environment. To support this, YCM needs to know the interpreter path of the
virtual environment. You can specify it by creating a `.ycm_extra_conf.py` file
at the root of your project with the following contents:

```python
def Settings( **kwargs ):
  return {
    'interpreter_path': '/path/to/virtual/environment/python'
  }
```

Here, `/path/to/virtual/environment/python` is the path to the Python used
by the virtual environment you are working in. Typically, the executable can be
found in the `Scripts` folder of the virtual environment directory on Windows
and in the `bin` folder on other platforms.

If you don't like having to create a `.ycm_extra_conf.py` file at the root of
your project and would prefer to specify the interpreter path with a Vim option,
read the [Configuring through Vim options](#configuring-through-vim-options)
section.

#### Working with third-party packages

Another common practice is to put the dependencies directly into the project and
add their paths to `sys.path` at runtime in order to import them. YCM needs to
be told about this path manipulation to support those dependencies. This can be
done by creating a `.ycm_extra_conf.py` file at the root of the project. This
file must define a `Settings( **kwargs )` function returning a dictionary with
the list of paths to prepend to `sys.path` under the `sys_path` key. For
instance, the following `.ycm_extra_conf.py` adds the paths
`/path/to/some/third_party/package` and `/path/to/another/third_party/package`
at the start of `sys.path`:

```python
def Settings( **kwargs ):
  return {
    'sys_path': [
      '/path/to/some/third_party/package',
      '/path/to/another/third_party/package'
    ]
  }
```

If you would rather prepend paths to `sys.path` with a Vim option, read the
[Configuring through Vim options](#configuring-through-vim-options) section.

If you need further control on how to add paths to `sys.path`, you should define
the `PythonSysPath( **kwargs )` function in the `.ycm_extra_conf.py` file. Its
keyword arguments are `sys_path` which contains the default `sys.path`, and
`interpreter_path` which is the path to the Python interpreter. Here's a trivial
example that inserts the `/path/to/third_party/package` path at the second
position of `sys.path`:

```python
def PythonSysPath( **kwargs ):
  sys_path = kwargs[ 'sys_path' ]
  sys_path.insert( 1, '/path/to/third_party/package' )
  return sys_path
```

A more advanced example can be found in [YCM's own
`.ycm_extra_conf.py`][ycm_flags_example].

#### Configuring through Vim options

You may find it inconvenient to have to create a `.ycm_extra_conf.py` file at the
root of each one of your projects in order to set the path to the Python
interpreter and/or add paths to `sys.path` and would prefer to be able to
configure those through Vim options. Don't worry, this is possible by using the
[`g:ycm_extra_conf_vim_data`](#the-gycm_extra_conf_vim_data-option) option and
creating a global extra configuration file. Let's take an example. Suppose that
you want to set the interpreter path with the `g:ycm_python_interpreter_path`
option and prepend paths to `sys.path` with the `g:ycm_python_sys_path` option.
Suppose also that you want to name the global extra configuration file
`global_extra_conf.py` and that you want to put it in your HOME folder. You
should then add the following lines to your vimrc:

```viml
let g:ycm_python_interpreter_path = ''
let g:ycm_python_sys_path = []
let g:ycm_extra_conf_vim_data = [
  \  'g:ycm_python_interpreter_path',
  \  'g:ycm_python_sys_path'
  \]
let g:ycm_global_ycm_extra_conf = '~/global_extra_conf.py'
```

Then, create the `~/global_extra_conf.py` file with the following contents:

```python
def Settings( **kwargs ):
  client_data = kwargs[ 'client_data' ]
  return {
    'interpreter_path': client_data[ 'g:ycm_python_interpreter_path' ],
    'sys_path': client_data[ 'g:ycm_python_sys_path' ]
  }
```

That's it. You are done. Note that you don't need to restart the server when
setting one of the options. YCM will automatically pick the new values.

### Rust Semantic Completion

YCM uses [rust-analyzer][] for Rust semantic completion.

NOTE: Previously, YCM used [rls][] for rust completion. This is no longer
supported, as the Rust community has decided on [rust-analyzer][] as the future
of Rust tooling.

Completions and GoTo commands within the current crate and its dependencies
should work out of the box with no additional configuration (provided that you
built YCM with the `--rust-completer` flag; see the [*Installation*
section](#installation) for details). The install script takes care of
installing [the Rust source code][rust-src], so no configuration is necessary.

`rust-analyzer` supports a myriad of options. These are configured using [LSP
configuration](#lsp-configuration), and are [documented here](https://rust-analyzer.github.io/manual.html#configuration]).

### Go Semantic Completion

Completions and GoTo commands should work out of the box (provided that you
built YCM with the `--go-completer` flag; see the [*Installation*
section](#installation) for details). The server only works for projects with
the "canonical" layout.

`gopls` also has a load of [documented options](https://github.com/golang/tools/blob/master/gopls/doc/settings.md).

You can set these in your `.ycm_extra_conf.py`. For example, to set the build tags:

```python
def Settings( **kwargs ):
  if kwargs[ 'language' ] == 'go':
    return {
       'ls': {
         'build.buildFlags': [ '-tags=debug' ] }
       }
    }
```

### JavaScript and TypeScript Semantic Completion

**NOTE:** YCM originally used the [Tern][] engine for JavaScript but due to
[Tern][] not being maintained anymore by its main author and the [TSServer][]
engine offering more features, YCM is moving to [TSServer][]. This won't affect
you if you were already using [Tern][] but you are encouraged to do the switch
by deleting the `third_party/ycmd/third_party/tern_runtime/node_modules`
directory in YCM folder. If you are a new user but still want to use [Tern][],
you should pass the `--js-completer` option to the `install.py` script during
installation. Further instructions on how to set up YCM with [Tern][] are
available on [the wiki][tern-instructions].

All JavaScript and TypeScript features are provided by the [TSServer][] engine,
which is included in the TypeScript SDK. To enable these features, install
[Node.js 18+ and npm][npm-install] and call the `install.py` script with the
`--ts-completer` flag.

[TSServer][] relies on [the `jsconfig.json` file][jsconfig.json] for JavaScript
and [the `tsconfig.json` file][tsconfig.json] for TypeScript to analyze your
project. Ensure the file exists at the root of your project.

To get diagnostics in JavaScript, set the `checkJs` option to `true` in your
`jsconfig.json` file:

```json
{
    "compilerOptions": {
        "checkJs": true
    }
}
```

### Semantic Completion for Other Languages

C-family, C#, Go, Java, Python, Rust, and JavaScript/TypeScript languages are
supported natively by YouCompleteMe using the [Clang][], [OmniSharp-Roslyn][],
[Gopls][], [jdt.ls][], [Jedi][], [rust-analyzer][], and [TSServer][] engines,
respectively. Check the [installation](#installation) section for instructions
to enable these features if desired.

#### Plugging an arbitrary LSP server

Similar to other LSP clients, YCM can use an arbitrary LSP server with the help
of [`g:ycm_language_server`](#the-gycm_language_server-option) option. An
example of a value of this option would be:

```viml
let g:ycm_language_server = 
  \ [ 
  \   {
  \     'name': 'yaml',
  \     'cmdline': [ '/path/to/yaml/server/yaml-language-server', '--stdio' ],
  \     'filetypes': [ 'yaml' ]
  \   },
  \   {
  \     'name': 'csharp',
  \     'cmdline': [ 'OmniSharp', '-lsp' ],
  \     'filetypes': [ 'csharp' ],
  \     'project_root_files': [ '*.csproj', '*.sln' ]
  \   },
  \   {
  \     'name': 'godot',
  \     'filetypes': [ 'gdscript' ],
  \     'port': 6008,
  \     'project_root_files': [ 'project.godot' ]
  \    }
  \ ]
```

Each dictionary contains the following keys:

* `name` (string, mandatory): When [configuring a LSP
  server](#lsp-configuration) the value of the `name` key will be used as the
  `kwargs[ 'language' ]`. Can be anything you like.
* `filetypes` (list of string, mandatory): List of Vim filetypes this server
  should be used for.
* `project_root_files` (list of string, optional): List of filenames to search
  for when trying to determine the project's root. Uses python's pathlib for
  glob matching.
* `cmdline` (list of strings, optional): If supplied, the server is started with
  this command line (each list element is a command line word). Typically, the
  server should be started with STDIO communication. If not supplied, `port`
  must be supplied.
* `port` (number, optional): If supplied, ycmd will connect to the server at
  `localhost:<port>` using TCP (remote servers are not supported).
* `capabilities` (dict, optional): If supplied, this is a dictionary that is
  merged with the LSP client capabilities reported to the language server. This
  can be used to enable or disable certain features, such as the support for
  configuration sections (`workspace/configuration`).

See [the LSP Examples](https://github.com/ycm-core/lsp-examples) project for more
examples of configuring the likes of PHP, Ruby, Kotlin, and D.

#### LSP Configuration

Many LSP servers allow some level of user configuration. YCM enables this with
the help of `.ycm_extra_conf.py` files. Here's an example of jdt.ls user
examples of configuring the likes of PHP, Ruby, Kotlin, D, and many, many more.

```python
def Settings( **kwargs ):
  if kwargs[ 'language' ] == 'java':
    return {
      'ls': {
        'java.format.onType.enabled': True
      }
    }
```

The `ls` key tells YCM that the dictionary should be passed to the LSP server.
For each of the LSP server's configuration, you should look up the respective
server's documentation.

Some servers request settings from arbitrary 'sections' of configuration. There
is no concept of configuration sections in Vim, so you can specify an additional
`config_sections` dictionary which maps section to a dictionary of config
required by the server. For example:

```python
def Settings( **kwargs ):
  if kwargs[ 'language' ] == 'java':
    return {
      'ls': {
        'java.format.onType.enabled': True
      },
      'config_sections': {
        'some section': {
          'some option': 'some value'
        }
    }
```

The sections and options/values are completely server-specific and rarely well
documented.

#### Using `omnifunc` for semantic completion

YCM will use your `omnifunc` (see `:h omnifunc` in Vim) as a source for semantic
completions if it does not have a native semantic completion engine for your
file's filetype. Vim comes with rudimentary omnifuncs for various languages like
Ruby, PHP, etc. It depends on the language.

You can get a stellar omnifunc for Ruby with [Eclim][]. Just make sure you have
the _latest_ Eclim installed and configured (this means Eclim `>= 2.2.*` and
Eclipse `>= 4.2.*`).

After installing Eclim remember to create a new Eclipse project within your
application by typing `:ProjectCreate <path-to-your-project> -n ruby` inside Vim
and don't forget to have `let g:EclimCompletionMethod = 'omnifunc'` in your
vimrc. This will make YCM and Eclim play nice; YCM will use Eclim's omnifuncs as
the data source for semantic completions and provide the auto-triggering and
subsequence-based matching (and other YCM features) on top of it.

### Writing New Semantic Completers

You have two options here: writing an `omnifunc` for Vim's omnicomplete system
that YCM will then use through its omni-completer, or a custom completer for YCM
using the [Completer API][completer-api].

Here are the differences between the two approaches:

- You have to use VimScript to write the omnifunc, but get to use Python to
  write for the Completer API; this by itself should make you want to use the
  API.
- The Completer API is a _much_ more powerful way to integrate with YCM and it
  provides a wider set of features. For instance, you can make your Completer
  query your semantic back-end in an asynchronous fashion, thus not blocking
  Vim's GUI thread while your completion system is processing stuff. This is
  impossible with VimScript. All of YCM's completers use the Completer API.
- Performance with the Completer API is better since Python executes faster than
  VimScript.

If you want to use the `omnifunc` system, see the relevant Vim docs with `:h
complete-functions`. For the Completer API, see [the API docs][completer-api].

If you want to upstream your completer into YCM's source, you should use the
Completer API.

### Diagnostic Display

YCM will display diagnostic notifications for the C-family, C#, Go, Java,
JavaScript, Rust, and TypeScript languages. Since YCM continuously recompiles
your file as you type, you'll get notified of errors and warnings in your file
as fast as possible.

Here are the various pieces of the diagnostic UI:

- Icons show up in the Vim gutter on lines that have a diagnostic.
- Regions of text related to diagnostics are highlighted (by default, a red
  wavy underline in `gvim` and a red background in `vim`).
- Moving the cursor to a line with a diagnostic echoes the diagnostic text.
- Vim's location list is automatically populated with diagnostic data (off by
  default, see options).

The new diagnostics (if any) will be displayed the next time you press any key
on the keyboard. So if you stop typing and just wait for the new diagnostics to
come in, that _will not work_. You need to press some key for the GUI to update.

Having to press a key to get the updates is unfortunate, but cannot be changed
due to the way Vim internals operate; there is no way that a background task can
update Vim's GUI after it has finished running.  You _have to_ press a key. This
will make YCM check for any pending diagnostics updates.

You _can_ force a full, blocking compilation cycle with the
`:YcmForceCompileAndDiagnostics` command (you may want to map that command to a
key; try putting `nnoremap <F5> :YcmForceCompileAndDiagnostics<CR>` in your
vimrc). Calling this command will force YCM to immediately recompile your file
and display any new diagnostics it encounters. Do note that recompilation with
this command may take a while and during this time the Vim GUI _will_ be
blocked.

YCM will display a short diagnostic message when you move your cursor to the
line with the error. You can get a detailed diagnostic message with the
`<leader>d` key mapping (can be changed in the options) YCM provides when your
cursor is on the line with the diagnostic.

You can also see the full diagnostic message for all the diagnostics in the
current file in Vim's `locationlist`, which can be opened with the `:lopen` and
`:lclose` commands (make sure you have set `let
g:ycm_always_populate_location_list = 1` in your vimrc). A good way to toggle
the display of the `locationlist` with a single key mapping is provided by
another (very small) Vim plugin called [ListToggle][] (which also makes it
possible to change the height of the `locationlist` window), also written by
yours truly.

#### Diagnostic Highlighting Groups

You can change the styling for the highlighting groups YCM uses. For the signs
in the Vim gutter, the relevant groups are:

- `YcmErrorSign`, which falls back to group `SyntasticErrorSign` and then
  `error` if they exist
- `YcmWarningSign`, which falls back to group `SyntasticWarningSign` and then
  `todo` if they exist

You can also style the line that has the warning/error with these groups:

- `YcmErrorLine`, which falls back to group `SyntasticErrorLine` if it exists
- `YcmWarningLine`, which falls back to group `SyntasticWarningLine` if it
  exists

Finally, you can also style the popup for the detailed diagnostics (it is shown
if `g:ycm_show_detailed_diag_in_popup` is set) using the group `YcmErrorPopup`,
which falls back to `ErrorMsg`.

Note that the line highlighting groups only work when the
[`g:ycm_enable_diagnostic_signs`](#the-gycm_enable_diagnostic_signs-option)
option is set. If you want highlighted lines but no signs in the Vim gutter,
set the `signcolumn` option to `no` in your vimrc:

```viml
set signcolumn=no
```

The syntax groups used to highlight regions of text with errors/warnings:
- `YcmErrorSection`, which falls back to group `SyntasticError` if it exists and
  then `SpellBad`
- `YcmWarningSection`, which falls back to group `SyntasticWarning` if it exists
  and then `SpellCap`

Here's how you'd change the style for a group:

```viml
highlight YcmErrorLine guibg=#3f0000
```

### Symbol Search

***This feature requires Vim and is not supported in Neovim***

YCM provides a way to search for and jump to a symbol in the current project or
document when using supported languages.

You can search for symbols in the current workspace when the `GoToSymbol`
request is supported and the current document when `GoToDocumentOutline` is
supported.

Here's a quick demo: 

[![asciicast](https://asciinema.org/a/4JmYLAaz5hOHbZDD0hbsQpY8C.svg)](https://asciinema.org/a/4JmYLAaz5hOHbZDD0hbsQpY8C)

As you can see, you can type and YCM filters down the list as you type. The
current set of matches are displayed in a popup window in the centre of the
screen and you can select an entry with the keyboard, to jump to that position.
Any matches are then added to the quickfix list.

To enable:

* `nmap <something> <Plug>(YCMFindSymbolInWorkspace)`
* `nmap <something> <Plug>(YCMFindSymbolInDocument)`

e.g.

* `nmap <leader>yfw <Plug>(YCMFindSymbolInWorkspace)`
* `nmap <leader>yfd <Plug>(YCMFindSymbolInDocument)`

When searching, YCM opens a prompt buffer at the top of the screen for the
input and puts you in insert mode. This means that you can hit `<Esc>` to go
into normal mode and use any other input commands that are supported in prompt
buffers. As you type characters, the search is updated.

Initially, results are queried from all open filetypes. You can hit `<C-f>` to
switch to just the current filetype while the popup is open.

While the popup is open, the following keys are intercepted:

* `<C-j>`, `<Down>`, `<C-n>`, `<Tab>` - select the next item
* `<C-k>`, `<Up>`, `<C-p>`, `<S-Tab>` - select the previous item
* `<PageUp>`, `<kPageUp>` - jump up one screenful of items 
* `<PageDown>`, `<kPageDown>` - jump down one screenful of items
* `<Home>`, `<kHome>` - jump to first item
* `<End>`, `<kEnd>` - jump to last item
* `<CR>` - jump to the selected item
* `<C-c>` cancel/dismiss the popup
* `<C-f>` - toggle results from all file types or just the current filetype

The search is also cancelled if you leave the prompt buffer window at any time,
so you can use window commands `<C-w>...` for example.

#### Closing the popup

***NOTE***: Pressing `<Esc>` does not close the popup - you must use `Ctrl-c`
for that, or use a window command (e.g. `<Ctrl-w>j`) or the mouse to leave the
prompt buffer window.

### Type/Call Hierarchy

***This feature requires Vim and is not supported in Neovim***

**NOTE**: This feature is highly experimental and offered in the hope that it is
useful. Please help us by reporting issues and offering feedback.

YCM provides a way to view and navigate hierarchies. The following hierarchies
are supported:

* Type hierachy `<Plug>(YCMTypeHierarchy)`: Display subtypes and supertypes
  of the symbol under cursor. Expand down to subtypes and up to supertypes.
* Call hierarchy `<Plug>(YCMCallHierarchy)`: Display callees and callers of
  the symbol under cursor. Expand down to callers and up to callees.

Take a look at this [![asciicast](https://asciinema.org/a/659925.svg)](https://asciinema.org/a/659925)
for brief demo.

Hierarchy UI can be initiated by mapping something to the indicated plug
mappings, for example:

```viml
nmap <leader>yth <Plug>(YCMTypeHierarchy)
nmap <leader>ych <Plug>(YCMCallHierarchy)
```

This opens a "modal" popup showing the current element in the hierarchy tree.
The current tree root is aligned to the left and child and parent nodes are
expanded to the right. Expand the tree "down" with `<Tab> and "up" with
`<S-Tab>`.

The "root" of the tree can be re-focused to the selected item with
`<S-Tab>` and further `<S-Tab>` will show the parents of the selected item. This
can take a little getting used to, but it's particularly important with multiple
inheritance where a "child" of the current root may actually have other,
invisible, parent links. `<S-Tab>` on that row will show these by setting the
display root to the selected item.

When the hierarchy is displayed, the following keys are intercepted:

* `<Tab>`: Drill into the hierarchy at the selected item: expand and show
  children of the selected item.
* `<S-Tab>`: Show parents of the selected item. When applied to sub-types, this
  will re-root the tree at that type, so that all parent types (are displayed).
  Similar for callers.
* `<CR>`: Jump to the symbol currently selected.
* `<Down>`, `<C-n>`, `<C-j>`, `j`: Select the next item
* `<Up>`, `<C-p>`, `<C-k>`, `k`; Select the previous item
* Any other key: closes the popup without jumping to any location

**Note:** you might think the call hierarchy tree is inverted, but we think
this way round is more intuitive because this is the typical way that call
stacks are displayed (with the current function at the top, and its callers
below). 

Commands
--------

### The `:YcmRestartServer` command

If the [ycmd completion server][ycmd] suddenly stops for some reason, you can
restart it with this command.

### The `:YcmForceCompileAndDiagnostics` command

Calling this command will force YCM to immediately recompile your file
and display any new diagnostics it encounters. Do note that recompilation with
this command may take a while and during this time the Vim GUI _will_ be
blocked.

You may want to map this command to a key; try putting `nnoremap <F5>
:YcmForceCompileAndDiagnostics<CR>` in your vimrc.

### The `:YcmDiags` command

Calling this command will fill Vim's `locationlist` with errors or warnings if
any were detected in your file and then open it. If a given error or warning can
be fixed by a call to `:YcmCompleter FixIt`, then ` (FixIt available)` is
appended to the error or warning text. See the `FixIt` completer subcommand for
more information.

**NOTE:** The absence of ` (FixIt available)` does not strictly imply a fix-it
is not available as not all completers are able to provide this indication. For
example, the c-sharp completer provides many fix-its but does not add this
additional indication.

The `g:ycm_open_loclist_on_ycm_diags` option can be used to prevent the location
list from opening, but still have it filled with new diagnostic data. See the
_Options_ section for details.

### The `:YcmShowDetailedDiagnostic` command

This command shows the full diagnostic text when the user's cursor is on the
line with the diagnostic.

An options argument can be passed. If the argument is `popup` the diagnostic
text will be displayed in a popup at the cursor position.

If you prefer the detailed diagnostic to always be shown in a popup, then
`let g:ycm_show_detailed_diag_in_popup=1`.

### The `:YcmDebugInfo` command

This will print out various debug information for the current file. Useful to
see what compile commands will be used for the file if you're using the semantic
completion engine.

### The `:YcmToggleLogs` command

This command presents the list of logfiles created by YCM, the [ycmd
server][ycmd], and the semantic engine server for the current filetype, if any.
One of these logfiles can be opened in the editor (or closed if already open) by
entering the corresponding number or by clicking on it with the mouse.
Additionally, this command can take the logfile names as arguments. Use the
`<TAB>` key (or any other key defined by the `wildchar` option) to complete the
arguments or to cycle through them (depending on the value of the `wildmode`
option). Each logfile given as an argument is directly opened (or closed if
already open) in the editor. Only for debugging purposes.

### The `:YcmCompleter` command

This command gives access to a number of additional [IDE-like
features](#quick-feature-summary) in YCM, for things like semantic GoTo, type
information, FixIt, and refactoring.

This command accepts a range that can either be specified through a selection in
one of Vim's visual modes (see `:h visual-use`) or on the command line. For
instance, `:2,5YcmCompleter` will apply the command from line 2 to line 5. This
is useful for [the `Format` subcommand](#the-format-subcommand).

Call `YcmCompleter` without further arguments for a list of the commands you can
call for the current completer.

See the [file type feature summary](#quick-feature-summary) for an overview of
the features available for each file type. See the _YcmCompleter subcommands_
section for more information on the available subcommands and their usage.

Some commands, like `Format` accept a range, like `:%YcmCompleter Format`.

Some commands like `GetDoc` and the various `GoTo` commands respect modifiers,
like `:rightbelow YcmCompleter GetDoc`, `:vertical YcmCompleter GoTo`.

YcmCompleter Subcommands
------------------------

**NOTE:** See the docs for the `YcmCompleter` command before tackling this
section.

The invoked subcommand is automatically routed to the currently active semantic
completer, so `:YcmCompleter GoToDefinition` will invoke the `GoToDefinition`
subcommand on the Python semantic completer if the currently active file is a
Python one and on the Clang completer if the currently active file is a C-family
language one.

You may also want to map the subcommands to something less verbose; for
instance, `nnoremap <leader>jd :YcmCompleter GoTo<CR>`
maps the `<leader>jd` sequence to the longer subcommand invocation.

### GoTo Commands

These commands are useful for jumping around and exploring code. When moving
the cursor, the subcommands add entries to Vim's `jumplist` so you can use
`CTRL-O` to jump back to where you were before invoking the command (and
`CTRL-I` to jump forward; see `:h jumplist` for details). If there is more
than one destination, the quickfix list (see `:h quickfix`) is populated with
the available locations and opened to the full width at the bottom of the screen.
You can change this behavior by using [the `YcmQuickFixOpened`
autocommand](#the-ycmquickfixopened-autocommand).

#### The `GoToInclude` subcommand

Looks up the current line for a header and jumps to it.

Supported in filetypes: `c, cpp, objc, objcpp, cuda`

#### The `GoToAlternateFile` subcommand

Jump to the associated file, as defined by the language server. Typically this
will jump you to the associated header file for a C or C++ translation unit.

Supported in filetypes: `c, cpp, objc, objcpp, cuda` (clangd only)

#### The `GoToDeclaration` subcommand

Looks up the symbol under the cursor and jumps to its declaration.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript,
python, rust, typescript`

#### The `GoToDefinition` subcommand

Looks up the symbol under the cursor and jumps to its definition.

**NOTE:** For C-family languages **this only works in certain situations**,
namely when the definition of the symbol is in the current translation unit. A
translation unit consists of the file you are editing and all the files you are
including with `#include` directives (directly or indirectly) in that file.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript,
python, rust, typescript`

#### The `GoTo` subcommand

This command tries to perform the "most sensible" GoTo operation it can.
Currently, this means that it tries to look up the symbol under the cursor and
jumps to its definition if possible; if the definition is not accessible from
the current translation unit, jumps to the symbol's declaration. For
C-family languages, it first tries to look up the current line for a header and
jump to it. For C#, implementations are also considered and preferred.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript,
python, rust, typescript`

#### The `GoToImprecise` subcommand

WARNING: This command trades correctness for speed!

Same as the `GoTo` command except that it doesn't recompile the file with
libclang before looking up nodes in the AST. This can be very useful when you're
editing files that take time to compile but you know that you haven't made any
changes since the last parse that would lead to incorrect jumps. When you're
just browsing around your codebase, this command can spare you quite a bit of
latency.

Supported in filetypes: `c, cpp, objc, objcpp, cuda`

#### The `GoToSymbol <symbol query>` subcommand

Finds the definition of all symbols matching a specified string. Note that this
does not use any sort of smart/fuzzy matching. However, an [interactive symbol
search](#symbol-search) is also available.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, java, javascript, python, typescript`

#### The `GoToReferences` subcommand

This command attempts to find all of the references within the project to the
identifier under the cursor and populates the quickfix list with those
locations.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust`

#### The `GoToImplementation` subcommand

Looks up the symbol under the cursor and jumps to its implementation (i.e.
non-interface). If there are multiple implementations, instead provides a list
of implementations to choose from.

Supported in filetypes: `cs, go, java, rust, typescript, javascript`

#### The `GoToImplementationElseDeclaration` subcommand

Looks up the symbol under the cursor and jumps to its implementation if one,
else jump to its declaration. If there are multiple implementations, instead
provides a list of implementations to choose from.

Supported in filetypes: `cs`

#### The `GoToType` subcommand

Looks up the symbol under the cursor and jumps to the definition of its type
e.g. if the symbol is an object, go to the definition of its class.

Supported in filetypes: `go, java, javascript, typescript`

#### The `GoToDocumentOutline` subcommand

Provides a list of symbols in the current document, in the quickfix list. See also
[interactive symbol search](#symbol-search).

Supported in filetypes: `c, cpp, objc, objcpp, cuda, go, java, rust`

#### The `GoToCallers` and `GoToCallees` subcommands

Note: A much more powerful call and type hierarchy can be viewd interactively.
See [interactive type and call hierarchy](#interactive-type-and-call-hierarchy).

Populate the quickfix list with the callers, or callees respectively, of the
function associated with the current cursor position. The semantics of this
differ depending on the filetype and language server.

Only supported for LSP servers that provide the `callHierarchyProvider`
capability.

### Semantic Information Commands

These commands are useful for finding static information about the code, such
as the types of variables, viewing declarations, and documentation strings.

#### The `GetType` subcommand

Echos the type of the variable or method under the cursor, and where it differs,
the derived type.

For example:

```c++
    std::string s;
```

Invoking this command on `s` returns `std::string => std::basic_string<char>`

**NOTE:** Causes re-parsing of the current translation unit.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript,
go, python, typescript, rust`

#### The `GetTypeImprecise` subcommand

WARNING: This command trades correctness for speed!

Same as the `GetType` command except that it doesn't recompile the file with
libclang before looking up nodes in the AST. This can be very useful when you're
editing files that take time to compile but you know that you haven't made any
changes since the last parse that would lead to incorrect type. When you're
just browsing around your codebase, this command can spare you quite a bit of
latency.

Supported in filetypes: `c, cpp, objc, objcpp, cuda`

#### The `GetParent` subcommand

Echos the semantic parent of the point under the cursor.

The semantic parent is the item that semantically contains the given position.

For example:

```c++
class C {
    void f();
};

void C::f() {

}
```

In the out-of-line definition of `C::f`, the semantic parent is the class `C`,
of which this function is a member.

In the example above, both declarations of `C::f` have `C` as their semantic
context, while the lexical context of the first `C::f` is `C` and the lexical
context of the second `C::f` is the translation unit.

For global declarations, the semantic parent is the translation unit.

**NOTE:** Causes re-parsing of the current translation unit.

Supported in filetypes: `c, cpp, objc, objcpp, cuda`

#### The `GetDoc` subcommand

Displays the preview window populated with quick info about the identifier
under the cursor. Depending on the file type, this includes things like:

* The type or declaration of identifier,
* Doxygen/javadoc comments,
* Python docstrings,
* etc.

The documentation is opened in the preview window, and options like
`previewheight` are respected. If you would like to customise the height and
position of this window, we suggest a custom command that:

* Sets `previewheight` temporarily
* Runs the `GetDoc` command with supplied modifiers
* Restores `previewheight`.

For example:

```viml
command -count ShowDocWithSize
  \ let g:ph=&previewheight 
  \ <bar> set previewheight=<count>
  \ <bar> <mods> YcmCompleter GetDoc
  \ <bar> let &previewheight=g:ph
```

You can then use something like `:botright vertical 80ShowDocWithSize`. Here's an
example of that: https://asciinema.org/a/hE6Pi1gU6omBShwFna8iwGEe9

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript,
python, typescript, rust`

#### The `GetDocImprecise` subcommand

WARNING: This command trades correctness for speed!

Same as the `GetDoc` command except that it doesn't recompile the file with
libclang before looking up nodes in the AST. This can be very useful when you're
editing files that take long to compile but you know that you haven't made any
changes since the last parse that would lead to incorrect docs. When you're
just browsing around your codebase, this command can spare you quite a bit of
latency.

Supported in filetypes: `c, cpp, objc, objcpp, cuda`

### Refactoring Commands

These commands make changes to your source code in order to perform refactoring
or code correction. YouCompleteMe does not perform any action which cannot be
undone, and never saves or writes files to the disk.

#### The `FixIt` subcommand

Where available, attempts to make changes to the buffer to correct diagnostics,
or perform refactoring, on the current line or selection. Where multiple
suggestions are available (such as when there are multiple ways to resolve a
given warning, or where multiple diagnostics are reported for the current line,
or multiple refactoring tweaks are available), the options are presented and
one can be selected.

Completers that provide diagnostics may also provide trivial modifications to
the source in order to correct the diagnostic. Examples include syntax errors
such as missing trailing semi-colons, spurious characters, or other errors which
the semantic engine can deterministically suggest corrections. A small demo
presenting how diagnostics can be fixed with clangd:

![YcmCompleter-FixIt-OnDiagnostic](https://user-images.githubusercontent.com/17928698/206855014-9131a49b-87e8-4ed4-8d91-f2fe7808a0b9.gif)

Completers (LSPs) may also provide refactoring tweaks, which may be available
even when no diagnostic is presented for the current line. These include
function extraction, variable extraction, `switch` population, constructor
generation, ... The tweaks work for a selection as well. Consult your LSP for
available refactorings. A demonstration of refactoring capabilities with clangd:

![YouCompleter-FixIt-Refactoring](https://user-images.githubusercontent.com/17928698/206855713-3588c8de-d0f5-4725-b65e-bc51110252cc.gif)

If no fix-it is available for the current line, or there is no diagnostic on the
current line, this command has no effect on the current buffer. If any
modifications are made, the number of changes made to the buffer is echo'd and
the user may use the editor's undo command to revert.

When a diagnostic is available, and `g:ycm_echo_current_diagnostic` is enabled,
then the text ` (FixIt)` is appended to the echo'd diagnostic when the
completer is able to add this indication. The text ` (FixIt available)` is
also appended to the diagnostic text in the output of the `:YcmDiags` command
for any diagnostics with available fix-its (where the completer can provide this
indication).

**NOTE:** Causes re-parsing of the current translation unit.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript,
rust, typescript`

#### The `RefactorRename <new name>` subcommand

In supported file types, this command attempts to perform a semantic rename of
the identifier under the cursor. This includes renaming declarations,
definitions, and usages of the identifier, or any other language-appropriate
action. The specific behavior is defined by the semantic engine in use.

Similar to `FixIt`, this command applies automatic modifications to your source
files. Rename operations may involve changes to multiple files, which may or may
not be open in Vim buffers at the time. YouCompleteMe handles all of this for
you. The behavior is described in [the following section](#multi-file-refactor).

Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust, cs`

#### Python refactorings

The following additional commands are supported for Python:

* `RefactorInline`
* `RefactorExtractVariable`
* `RefactorExtractFunction`

See the [jedi docs][jedi-refactor-doc] for what they do.

Supported in filetypes: `python`

#### Multi-file Refactor

When a Refactor or FixIt command touches multiple files, YouCompleteMe attempts
to apply those modifications to any existing open, visible buffer in the current
tab. If no such buffer can be found, YouCompleteMe opens the file in a new
small horizontal split at the top of the current window, applies the change,
and then *hides* the window. **NOTE:** The buffer remains open, and must be
manually saved. A confirmation dialog is opened prior to doing this to remind
you that this is about to happen.

Once the modifications have been made, the quickfix list (see `:help quickfix`)
is populated with the locations of all modifications. This can be used to review
all automatic changes made by using `:copen`. Typically, use the `CTRL-W
<enter>` combination to open the selected file in a new split. It is possible to
customize how the quickfix window is opened by using [the `YcmQuickFixOpened`
autocommand](#the-ycmquickfixopened-autocommand).

The buffers are *not* saved automatically. That is, you must save the modified
buffers manually after reviewing the changes from the quickfix list. Changes
can be undone using Vim's powerful undo features (see `:help undo`). Note
that Vim's undo is per-buffer, so to undo all changes, the undo commands must
be applied in each modified buffer separately.

**NOTE:** While applying modifications, Vim may find files that are already
open and have a swap file. The command is aborted if you select Abort or Quit in
any such prompts. This leaves the Refactor operation partially complete and must
be manually corrected using Vim's undo features. The quickfix list is *not*
populated in this case. Inspect `:buffers` or equivalent (see `:help buffers`)
to see the buffers that were opened by the command.

#### The `Format` subcommand

This command formats the whole buffer or some part of it according to the value
of the Vim options `shiftwidth` and `expandtab` (see `:h 'sw'` and `:h et`
respectively). To format a specific part of your document, you can either select
it in one of Vim's visual modes (see `:h visual-use`) and run the command or
directly enter the range on the command line, e.g. `:2,5YcmCompleter Format` to
format it from line 2 to line 5.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, java, javascript, go, typescript, rust, cs`

#### The `OrganizeImports` subcommand

This command removes unused imports and sorts imports in the current file. It
can also group imports from the same module in TypeScript and resolve imports
in Java.

Supported in filetypes: `java, javascript, typescript`

### Miscellaneous Commands

These commands are for general administration, rather than IDE-like features.
They cover things like the semantic engine server instance and compilation
flags.

#### The `ExecuteCommand <args>` subcommand

Some LSP completers (currently only Java completers) support executing
server-specific commands. Consult the [jdt.ls][] documentation to find out
what commands are supported and which arguments are expected.

The support for `ExecuteCommand` was implemented to support plugins like
[Vimspector][] to debug java, but isn't limited to that specific use case.

#### The `RestartServer` subcommand

Restarts the downstream semantic engine server for those semantic engines that
work as separate servers that YCM talks to.

Supported in filetypes: `c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript`

#### The `ReloadSolution` subcommand

Instruct the Omnisharp-Roslyn server to clear its cache and reload all files
from the disk.  This is useful when files are added, removed, or renamed in the
solution, files are changed outside of Vim, or whenever Omnisharp-Roslyn cache
is out-of-sync.

Supported in filetypes: `cs`

Functions
--------

### The `youcompleteme#GetErrorCount` function

Get the number of YCM Diagnostic errors. If no errors are present, this function
returns 0.

For example:

```viml
  call youcompleteme#GetErrorCount()
```

Both this function and `youcompleteme#GetWarningCount` can be useful when
integrating YCM with other Vim plugins. For example, a [lightline][] user could
add a diagnostics section to their statusline which would display the number of
errors and warnings.

### The `youcompleteme#GetWarningCount` function

Get the number of YCM Diagnostic warnings. If no warnings are present, this
function returns 0.

For example:

```viml
  call youcompleteme#GetWarningCount()
```

### The `youcompleteme#GetCommandResponse( ... )` function

Run a [completer subcommand](#ycmcompleter-subcommands) and return the result as
a string. This can be useful for example to display the `GetDoc` output in a
popup window, e.g.:

```viml
let s:ycm_hover_popup = -1
function s:Hover()
  let response = youcompleteme#GetCommandResponse( 'GetDoc' )
  if response == ''
    return
  endif

  call popup_hide( s:ycm_hover_popup )
  let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} )
endfunction

" CursorHold triggers in normal mode after a delay
autocmd CursorHold * call s:Hover()
" Or, if you prefer, a mapping:
nnoremap <silent> <leader>D :call <SID>Hover()<CR>
```

**NOTE**: This is only an example, for real hover support, see
[`g:ycm_auto_hover`](#the-gycm_auto_hover-option).

If the completer subcommand result is not a string (for example, it's a FixIt or
a Location), or if the completer subcommand raises an error, an empty string is
returned, so that calling code does not have to check for complex error
conditions.

The arguments to the function are the same as the arguments to the
`:YcmCompleter` ex command, e.g. the name of the subcommand, followed by any
additional subcommand arguments. As with the `YcmCompleter` command, if the
first argument is `ft=<filetype>` the request is targeted at the specified
filetype completer. This is an advanced usage and not necessary in most cases.

NOTE: The request is run synchronously and blocks Vim until the response is
received, so we do not recommend running this as part of an autocommand that
triggers frequently.

### The `youcompleteme#GetCommandResponseAsync( callback, ... )` function

This works exactly like `youcompleteme#GetCommandResponse`, except that instead
of returning the result, you supply a `callback` argument. This argument must be
a `FuncRef` to a function taking a single argument `response`. This callback
will be called with the command response at some point later, or immediately.

As with `youcompleteme#GetCommandResponse()`, this function will call the
callback with `''` (an empty string) if the request is not sent, or if there was
some sort of error.

Here's an example that's similar to the one above:

```viml

let s:ycm_hover_popup = -1
function! s:ShowDataPopup( response ) abort
  if response == ''
    return
  endif

  call popup_hide( s:ycm_hover_popup )
  let s:ycm_hover_popup = popup_atcursor( balloon_split( response ), {} )
endfunction

function! s:GetData() abort
  call youcompleteme#GetCommandResponseAsync(
    \ function( 's:ShowDataPopup' ),
    \ 'GetDoc' )
endfunction

autocommand CursorHold * call s:GetData()
```

Again, see [`g:ycm_auto_hover`](#the-gycm_auto_hover-option) for proper hover
support.

**NOTE**: The callback may be called immediately, in the stack frame that called
this function.

**NOTE**: Only one command request can be outstanding at once. Attempting to
request a second response while the first is outstanding will result in the
second callback being immediately called with `''`.

Autocommands
------------

### The `YcmLocationOpened` autocommand

This `User` autocommand is fired when YCM opens the location list window in
response to the `YcmDiags` command. By default, the location list window is
opened to the bottom of the current window and its height is set to fit all
entries. This behavior can be overridden by using the `YcmLocationOpened`
autocommand which is triggered while the cursor is in the location list window.
For instance:

```viml
function! s:CustomizeYcmLocationWindow()
  " Move the window to the top of the screen.
  wincmd K
  " Set the window height to 5.
  5wincmd _
  " Switch back to the working window.
  wincmd p
endfunction

autocmd User YcmLocationOpened call s:CustomizeYcmLocationWindow()
```

### The `YcmQuickFixOpened` autocommand

This `User` autocommand is fired when YCM opens the quickfix window in response
to the `GoTo*` and `RefactorRename` subcommands. By default, the quickfix window
is opened to full width at the bottom of the screen and its height is set to fit
all entries. This behavior can be overridden by using the `YcmQuickFixOpened`
autocommand which is triggered while the cursor is in the quickfix window. For
instance:

```viml
function! s:CustomizeYcmQuickFixWindow()
  " Move the window to the top of the screen.
  wincmd K
  " Set the window height to 5.
  5wincmd _
endfunction

autocmd User YcmQuickFixOpened call s:CustomizeYcmQuickFixWindow()
```

Options
-------

All options have reasonable defaults so if the plug-in works after installation
you don't need to change any options. These options can be configured in your
[vimrc script][vimrc] by including a line like this:

```viml
let g:ycm_min_num_of_chars_for_completion = 1
```

Note that after changing an option in your [vimrc script][vimrc] you have to
restart [ycmd][] with the `:YcmRestartServer` command for the changes to take
effect.

### The `g:ycm_min_num_of_chars_for_completion` option

This option controls the number of characters the user needs to type before
identifier-based completion suggestions are triggered. For example, if the
option is set to `2`, then when the user types a second alphanumeric character
after a whitespace character, completion suggestions will be triggered. This
option is NOT used for semantic completion.

Setting this option to a high number like `99` effectively turns off the
identifier completion engine and just leaves the semantic engine.

Default: `2`

```viml
let g:ycm_min_num_of_chars_for_completion = 2
```

### The `g:ycm_min_num_identifier_candidate_chars` option

This option controls the minimum number of characters that a completion
candidate coming from the identifier completer must have to be shown in the
popup menu.

A special value of `0` means there is no limit.

**NOTE:** This option only applies to the identifier completer; it has no effect
on the various semantic completers.

Default: `0`

```viml
let g:ycm_min_num_identifier_candidate_chars = 0
```

### The `g:ycm_max_num_candidates` option

This option controls the maximum number of semantic completion suggestions shown
in the completion menu. This only applies to suggestions from semantic
completion engines; see [the `g:ycm_max_identifier_candidates`
option](#the-gycm_max_num_identifier_candidates-option) to limit the number of
suggestions from the identifier-based engine.

A special value of `0` means there is no limit.

**NOTE:** Setting this option to `0` or to a value greater than `100` is not
recommended as it will slow down completion when there is a very large number
of suggestions.

Default: `50`

```viml
let g:ycm_max_num_candidates = 50
```

### The `g:ycm_max_num_candidates_to_detail` option

Some completion engines require completion candidates to be 'resolved' in order
to get detailed info such as inline documentation, method signatures, etc.  This
information is displayed by YCM in the preview window, or if `completeopt`
contains `popup`, in the info popup next to the completion menu.

By default, if the info popup is in use, and there are more than 10 candidates,
YCM will defer resolving candidates until they are selected in the completion
menu.  Otherwise, YCM must resolve the details upfront, which can be costly.

If neither `popup` nor `preview` are in `completeopt`, YCM disables resolving
altogether as the information would not be displayed.

This setting can be used to override these defaults and  controls the number of
completion candidates that should be resolved upfront. Typically users do not
need to change this, as YCM will work out an appropriate value based on your
`completeopt` and `g:ycm_add_preview_to_completeopt` settings. However, you may
override this calculation by setting this value to a number:

* `-1` - Resolve all candidates upfront
* `0` - Never resolve any candidates upfront.
* `> 0` - Resolve up to this many candidates upfront. If the number of
  candidates is greater than this value, no candidates are resolved.

In the latter two cases, if `completeopt` contains `popup`, then candidates are
resolved on demand asynchronously.

Default:

* `0` if neither `popup` nor `preview` are in `completeopt`.
* `10` if `popup` is in completeopt.
* `-1` if `preview` is in completeopt.

Example:

```viml
let g:ycm_max_num_candidates_to_detail = 0
```

### The `g:ycm_max_num_identifier_candidates` option

This option controls the maximum number of completion suggestions from the
identifier-based engine shown in the completion menu.

A special value of `0` means there is no limit.

**NOTE:** Setting this option to `0` or to a value greater than `100` is not
recommended as it will slow down completion when there is a very large number
of suggestions.

Default: `10`

```viml
let g:ycm_max_num_identifier_candidates = 10
```

### The `g:ycm_auto_trigger` option

When set to `0`, this option turns off YCM's identifier completer (the
as-you-type popup) _and_ the semantic triggers (the popup you'd get after typing
`.` or `->` in say C++). You can still force semantic completion with the
`<C-Space>` shortcut.

If you want to just turn off the identifier completer but keep the semantic
triggers, you should set `g:ycm_min_num_of_chars_for_completion` to a high
number like `99`.

When `g:ycm_auto_trigger` is `0`, YCM sets the `completefunc`, so that you can
manually trigger normal completion using `C-x C-u`.

If you want to map something else to trigger completion, such as `C-d`,
then you can map it to `<plug>(YCMComplete)`. For example:

```viml
let g:ycm_auto_trigger = 0
imap <c-d> <plug>(YCMComplete)
```

NOTE: It's not possible to map one of the keys in
`g:ycm_key_list_select_completion` (or similar) to `<plug>(YCMComplete)`. In
practice that means that you can't use `<Tab>` for this.

Default: `1`

```viml
let g:ycm_auto_trigger = 1
```

### The `g:ycm_filetype_whitelist` option

This option controls for which Vim filetypes (see `:h filetype`) should YCM be
turned on. The option value should be a Vim dictionary with keys being filetype
strings (like `python`, `cpp`, etc.) and values being unimportant (the
dictionary is used like a hash set, meaning that only the keys matter).

The `*` key is special and matches all filetypes. By default, the whitelist
contains only this `*` key.

YCM also has a `g:ycm_filetype_blacklist` option that lists filetypes for which
YCM shouldn't be turned on. YCM will work only in filetypes that both the
whitelist and the blacklist allow (the blacklist "allows" a filetype by _not_
having it as a key).

For example, let's assume you want YCM to work in files with the `cpp` filetype.
The filetype should then be present in the whitelist either directly (`cpp` key
in the whitelist) or indirectly through the special `*` key. It should _not_ be
present in the blacklist.

Filetypes that are blocked by either of the lists will be completely ignored
by YCM, meaning that neither the identifier-based completion engine nor the
semantic engine will operate in them.

You can get the filetype of the current file in Vim with `:set ft?`.

Default: `{'*': 1}`

```viml
let g:ycm_filetype_whitelist = {'*': 1}
```

** Completion in buffers with no filetype **

There is one exception to the above rule. YCM supports completion in buffers
with no filetype set, but this must be _explicitly_ whitelisted. To identify
buffers with no filetype, we use the `ycm_nofiletype` pseudo-filetype. To enable
completion in buffers with no filetype, set:

```viml
let g:ycm_filetype_whitelist = {
  \ '*': 1,
  \ 'ycm_nofiletype': 1
  \ }
```

### The `g:ycm_filetype_blacklist` option

This option controls for which Vim filetypes (see `:h filetype`) should YCM be
turned off. The option value should be a Vim dictionary with keys being filetype
strings (like `python`, `cpp`, etc.) and values being unimportant (the
dictionary is used like a hash set, meaning that only the keys matter).

See the `g:ycm_filetype_whitelist` option for more details on how this works.

Default: `[see next line]`

```viml
let g:ycm_filetype_blacklist = {
      \ 'tagbar': 1,
      \ 'notes': 1,
      \ 'markdown': 1,
      \ 'netrw': 1,
      \ 'unite': 1,
      \ 'text': 1,
      \ 'vimwiki': 1,
      \ 'pandoc': 1,
      \ 'infolog': 1,
      \ 'leaderf': 1,
      \ 'mail': 1
      \}
```

In addition, `ycm_nofiletype` (representing buffers with no filetype set)
is blacklisted if `ycm_nofiletype` is not _explicitly_ whitelisted (using
`g:ycm_filetype_whitelist`).

### The `g:ycm_filetype_specific_completion_to_disable` option

This option controls for which Vim filetypes (see `:h filetype`) should the YCM
semantic completion engine be turned off. The option value should be a Vim
dictionary with keys being filetype strings (like `python`, `cpp`, etc.) and
values being unimportant (the dictionary is used like a hash set, meaning that
only the keys matter). The listed filetypes will be ignored by the YCM semantic
completion engine, but the identifier-based completion engine will still trigger
in files of those filetypes.

Note that even if semantic completion is not turned off for a specific filetype,
you will not get semantic completion if the semantic engine does not support
that filetype.

You can get the filetype of the current file in Vim with `:set ft?`.

Default: `[see next line]`

```viml
let g:ycm_filetype_specific_completion_to_disable = {
      \ 'gitcommit': 1
      \}
```

### The `g:ycm_filepath_blacklist` option

This option controls for which Vim filetypes (see `:h filetype`) should filepath
completion be disabled. The option value should be a Vim dictionary with keys
being filetype strings (like `python`, `cpp`, etc.) and values being unimportant
(the dictionary is used like a hash set, meaning that only the keys matter).

The `*` key is special and matches all filetypes. Use this key if you want to
completely disable filepath completion:

```viml
let g:ycm_filepath_blacklist = {'*': 1}
```

You can get the filetype of the current file in Vim with `:set ft?`.

Default: `[see next line]`

```viml
let g:ycm_filepath_blacklist = {
      \ 'html': 1,
      \ 'jsx': 1,
      \ 'xml': 1,
      \}
```

### The `g:ycm_show_diagnostics_ui` option

When set, this option turns on YCM's diagnostic display features. See the
_Diagnostic display_ section in the _User Manual_ for more details.

Specific parts of the diagnostics UI (like the gutter signs, text highlighting,
diagnostic echo, and auto location list population) can be individually turned on
or off. See the other options below for details.

Note that YCM's diagnostics UI is only supported for C-family languages.

When set, this option also makes YCM remove all Syntastic checkers set for the
`c`, `cpp`, `objc`, `objcpp`, and `cuda` filetypes since this would conflict
with YCM's own diagnostics UI.

If you're using YCM's identifier completer in C-family languages but cannot use
the clang-based semantic completer for those languages _and_ want to use the GCC
Syntastic checkers, unset this option.

Default: `1`

```viml
let g:ycm_show_diagnostics_ui = 1
```

### The `g:ycm_error_symbol` option

YCM will use the value of this option as the symbol for errors in the Vim
gutter.

This option is part of the Syntastic compatibility layer; if the option is not
set, YCM will fall back to the value of the `g:syntastic_error_symbol` option
before using this option's default.

Default: `>>`

```viml
let g:ycm_error_symbol = '>>'
```

### The `g:ycm_warning_symbol` option

YCM will use the value of this option as the symbol for warnings in the Vim
gutter.

This option is part of the Syntastic compatibility layer; if the option is not
set, YCM will fall back to the value of the `g:syntastic_warning_symbol` option
before using this option's default.

Default: `>>`

```viml
let g:ycm_warning_symbol = '>>'
```

### The `g:ycm_enable_diagnostic_signs` option

When this option is set, YCM will put icons in Vim's gutter on lines that have a
diagnostic set. Turning this off will also turn off the `YcmErrorLine` and
`YcmWarningLine` highlighting.

This option is part of the Syntastic compatibility layer; if the option is not
set, YCM will fall back to the value of the `g:syntastic_enable_signs` option
before using this option's default.

Default: `1`

```viml
let g:ycm_enable_diagnostic_signs = 1
```

### The `g:ycm_enable_diagnostic_highlighting` option

When this option is set, YCM will highlight regions of text that are related to
the diagnostic that is present on a line, if any.

This option is part of the Syntastic compatibility layer; if the option is not
set, YCM will fall back to the value of the `g:syntastic_enable_highlighting`
option before using this option's default.

Default: `1`

```viml
let g:ycm_enable_diagnostic_highlighting = 1
```

### The `g:ycm_echo_current_diagnostic` option

When this option is set to 1, YCM will echo the text of the diagnostic present
on the current line when you move your cursor to that line. If a `FixIt` is
available for the current diagnostic, then ` (FixIt)` is appended.

If you have a Vim that supports virtual text, you can set this option
to the string `virtual-text`, and the diagnostic will be displayed inline with
the text, right aligned in the window and wrapping to the next line if there is
not enough space, for example:

![Virtual text diagnostic demo][diagnostic-echo-virtual-text1]

![Virtual text diagnostic demo][diagnostic-echo-virtual-text2]

**NOTE**: It's _strongly_ recommended to also set
`g:ycm_update_diagnostics_in_insert_mode` to `0` when using `virtual-text` for
diagnostics. This is due to the increased amount of distraction provided by
drawing diagnostics next to your input position.

This option is part of the Syntastic compatibility layer; if the option is not
set, YCM will fall back to the value of the `g:syntastic_echo_current_error`
option before using this option's default.

Default: `1`

Valid values:

* `0` - disabled
* `1` - echo diagnostic to the command area
* `'virtual-text'` - display the dignostic to the right of the line in the
  window using virtual text

```viml
let g:ycm_echo_current_diagnostic = 1
" Or, when you have Vim supporting virtual text
let g:ycm_echo_current_diagnostic = 'virtual-text'
```

### The `g:ycm_auto_hover` option

This option controls whether or not YCM shows documentation in a popup at the
cursor location after a short delay. Only supported in Vim.

When this option is set to `'CursorHold'`, the popup is displayed on the
`CursorHold` autocommand. See `:help CursorHold` for the details, but this means
that it is displayed after `updatetime` milliseconds.  When set to an empty
string, the popup is not automatically displayed.

In addition to this setting, there is the `<plug>(YCMHover)` mapping, which can
be used to manually trigger or hide the popup (it works like a toggle).
For example:

```viml
nmap <leader>D <plug>(YCMHover)
```

After dismissing the popup with this mapping, it will not be automatically
triggered again until the cursor is moved (i.e. `CursorMoved` autocommand).

The displayed documentation depends on what the completer for the current
language supports. It's selected heuristically in this order of preference:

1. `GetHover` with `markdown` syntax
2. `GetDoc` with no syntax
3. `GetType` with the syntax of the current file. 

You can customise this by manually setting up `b:ycm_hover` to your liking. This
buffer-local variable can be set to a dictionary with the following keys:

* `command`: The YCM completer subcommand which should be run on hover
* `syntax`: The syntax to use (as in `set syntax=`) in the popup window for
  highlighting.
* `popup_params`: The params passed to a popup window which gets opened.

For example, to use C/C++ syntax highlighting in the popup for C-family
languages, add something like this to your vimrc:

```viml
augroup MyYCMCustom
  autocmd!
  autocmd FileType c,cpp let b:ycm_hover = {
    \ 'command': 'GetDoc',
    \ 'syntax': &filetype
    \ }
augroup END
```

You can also modify the opened popup with `popup_params` key.
For example, you can limit the popup's maximum width and add a border to it:

```viml
augroup MyYCMCustom
  autocmd!
  autocmd FileType c,cpp let b:ycm_hover = {
    \ 'command': 'GetDoc',
    \ 'syntax': &filetype
    \ 'popup_params': {
    \     'maxwidth': 80,
    \     'border': [],
    \     'borderchars': ['─', '│', '─', '│', '┌', '┐', '┘', '└'],
    \   },
    \ }
augroup END
```
See `:help popup_create-arguments` for the list of available popup window options.

Default: `'CursorHold'`

### The `g:ycm_filter_diagnostics` option

This option controls which diagnostics will be rendered by YCM. This option
holds a dictionary of key-values, where the keys are Vim's filetype strings
delimited by commas and values are dictionaries describing the filter.

A filter is a dictionary of key-values, where the keys are the type of filter,
and the value is a list of arguments to that filter. In the case of just a
single item in the list, you may omit the brackets and just provide the argument
directly. If any filter matches a diagnostic, it will be dropped and YCM will
not render it.

The following filter types are supported:

- "regex": Accepts a string [regular expression][python-re]. This type matches
when the regex (treated as case-insensitive) is found anywhere in the diagnostic
text (`re.search`, not `re.match`)
- "level": Accepts a string level, either "warning" or "error." This type
matches when the diagnostic has the same level, that is,
specifying `level: "error"` will remove **all** errors from the diagnostics.

**NOTE:** The regex syntax is **NOT** Vim's, it's [Python's][python-re].

Default: `{}`

The following example will do, for Java filetype only:
- Remove **all** error level diagnostics, and,
- Also remove anything that contains `ta<something>co`

```viml
let g:ycm_filter_diagnostics = {
  \ "java": {
  \      "regex": [ "ta.+co", ... ],
  \      "level": "error",
  \      ...
  \    }
  \ }
```

### The `g:ycm_always_populate_location_list` option

When this option is set, YCM will populate the location list automatically every
time it gets new diagnostic data. This option is off by default so as not to
interfere with other data you might have placed in the location list.

See `:help location-list` in Vim to learn more about the location list.

This option is part of the Syntastic compatibility layer; if the option is not
set, YCM will fall back to the value of the
`g:syntastic_always_populate_loc_list` option before using this option's
default.

Note: if YCM's errors aren't visible, it might be that YCM is updating an older location list. See `:help :lhistory` and `:lolder`.

Default: `0`

```viml
let g:ycm_always_populate_location_list = 0
```

### The `g:ycm_open_loclist_on_ycm_diags` option

When this option is set, `:YcmDiags` will automatically open the location list
after forcing a compilation and filling the list with diagnostic data.

See `:help location-list` in Vim to learn more about the location list.

Default: `1`

```viml
let g:ycm_open_loclist_on_ycm_diags = 1
```

### The `g:ycm_complete_in_comments` option

When this option is set to `1`, YCM will show the completion menu even when
typing inside comments.

Default: `0`

```viml
let g:ycm_complete_in_comments = 0
```

### The `g:ycm_complete_in_strings` option

When this option is set to `1`, YCM will show the completion menu even when
typing inside strings.

Note that this is turned on by default so that you can use the filename
completion inside strings. This is very useful for instance in C-family files
where typing `#include "` will trigger the start of filename completion. If you
turn off this option, you will turn off filename completion in such situations
as well.

Default: `1`

```viml
let g:ycm_complete_in_strings = 1
```

### The `g:ycm_collect_identifiers_from_comments_and_strings` option

When this option is set to `1`, YCM's identifier completer will also collect
identifiers from strings and comments. Otherwise, the text in comments and
strings will be ignored.

Default: `0`

```viml
let g:ycm_collect_identifiers_from_comments_and_strings = 0
```

### The `g:ycm_collect_identifiers_from_tags_files` option

When this option is set to `1`, YCM's identifier completer will also collect
identifiers from tags files. The list of tags files to examine is retrieved from
the `tagfiles()` Vim function which examines the `tags` Vim option. See `:h
'tags'` for details.

YCM will re-index your tags files if it detects that they have been modified.

The only supported tag format is the [Exuberant Ctags format][ctags-format]. The
format from "plain" ctags is NOT supported. Ctags needs to be called with the
`--fields=+l` option (that's a lowercase `L`, not a one) because YCM needs the
`language:<lang>` field in the tags output.

See the _FAQ_ for pointers if YCM does not appear to read your tag files.

This option is off by default because it makes Vim slower if your tags are on a
network directory.

Default: `0`

```viml
let g:ycm_collect_identifiers_from_tags_files = 0
```

### The `g:ycm_seed_identifiers_with_syntax` option

When this option is set to `1`, YCM's identifier completer will seed its
identifier database with the keywords of the programming language you're
writing.

Since the keywords are extracted from the Vim syntax file for the filetype, all
keywords may not be collected, depending on how the syntax file was written.
Usually at least 95% of the keywords are successfully extracted.

Default: `0`

```viml
let g:ycm_seed_identifiers_with_syntax = 0
```

### The `g:ycm_extra_conf_vim_data` option

If you're using semantic completion for C-family files, this option might come
handy; it's a way of sending data from Vim to your `Settings` function in
your `.ycm_extra_conf.py` file.

This option is supposed to be a list of VimScript expression strings that are
evaluated for every request to the [ycmd server][ycmd] and then passed to your
`Settings` function as a `client_data` keyword argument.

For instance, if you set this option to `['v:version']`, your `Settings`
function will be called like this:

```python
# The '801' value is of course contingent on Vim 8.1; in 8.0 it would be '800'
Settings( ..., client_data = { 'v:version': 801 } )
```

So the `client_data` parameter is a dictionary mapping Vim expression strings to
their values at the time of the request.

The correct way to define parameters for your `Settings` function:

```python
def Settings( **kwargs ):
```

You can then get to `client_data` with `kwargs['client_data']`.

Default: `[]`

```viml
let g:ycm_extra_conf_vim_data = []
```

### The `g:ycm_server_python_interpreter` option

YCM will by default search for an appropriate Python interpreter on your system.
You can use this option to override that behavior and force the use of a
specific interpreter of your choosing.

**NOTE:** This interpreter is only used for the [ycmd server][ycmd]. The YCM
client running inside Vim always uses the Python interpreter that's embedded
inside Vim.

Default: `''`

```viml
let g:ycm_server_python_interpreter = ''
```

### The `g:ycm_keep_logfiles` option

When this option is set to `1`, YCM and the [ycmd completion server][ycmd] will
keep the logfiles around after shutting down (they are deleted on shutdown by
default).

To see where the log files are, call `:YcmDebugInfo`.

Default: `0`

```viml
let g:ycm_keep_logfiles = 0
```

### The `g:ycm_log_level` option

The logging level that YCM and the [ycmd completion server][ycmd] use. Valid
values are the following, from most verbose to least verbose:
- `debug`
- `info`
- `warning`
- `error`
- `critical`

Note that `debug` is _very_ verbose.

Default: `info`

```viml
let g:ycm_log_level = 'info'
```

### The `g:ycm_auto_start_csharp_server` option

When set to `1`, the OmniSharp-Roslyn server will be automatically started
(once per Vim session) when you open a C# file.

Default: `1`

```viml
let g:ycm_auto_start_csharp_server = 1
```

### The `g:ycm_auto_stop_csharp_server` option

When set to `1`, the OmniSharp-Roslyn server will be automatically stopped upon
closing Vim.

Default: `1`

```viml
let g:ycm_auto_stop_csharp_server = 1
```

### The `g:ycm_csharp_server_port` option

When g:ycm_auto_start_csharp_server is set to `1`, specifies the port for
the OmniSharp-Roslyn server to listen on. When set to `0` uses an unused port provided
by the OS.

Default: `0`

```viml
let g:ycm_csharp_server_port = 0
```

### The `g:ycm_csharp_insert_namespace_expr` option

By default, when YCM inserts a namespace, it will insert the `using` statement
under the nearest `using` statement. You may prefer that the `using` statement is
inserted somewhere, for example, to preserve sorting. If so, you can set this
option to override this behavior.

When this option is set, instead of inserting the `using` statement itself, YCM
will set the global variable `g:ycm_namespace_to_insert` to the namespace to
insert, and then evaluate this option's value as an expression. The option's
expression is responsible for inserting the namespace - the default insertion
will not occur.

Default: ''

```viml
let g:ycm_csharp_insert_namespace_expr = ''
```

### The `g:ycm_add_preview_to_completeopt` option

When this option is set to `1`, YCM will add the `preview` string to Vim's
`completeopt` option (see `:h completeopt`). If your `completeopt` option
already has `preview` set, there will be no effect. Alternatively, when set to
`popup` and your version of Vim supports popup windows (see `:help popup`), the
`popup` string will be used instead. You can see the current state of your
`completeopt` setting with `:set completeopt?` (yes, the question mark is
important).

When `preview` is present in `completeopt`, YCM will use the `preview` window at
the top of the file to store detailed information about the current completion
candidate (but only if the candidate came from the semantic engine). For
instance, it would show the full function prototype and all the function
overloads in the window if the current completion is a function name.

When `popup` is present in `completeopt`, YCM will instead use a `popup`
window to the side of the completion popup for storing detailed information
about the current completion candidate. In addition, YCM may truncate the
detailed completion information in order to give the popup sufficient room
to display that detailed information.

Default: `0`

```viml
let g:ycm_add_preview_to_completeopt = 0
```

### The `g:ycm_autoclose_preview_window_after_completion` option

When this option is set to `1`, YCM will auto-close the `preview` window after
the user accepts the offered completion string. If there is no `preview` window
triggered because there is no `preview` string in `completeopt`, this option is
irrelevant. See the `g:ycm_add_preview_to_completeopt` option for more details.

Default: `0`

```viml
let g:ycm_autoclose_preview_window_after_completion = 0
```

### The `g:ycm_autoclose_preview_window_after_insertion` option

When this option is set to `1`, YCM will auto-close the `preview` window after
the user leaves insert mode. This option is irrelevant if
`g:ycm_autoclose_preview_window_after_completion` is set or if no `preview`
window is triggered. See the `g:ycm_add_preview_to_completeopt` option for more
details.

Default: `0`

```viml
let g:ycm_autoclose_preview_window_after_insertion = 0
```

### The `g:ycm_max_diagnostics_to_display` option

This option controls the maximum number of diagnostics shown to the user when
errors or warnings are detected in the file. This option is only relevant for
the C-family, C#, Java, JavaScript, and TypeScript languages.

A special value of `0` means there is no limit.

Default: `30`

```viml
let g:ycm_max_diagnostics_to_display = 30
```

### The `g:ycm_key_list_select_completion` option

This option controls the key mappings used to select the first completion
string.  Invoking any of them repeatedly cycles forward through the completion
list.

Some users like adding `<Enter>` to this list.

Default: `['<TAB>', '<Down>']`

```viml
let g:ycm_key_list_select_completion = ['<TAB>', '<Down>']
```

### The `g:ycm_key_list_previous_completion` option

This option controls the key mappings used to select the previous completion
string. Invoking any of them repeatedly cycles backward through the completion
list.

Note that one of the defaults is `<S-TAB>` which means Shift-TAB. That mapping
will probably only work in GUI Vim (Gvim or MacVim) and not in plain console Vim
because the terminal usually does not forward modifier key combinations to Vim.

Default: `['<S-TAB>', '<Up>']`

```viml
let g:ycm_key_list_previous_completion = ['<S-TAB>', '<Up>']
```

### The `g:ycm_key_list_stop_completion` option

This option controls the key mappings used to close the completion menu. This is
useful when the menu is blocking the view, when you need to insert the `<TAB>`
character, or when you want to expand a snippet from [UltiSnips][] and navigate
through it.

Default: `['<C-y>']`

```viml
let g:ycm_key_list_stop_completion = ['<C-y>']
```

### The `g:ycm_key_invoke_completion` option

This option controls the key mapping used to invoke the completion menu for
semantic completion. By default, semantic completion is triggered automatically
after typing characters appropriate for the language, such as `.`, `->`, `::`,
etc. in insert mode (if semantic completion support has been compiled in). This
key mapping can be used to trigger semantic completion anywhere. Useful for
searching for top-level functions and classes.

Console Vim (not Gvim or MacVim) passes `<Nul>` to Vim when the user types
`<C-Space>` so YCM will make sure that `<Nul>` is used in the map command when
you're editing in console Vim, and `<C-Space>` in GUI Vim. This means that you
can just press `<C-Space>` in both the console and GUI Vim and YCM will do the right
thing.

Setting this option to an empty string will make sure no mapping is created.

Default: `<C-Space>`

```viml
let g:ycm_key_invoke_completion = '<C-Space>'
```

### The `g:ycm_key_detailed_diagnostics` option

This option controls the key mapping used to show the full diagnostic text when
the user's cursor is on the line with the diagnostic. It basically calls
`:YcmShowDetailedDiagnostic`.

Setting this option to an empty string will make sure no mapping is created.

If you prefer the detailed diagnostic to be shown in a popup, then
`let g:ycm_show_detailed_diag_in_popup=1`.

Default: `<leader>d`

```viml
let g:ycm_key_detailed_diagnostics = '<leader>d'
```

### The `g:ycm_show_detailed_diag_in_popup` option

Makes `:YcmShowDetailedDiagnostic` always show in a popup rather than echoing to
the command line.

Default: 0

```viml
let g:ycm_show_detailed_diag_in_popup = 0
```

### The `g:ycm_global_ycm_extra_conf` option

Normally, YCM searches for a `.ycm_extra_conf.py` file for compilation flags
(see the User Guide for more details on how this works). This option specifies
a fallback path to a config file which is used if no `.ycm_extra_conf.py` is
found.

You can place such a global file anywhere in your filesystem.

Default: `''`

```viml
let g:ycm_global_ycm_extra_conf = ''
```

### The `g:ycm_confirm_extra_conf` option

When this option is set to `1` YCM will ask once per `.ycm_extra_conf.py` file
if it is safe to be loaded. This is to prevent the execution of malicious code
from a `.ycm_extra_conf.py` file you didn't write.

To selectively get YCM to ask/not ask about loading certain `.ycm_extra_conf.py`
files, see the `g:ycm_extra_conf_globlist` option.

Default: `1`

```viml
let g:ycm_confirm_extra_conf = 1
```

### The `g:ycm_extra_conf_globlist` option

This option is a list that may contain several globbing patterns. If a pattern
starts with a `!` all `.ycm_extra_conf.py` files matching that pattern will be
blacklisted, that is they won't be loaded and no confirmation dialog will be
shown. If a pattern does not start with a `!` all files matching that pattern
will be whitelisted. Note that this option is not used when confirmation is
disabled using `g:ycm_confirm_extra_conf` and that items earlier in the list
will take precedence over the later ones.

Rules:

* `*`       matches everything
* `?`       matches any single character
* `[seq]`   matches any character in seq
* `[!seq]`  matches any char not in seq

Example:

```viml
let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*']
```

* The first rule will match everything contained in the `~/dev` directory so
  `.ycm_extra_conf.py` files from there will be loaded.
* The second rule will match everything in the home directory so a
  `.ycm_extra_conf.py` file from there won't be loaded.
* As the first rule takes precedence everything in the home directory excluding
  the `~/dev` directory will be blacklisted.

**NOTE:** The glob pattern is first expanded with Python's
`os.path.expanduser()` and then resolved with `os.path.abspath()` before being
matched against the filename.

Default: `[]`

```viml
let g:ycm_extra_conf_globlist = []
```

### The `g:ycm_filepath_completion_use_working_dir` option

By default, YCM's filepath completion will interpret relative paths like `../`
as being relative to the folder of the file of the currently active buffer.
Setting this option will force YCM to always interpret relative paths as being
relative to Vim's current working directory.

Default: `0`

```viml
let g:ycm_filepath_completion_use_working_dir = 0
```

### The `g:ycm_semantic_triggers` option

This option controls the character-based triggers for the various semantic
completion engines. The option holds a dictionary of key-values, where the keys
are Vim's filetype strings delimited by commas and values are lists of strings,
where the strings are the triggers.

Setting key-value pairs on the dictionary _adds_ semantic triggers to the
internal default set (listed below). You cannot remove the default triggers,
only add new ones.

A "trigger" is a sequence of one or more characters that trigger semantic
completion when typed. For instance, C++ (`cpp` filetype) has `.` listed as a
trigger. So when the user types `foo.`, the semantic engine will trigger and
serve `foo`'s list of member functions and variables. Since C++ also has `->`
listed as a trigger, the same thing would happen when the user typed `foo->`.

It's also possible to use a regular expression as a trigger. You have to prefix
your trigger with `re!` to signify it's a regex trigger. For instance,
`re!\w+\.` would only trigger after the `\w+\.` regex matches.

**NOTE:** The regex syntax is **NOT** Vim's, it's [Python's][python-re].

Default: `[see next line]`

```viml
let g:ycm_semantic_triggers =  {
  \   'c': ['->', '.'],
  \   'objc': ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s',
  \            're!\[.*\]\s'],
  \   'ocaml': ['.', '#'],
  \   'cpp,cuda,objcpp': ['->', '.', '::'],
  \   'perl': ['->'],
  \   'php': ['->', '::'],
  \   'cs,d,elixir,go,groovy,java,javascript,julia,perl6,python,scala,typescript,vb': ['.'],
  \   'ruby,rust': ['.', '::'],
  \   'lua': ['.', ':'],
  \   'erlang': [':'],
  \ }
```

### The `g:ycm_cache_omnifunc` option

Some omnicompletion engines do not work well with the YCM cache—in particular,
they might not produce all possible results for a given prefix. By unsetting
this option you can ensure that the omnicompletion engine is re-queried on every
keypress. That will ensure all completions will be presented but might cause
stuttering and lag if the omnifunc is slow.

Default: `1`

```viml
let g:ycm_cache_omnifunc = 1
```

### The `g:ycm_use_ultisnips_completer` option

By default, YCM will query the UltiSnips plugin for possible completions of
snippet triggers. This option can turn that behavior off.

Default: `1`

```viml
let g:ycm_use_ultisnips_completer = 1
```

### The `g:ycm_goto_buffer_command` option

Defines where `GoTo*` commands result should be opened. Can take one of the
following values: `'same-buffer'`, `'split'`, or `'split-or-existing-window'`.
If this option is set to the `'same-buffer'` but current buffer can not be
switched (when buffer is modified and `nohidden` option is set), then result
will be opened in a split. When the option is set to
`'split-or-existing-window'`, if the result is already open in a window of the
current tab page (or any tab pages with the `:tab` modifier; see below), it will
jump to that window. Otherwise, the result will be opened in a split as if the
option was set to `'split'`.

To customize the way a new window is split, prefix the `GoTo*` command with one
of the following modifiers: `:aboveleft`, `:belowright`, `:botright`,
`:leftabove`, `:rightbelow`, `:topleft`, and `:vertical`. For instance, to
split vertically to the right of the current window, run the command:

```viml
:rightbelow vertical YcmCompleter GoTo
```

To open in a new tab page, use the `:tab` modifier with the `'split'` or
`'split-or-existing-window'` options e.g.:

```viml
:tab YcmCompleter GoTo
```

Default: `'same-buffer'`

```viml
let g:ycm_goto_buffer_command = 'same-buffer'
```

### The `g:ycm_disable_for_files_larger_than_kb` option

Defines the max size (in Kb) for a file to be considered for completion. If this
option is set to 0 then no check is made on the size of the file you're opening.

Default: 1000

```viml
let g:ycm_disable_for_files_larger_than_kb = 1000
```

### The `g:ycm_use_clangd` option

This option controls whether **clangd** should be used as a completion engine for
C-family languages. Can take one of the following values: `1`, `0`, with
meanings:

- `1`: YCM will use clangd if clangd binary exists in third party or it was
provided with `ycm_clangd_binary_path` option.
- `0`: YCM will never use clangd completer.

Default: `1`

```viml
let g:ycm_use_clangd = 1
```

### The `g:ycm_clangd_binary_path` option

When `ycm_use_clangd` option is set to `1`, this option sets the path to
**clangd** binary.

Default: `''`

```viml
let g:ycm_clangd_binary_path = ''
```

### The `g:ycm_clangd_args` option

This option controls the command line arguments passed to the clangd binary. It
appends new options and overrides the existing ones.

Default: `[]`

```viml
let g:ycm_clangd_args = []
```

### The `g:ycm_clangd_uses_ycmd_caching` option

This option controls which ranking and filtering algorithm to use for completion
items. It can take values:

- `1`: Uses ycmd's caching and filtering logic.
- `0`: Uses clangd's caching and filtering logic.

Default: `1`

```viml
let g:ycm_clangd_uses_ycmd_caching = 1
```

### The `g:ycm_language_server` option

This option lets YCM use an arbitrary Language Server Protocol (LSP) server, not
unlike many other completion systems.  The officially supported completers are
favoured over custom LSP ones, so overriding an existing completer means first
making sure YCM won't choose that existing completer in the first place.

A simple working example of this option can be found in the section called
["Semantic Completion for Other Languages"](#semantic-completion-for-other-languages).

Many working examples can be found in the YCM [lsp-examples][] repo.

Default: `[]`

```viml
let g:ycm_language_server = []
```

### The `g:ycm_disable_signature_help` option

This option allows you to disable all signature help for all completion engines.
There is no way to disable it per-completer.

Default: `0`

```viml
" Disable signature help
let g:ycm_disable_signature_help = 1
```

### The `g:ycm_signature_help_disable_syntax` option

Set this to 1 to disable syntax highlighting in the signature help popup. Thiis
can help if your colourscheme doesn't work well with the default highliting and
inverse video.

Default: `0`

```viml
" Disable signature help syntax highliting
let g:ycm_signature_help_disable_syntax = 1
```

### The `g:ycm_gopls_binary_path` option

In case the system-wide `gopls` binary is newer than the bundled one, setting
this option to the path of the system-wide `gopls` would make YCM use that one
instead.

If the path is just `gopls`, YCM will search in `$PATH`.


### The `g:ycm_gopls_args` option

Similar to [the `g:ycm_clangd_args`](#the-gycm-clangd-args), this option allows
passing additional flags to the `gopls` command line.

Default: `[]`

```viml
let g:ycm_gopls_args = []
```


### The `g:ycm_rls_binary_path` and `g:ycm_rustc_binary_path` options

YCM no longer uses RLS for rust, and these options are therefore no longer
supported.

To use a custom rust-analyzer, see `g:ycm_rust_toolchain_root`.

### The `g:ycm_rust_toolchain_root` option

Optionally specify the path to a custom rust toolchain including at least a
supported version of `rust-analyzer`.


### The `g:ycm_tsserver_binary_path` option

Similar to [the `gopls` path](#the-gycm-gopls-binaty-path), this option
tells YCM where is the TSServer executable located.

### The `g:ycm_roslyn_binary_path` option

Similar to [the `gopls` path](#the-gycm-gopls-binaty-path), this option
tells YCM where is the Omnisharp-Roslyn executable located.

### The `g:ycm_update_diagnostics_in_insert_mode` option

With async diagnostics, LSP servers might send new diagnostics mid-typing.
If seeing these new diagnostics while typing is not desired, this option can
be set to 0.

When this option is set to `0`, diagnostic signs, virtual text, and highlights
are cleared when entering insert mode and replaced when leaving insert mode.
This reduces visual noise while editing.

In addition, this option is recommended when `g:ycm_echo_current_diagnostic` is
set to `virtual-text` as it prevents updating the virtual text while you are
typing.

Default: `1`

```viml
let g:ycm_update_diagnostics_in_insert_mode = 1
```

FAQ
---

The FAQ section has been moved to the [wiki][wiki-faq].

Contributor Code of Conduct
---------------------------

Please note that this project is released with a [Contributor Code of
Conduct][ccoc]. By participating in this project you agree to abide by its
terms.


Contact
-------

If you have questions about the plugin or need help, please join the [Gitter
room][gitter] or use the [ycm-users][] mailing list.

If you have bug reports or feature suggestions, please use the [issue
tracker][tracker]. Before you do, please carefully read
[CONTRIBUTING.md][contributing-md] as this asks for important diagnostics which
the team will use to help get you going.

The latest version of the plugin is available at
<https://ycm-core.github.io/YouCompleteMe/>.

The author's homepage is <https://val.markovic.io>.

Please do **NOT** go to #vim, Reddit, or Stack Overflow for support. Please
contact the YouCompleteMe maintainers directly using the [contact
details](#contact).

License
-------

This software is licensed under the [GPL v3 license][gpl].
© 2015-2018 YouCompleteMe contributors

Sponsorship
-----------

If you like YCM so much that you're willing to part with your hard-earned cash, please consider donating to one of the following charities, which are meaningful to the current maintainers (in no particular order):

* [Hector's Greyhound Rescue](https://www.hectorsgreyhoundrescue.org)
* [Be Humane](https://www.budihuman.rs/en)
* [Cancer Research UK](https://www.cancerresearchuk.org)
* [ICCF Holland](https://iccf.nl)
* Any charity of your choosing.

Please note: The YCM maintainers do not specifically endorse nor necessarily have any relationship with the above charities. Disclosure: It is noted that one key maintainer is a family with Trustees of Greyhound Rescue Wales.


[ycmd]: https://github.com/ycm-core/ycmd
[Clang]: https://clang.llvm.org/
[vundle]: https://github.com/VundleVim/Vundle.vim#about
[brew]: https://brew.sh
[cmake-download]: https://cmake.org/download/
[macvim]: https://macvim-dev.github.io/macvim/
[vimrc]: https://vimhelp.appspot.com/starting.txt.html#vimrc
[gpl]: https://www.gnu.org/copyleft/gpl.html
[vim]: https://www.vim.org/
[syntastic]: https://github.com/scrooloose/syntastic
[lightline]: https://github.com/itchyny/lightline.vim
[ycm_flags_example]: https://github.com/ycm-core/YouCompleteMe/blob/master/.ycm_extra_conf.py
[ycmd_flags_example]: https://raw.githubusercontent.com/ycm-core/ycmd/66030cd94299114ae316796f3cad181cac8a007c/.ycm_extra_conf.py
[compdb]: https://clang.llvm.org/docs/JSONCompilationDatabase.html
[subsequence]: https://en.wikipedia.org/wiki/Subsequence
[listtoggle]: https://github.com/Valloric/ListToggle
[vim-build]: https://github.com/ycm-core/YouCompleteMe/wiki/Building-Vim-from-source
[tracker]: https://github.com/ycm-core/YouCompleteMe/issues?state=open
[completer-api]: https://github.com/ycm-core/ycmd/blob/master/ycmd/completers/completer.py
[eclim]: http://eclim.org/
[jedi]: https://github.com/davidhalter/jedi
[ultisnips]: https://github.com/SirVer/ultisnips/blob/master/doc/UltiSnips.txt
[ctags-format]: http://ctags.sourceforge.net/FORMAT
[ycm-users]: https://groups.google.com/forum/?hl=en#!forum/ycm-users
[omnisharp-roslyn]: https://github.com/OmniSharp/omnisharp-roslyn
[python-re]: https://docs.python.org/2/library/re.html#regular-expression-syntax
[Bear]: https://github.com/rizsotto/Bear
[ygen]: https://github.com/rdnetto/YCM-Generator
[Gopls]: https://github.com/golang/go/wiki/gopls
[gopls-preferences]: https://github.com/golang/tools/blob/master/internal/lsp/server.go
[TSServer]: https://github.com/Microsoft/TypeScript/tree/master/src/server
[jsconfig.json]: https://code.visualstudio.com/docs/languages/jsconfig
[tsconfig.json]: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
[vim-win-download]: https://github.com/vim/vim-win32-installer/releases
[python-win-download]: https://www.python.org/downloads/windows/
[visual-studio-download]: https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=16
[mono-install-macos]: https://www.mono-project.com/download/stable/
[mono-install-linux]: https://www.mono-project.com/download/stable/#download-lin
[go-install]: https://golang.org/doc/install
[npm-install]: https://docs.npmjs.com/getting-started/installing-node#1-install-nodejs--npm
[tern-instructions]: https://github.com/ycm-core/YouCompleteMe/wiki/JavaScript-Semantic-Completion-through-Tern
[libclang-instructions]: https://github.com/ycm-core/YouCompleteMe/wiki/C-family-Semantic-Completion-through-libclang
[Tern]: https://ternjs.net
[rls]: https://github.com/rust-lang/rls
[rust-analyzer]: https://rust-analyzer.github.io
[rust-src]: https://www.rust-lang.org/downloads.html
[add-msbuild-to-path]: https://stackoverflow.com/questions/6319274/how-do-i-run-msbuild-from-the-command-line-using-windows-sdk-7-1
[ccoc]: https://github.com/ycm-core/YouCompleteMe/blob/master/CODE_OF_CONDUCT.md
[gitter]: https://gitter.im/Valloric/YouCompleteMe
[ninja-compdb]: https://ninja-build.org/manual.html
[++enc]: http://vimdoc.sourceforge.net/htmldoc/editing.html#++enc
[contributing-md]: https://github.com/ycm-core/YouCompleteMe/blob/master/CONTRIBUTING.md
[jdt.ls]: https://github.com/eclipse/eclipse.jdt.ls
[jdk-install]: https://adoptium.net/en-GB/temurin/releases
[mvn-project]: https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
[eclipse-project]: https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fproject_description_file.html
[gradle-project]: https://docs.gradle.org/current/userguide/tutorial_java_projects.html
[eclipse-dot-project]: https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fproject_description_file.html
[eclipse-dot-classpath]: https://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2FIClasspathEntry.html
[ycmd-eclipse-project]: https://github.com/ycm-core/ycmd/tree/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_eclipse_project
[ycmd-mvn-pom-xml]: https://github.com/ycm-core/ycmd/blob/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_maven_project/pom.xml
[ycmd-gradle-project]: https://github.com/ycm-core/ycmd/tree/3602f38ef7a762fc765afd75e562aec9a134711e/ycmd/tests/java/testdata/simple_gradle_project
[jdtls-preferences]: https://github.com/eclipse/eclipse.jdt.ls/blob/master/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/preferences/Preferences.java
[diacritic]: https://www.unicode.org/glossary/#diacritic
[clangd]: https://clang.llvm.org/extra/clangd.html
[vimspector]: https://github.com/puremourning/vimspector
[compiledb]: https://pypi.org/project/compiledb/
[signature-help-pr]: https://github.com/ycm-core/ycmd/pull/1255
[wiki-faq]: https://github.com/ycm-core/YouCompleteMe/wiki/FAQ
[wiki-full-install]: https://github.com/ycm-core/YouCompleteMe/wiki/Full-Installation-Guide
[wiki-troubleshooting]: https://github.com/ycm-core/YouCompleteMe/wiki/Troubleshooting-steps-for-ycmd-server-SHUT-DOWN
[lsp-examples]: https://github.com/ycm-core/lsp-examples
[diagnostic-echo-virtual-text1]: https://user-images.githubusercontent.com/10584846/185707973-39703699-0263-47d3-82ac-639d52259bea.png
[diagnostic-echo-virtual-text2]: https://user-images.githubusercontent.com/10584846/185707993-14ff5fd7-c082-4e5a-b825-f1364e619b6a.png
[jedi-refactor-doc]: https://jedi.readthedocs.io/en/latest/docs/api.html#jedi.Script.extract_variable
