MAC安装YCM

Mac OS X

请依照下面的引导进行安装,这是在mac上安装的最佳方式,但也有可能不适合您的情况.

1 首先安装最新版本的MacVim.

如果你不需要使用mvim的图形界面, 推荐将MacVim.app包中的Vim进行软链接出来使用. 为了保证正常工作, 请先拷贝MacVim中的mvim脚本到你的本地目录(例如:/usr/local/bin/mvim), 然后用下述命令创建符号链接.

ln -s /usr/local/bin/mvim vim

2 然后使用Vundle安装YouCompleteMe(其实是用Vundle下载YCM,因为下载下来还需要编译)

记住: YCM是一个编译型插件. 如果你使用Vundle升级YCM, 而此时ycm_core这个库的API有改动(虽然很少发生), 则YCM会提示你重新编译它自身. 那么你就要回到这个安装教程中, 按引导重新编译.

注意: 如果需要C语言或类C语言的补全功能, 则必须安装有最新版本的Xcode, 并且安装了Xcode最新的命令行工具.(命令行工具当你第一次使用clang命令时会自动安装, 也可以使用xcode-select --install手动安装)

3 安装CMake, 推荐使用Homebrew安装, 也可以使用独立的CMake安装包.

如果安装过Homebrew Python 或 Homebrew MacVim, 请参加FAQ.

4 编译YCM支持C语言族的补全:

cd ~/.vim/bundle/YouCompleteMe
./install.py --clang-completer

编译YCM, 不带C语言族补全:

cd ~/.vim/bundle/YouCompleteMe
./install.py

以下是支持的其他语言:

  • C# support: install Mono with Homebrew or by downloading the Mono Mac package and add --omnisharp-completerwhen calling ./install.py.
  • Go support: install Go and add --gocode-completer when calling ./install.py.
  • TypeScript support: install Node.js and npm then install the TypeScript SDK with npm install -g typescript.
  • JavaScript support: install Node.js and npm and add --tern-completer when calling ./install.py.
  • Rust support: install Rust and add --racer-completer when calling ./install.py.

为了简化编译过程, 可以使用--all 参数将所有支持打开. 需要保证xbuild,gotsservernodenpmrustc, 以及cargo 工具都已经安装到用户目录. 然后就可以使用下列命令:

cd ~/.vim/bundle/YouCompleteMe
./install.py --all

这就是全部的安装过程, 为保证C族补全正常工作, 你需要提供一些额外的编译标记给YCM, 这些都在用户向导中.

另外可以设置一些自定义参数,详见用户向导.

.ycm文件的例子:

# 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
import ycm_core

# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-DNDEBUG',
# You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM
# source code needs it.
'-DUSE_CLANG_COMPLETER',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++11',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x',
'c++',
'-isystem',
'../BoostParts',
'-isystem',
# This path will only work on OS X, but extra paths that don't exist are not
# harmful
'/System/Library/Frameworks/Python.framework/Headers',
'-isystem',
'../llvm/include',
'-isystem',
'../llvm/tools/clang/include',
'-I',
'.',
'-I',
'./ClangCompleter',
'-isystem',
'./tests/gmock/gtest',
'-isystem',
'./tests/gmock/gtest/include',
'-isystem',
'./tests/gmock',
'-isystem',
'./tests/gmock/include',
]


# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# You can get CMake to generate this file for you by adding:
# set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''

if os.path.exists( compilation_database_folder ):
  database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
  database = None

SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]

def DirectoryOfThisScript():
  return os.path.dirname( os.path.abspath( __file__ ) )


def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
  if not working_directory:
    return list( flags )
  new_flags = []
  make_next_absolute = False
  path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
  for flag in flags:
    new_flag = flag

    if make_next_absolute:
      make_next_absolute = False
      if not flag.startswith( '/' ):
        new_flag = os.path.join( working_directory, flag )

    for path_flag in path_flags:
      if flag == path_flag:
        make_next_absolute = True
        break

      if flag.startswith( path_flag ):
        path = flag[ len( path_flag ): ]
        new_flag = path_flag + os.path.join( working_directory, path )
        break

    if new_flag:
      new_flags.append( new_flag )
  return new_flags


def IsHeaderFile( filename ):
  extension = os.path.splitext( filename )[ 1 ]
  return extension in [ '.h', '.hxx', '.hpp', '.hh' ]


def GetCompilationInfoForFile( filename ):
  # The compilation_commands.json file generated by CMake does not have entries
  # for header files. So we do our best by asking the db for flags for a
  # corresponding source file, if any. If one exists, the flags for that file
  # should be good enough.
  if IsHeaderFile( filename ):
    basename = os.path.splitext( filename )[ 0 ]
    for extension in SOURCE_EXTENSIONS:
      replacement_file = basename + extension
      if os.path.exists( replacement_file ):
        compilation_info = database.GetCompilationInfoForFile(
          replacement_file )
        if compilation_info.compiler_flags_:
          return compilation_info
    return None
  return database.GetCompilationInfoForFile( filename )


def FlagsForFile( filename, **kwargs ):
  if database:
    # Bear in mind that compilation_info.compiler_flags_ does NOT return a
    # python list, but a "list-like" StringVec object
    compilation_info = GetCompilationInfoForFile( filename )
    if not compilation_info:
      return None

    final_flags = MakeRelativePathsInFlagsAbsolute(
      compilation_info.compiler_flags_,
      compilation_info.compiler_working_dir_ )

    # NOTE: This is just for YouCompleteMe; it's highly likely that your project
    # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
    # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
    try:
      final_flags.remove( '-stdlib=libc++' )
    except ValueError:
      pass
  else:
    relative_to = DirectoryOfThisScript()
    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )

  return {
    'flags': final_flags,
    'do_cache': True
  }

C-family Semantic Completion

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 FlagsForFile 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 .ycm_extra_conf.py file, 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 Options section for more details.

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.

See YCM’s own .ycm_extra_conf.py for details on how this works. You should be able to use it as a starting pointDon’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.

Yes, Clang’s CompilationDatabase system is also supported. Again, see the above linked example file. You can get CMake to generate this file for you by adding set( CMAKE_EXPORT_COMPILE_COMMANDS 1 ) to your project’sCMakeLists.txt file (if using CMake). If you’re not using CMake, you could use something like Bear to generate thecompile_commands.json file.

Consider using YCM-Generator to generate the ycm_extra_conf.py file.

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.

Commands

The :YcmRestartServer command

If the ycmd completion server 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 :YcmForceCompileAndDiagnostics 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 absense 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.

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 automatically opens in windows the stdout and stderr logfiles written by the ycmd server. If one or both logfiles are already opened, they are automatically closed. stderr or stdout can be specified as an argument of this command to only open the corresponding logfile instead of both. If this logfile is already opened, it will be closed. Only for debugging purpose.

The :YcmCompleter command

This command gives access to a number of additional IDE-like features in YCM, for things like semantic GoTo, type information, FixIt and refactoring.

Technically the command invokes completer-specific commands. If the first argument is of the form ft=... the completer for that file type will be used (for example ft=cpp), else the native completer of the current buffer will be used. CallYcmCompleter without further arguments for a list of the commands you can call for the current completer.

See the file type 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.

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/C++/Objective-C one.

You may also want to map the subcommands to something less verbose; for instance, nnoremap jd :YcmCompleter GoTo maps the 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 where before invoking the command (andCTRL-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 full width at the bottom of the screen. You can change this behavior by using 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

The GoToDeclaration subcommand

Looks up the symbol under the cursor and jumps to its declaration.

Supported in filetypes: c, cpp, objc, objcpp, cs, go, python, rust

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 #includedirectives (directly or indirectly) in that file.

Supported in filetypes: c, cpp, objc, objcpp, cs, go, 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/C++/Objective-C, 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, cs, go, javascript, python, rust

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 long 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

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: javascript, python, typescript

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

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

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:

    std::string s;

Invoking this command on s returns std::string => std::basic_string

NOTE: Due to limitations of libclang, invoking this command on the word auto typically returns auto. However, invoking it on a usage of the variable with inferred type returns the correct type, but typically it is repeated due to libclangreturning that the types differ.

For example:

const char *s = "String";
auto x = &s; // invoking on x or auto returns "auto";
             // invoking on s returns "const char *"
std::cout << *x; // invoking on x returns "const char ** => const char **"

NOTE: Causes re-parsing of the current translation unit.

Supported in filetypes: c, cpp, objc, objcpp, javascript, typescript

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:

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 firstC::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

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.

Supported in filetypes: c, cpp, objc, objcpp, cs, python, typescript, javascript

Refactoring and FixIt 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 the diagnostic closest to the cursor position.

Completers which 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.

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 set to 1, 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.

NOTE: After applying a fix-it, the diagnostics UI is not immediately updated. This is due to a technical restriction in Vim. Moving the cursor, or issuing the :YcmForceCompileAndDiagnostics command will refresh the diagnostics. Repeated invocations of the FixIt command on a given line, however, do apply all diagnostics as expected without requiring refreshing of the diagnostics UI. This is particularly useful where there are multiple diagnostics on one line, or where after fixing one diagnostic, another fix-it is available.

Supported in filetypes: c, cpp, objc, objcpp, cs

The RefactorRename 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.

Supported in filetypes: javascript (variables only), typescript

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 opened and populated with the locations of all modifications. This can be used to review all automatic changes made. Typically, use the CTRL-Wcombination to open the selected file in a new split. It is possible to customize how the quickfix window is opened by usingthe 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 which 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.

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 ClearCompilationFlagCache subcommand

YCM caches the flags it gets from the FlagsForFile function in your ycm_extra_conf.py file if you return them with thedo_cache parameter set to True. The cache is in memory and is never invalidated (unless you restart Vim of course).

This command clears that cache entirely. YCM will then re-query your FlagsForFile function as needed in the future.

Supported in filetypes: c, cpp, objc, objcpp

The StartServer subcommand

Starts the semantic-engine-as-localhost-server for those semantic engines that work as separate servers that YCM talks to.

Supported in filetypes: cs, go, javascript, rust

The StopServer subcommand

Stops the semantic-engine-as-localhost-server for those semantic engines that work as separate servers that YCM talks to.

Supported in filetypes: cs, go, javascript, rust

The RestartServer subcommand

Restarts the semantic-engine-as-localhost-server for those semantic engines that work as separate servers that YCM talks to.

An additional optional argument may be supplied for Python, specifying the python binary to use to restart the Python semantic engine.

:YcmCompleter RestartServer /usr/bin/python3.4

Supported in filetypes: cs, python, rust

The ReloadSolution subcommand

Instruct the Omnisharp server to clear its cache and reload all files from disk. This is useful when files are added, removed, or renamed in the solution, files are changed outside of Vim, or whenever Omnisharp 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:

  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:

  call youcompleteme#GetWarningCount()

Autocommands

The YcmQuickFixOpened autocommand

This User autocommand is fired when YCM opens the quickfix window in response to the GoTo* and RefactorRenamesubcommands. 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. For instance:

function s:CustomizeYcmQuickFixWindow()
  " Move the window at the top of the screen. execute "wincmd K" " Set the window height to 5.
  execute "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 by including a line like this:

let g:ycm_min_num_of_chars_for_completion = 1

Note that after changing an option in your vimrc script you have to restart Vim 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

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

let g:ycm_min_num_identifier_candidate_chars = 0

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 “ shortcut.

If you want to just turn off the identifier completer but keep the semantic triggers, you should setg:ycm_min_num_of_chars_for_completion to a high number like 99.

Default: 1

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 pythoncpp 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 the 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}

let g:ycm_filetype_whitelist = { '*': 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 pythoncpp 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]

let g:ycm_filetype_blacklist = {
      \ 'tagbar' : 1,
      \ 'qf' : 1,
      \ 'notes' : 1,
      \ 'markdown' : 1,
      \ 'unite' : 1,
      \ 'text' : 1,
      \ 'vimwiki' : 1,
      \ 'pandoc' : 1,
      \ 'infolog' : 1,
      \ 'mail' : 1
      \}

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 pythoncpp 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]

let g:ycm_filetype_specific_completion_to_disable = {
      \ 'gitcommit': 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 ccppobjc and objcpp 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

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 theg:syntastic_error_symbol option before using this option’s default.

Default: >>

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 theg:syntastic_warning_symbol option before using this option’s default.

Default: >>

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 theg:syntastic_enable_signs option before using this option’s default.

Default: 1

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 theg:syntastic_enable_highlighting option before using this option’s default.

Default: 1

let g:ycm_enable_diagnostic_highlighting = 1

The g:ycm_echo_current_diagnostic option

When this option is set, 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.

This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of theg:syntastic_echo_current_error option before using this option’s default.

Default: 1

let g:ycm_echo_current_diagnostic = 1

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 theg:syntastic_always_populate_loc_list option before using this option’s default.

Default: 0

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

let g:ycm_open_loclist_on_ycm_diags = 1

The g:ycm_allow_changing_updatetime option

When this option is set to 1, YCM will change the updatetime Vim option to 2000 (see :h updatetime). This may conflict with some other plugins you have (but it’s unlikely). The updatetime option is the number of milliseconds that have to pass before Vim’s CursorHold (see :h CursorHold) event fires. YCM runs the completion engines’ “file comprehension” systems in the background on every such event; the identifier-based engine collects the identifiers whereas the semantic engine compiles the file to build an AST.

The Vim default of 4000 for updatetime is a bit long, so YCM reduces this. Set this option to 0 to force YCM to leave your updatetime setting alone.

Default: 1

let g:ycm_allow_changing_updatetime = 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

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

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

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. 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: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

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

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 FlagsForFile 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 serverand then passed to your FlagsForFile function as a client_data keyword argument.

For instance, if you set this option to ['v:version'], your FlagsForFile function will be called like this:

# The '704' value is of course contingent on Vim 7.4; in 7.3 it would be '703'
FlagsForFile(filename, client_data = {'v:version': 704})

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 FlagsForFile function:

def FlagsForFile(filename, **kwargs):

You can then get to client_data with kwargs['client_data'].

Default: []

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. The YCM client running inside Vim always uses the Python interpreter that’s embedded inside Vim.

Default: ''

let g:ycm_server_python_interpreter = ''

The g:ycm_server_keep_logfiles option

When this option is set to 1, the ycmd completion server will keep the logfiles around after shutting down (they are deleted on shutdown by default).

To see where the logfiles are, call :YcmDebugInfo.

Default: 0

let g:ycm_server_keep_logfiles = 0

The g:ycm_server_log_level option

The logging level that the ycmd completion server uses. Valid values are the following, from most verbose to least verbose:

  • debug
  • info
  • warning
  • error
  • critical

Note that debug is very verbose.

Default: info

let g:ycm_server_log_level = 'info'

The g:ycm_auto_start_csharp_server option

When set to 1, the OmniSharp server will be automatically started (once per Vim session) when you open a C# file.

Default: 1

let g:ycm_auto_start_csharp_server = 1

The g:ycm_auto_stop_csharp_server option

When set to 1, the OmniSharp server will be automatically stopped upon closing Vim.

Default: 1

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 server to listen on. When set to 0uses an unused port provided by the OS.

Default: 0

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 variableg: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: ”

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. You can see the current state of yourcompleteopt 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.

Default: 0

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

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 theg:ycm_add_preview_to_completeopt option for more details.

Default: 0

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 if you are using the C-family semantic completion engine.

Default: 30

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 “ to this list.

Default: ['', '']

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 backwards through the completion list.

Note that one of the defaults is “ 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: ['', '']

let g:ycm_key_list_previous_completion = ['<S-TAB>', '<Up>']

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 trigged automatically after typing .-> and :: 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  to Vim when the user types  so YCM will make sure that is used in the map command when you're editing in console Vim, and  in GUI Vim. This means that you can just press “ in both 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: “

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.

Default: d

let g:ycm_key_detailed_diagnostics = '<leader>d'

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: ''

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 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 theg:ycm_extra_conf_globlist option.

Default: 1

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:

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 withos.path.abspath() before being matched against the filename.

Default: []

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

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++ (cppfiletype) 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.

Default: [see next line]

let g:ycm_semantic_triggers =  {
  \   'c' : ['->', '.'],
  \   'objc' : ['->', '.', 're!\[[_a-zA-Z]+\w*\s', 're!^\s*[^\W\d]\w*\s',
  \             're!\[.*\]\s'],
  \   'ocaml' : ['.', '#'],
  \   'cpp,objcpp' : ['->', '.', '::'],
  \   'perl' : ['->'],
  \   'php' : ['->', '::'],
  \   'cs,java,javascript,typescript,d,python,perl6,scala,vb,elixir,go' : ['.'],
  \   'ruby' : ['.', '::'],
  \   '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 lagginess if the omnifunc is slow.

Default: 1

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

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', 'horizontal-split', 'vertical-split', 'new-tab', 'new-or-existing-tab' ] 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 horizontal split.

Default: 'same-buffer'

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

let g:ycm_disable_for_files_larger_than_kb = 1000

The g:ycm_python_binary_path option

This option specifies the Python interpreter to use to run the jedi completion library. Specify the Python interpreter to use to get completions. By default the Python under which ycmd runs is used (ycmd runs on Python 2.6, 2.7 or 3.3+).

Default: ''

let g:ycm_python_binary_path = '/usr/bin/python3'

你可能感兴趣的:(mac,vim,YCM)