vim配置YCM

来源:互联网 发布:sopcast2016地址源码 编辑:程序博客网 时间:2024/06/14 18:42

安装配置时借鉴自 : http://www.tuicool.com/articles/f6feae

最近在接触新的内容.发现没有代码补全的vim真的有点力不从心.就像雄鹰要飞却没有强有力的翅膀.

在网上搜索了一番.得出结论是,omnicpp很屌,neocomplete也很屌,supertab也不错.纠结了好久.选择了YoucompleteMe,多么浪漫的名字.有网友将其定义成vim史上最强.一点不为过.

它集成了clangcomplete omnicppcomplete 等等.有点我就不多说了.网上随便一篇文章都比我能夸.

所以本文的重点不是如何安装.而是如何配置,如果让它工作的更好.

1. 配置YCM

首先是关于syntastic,很多教程现在还是说YCM 结合 syntastic一起工作.但是其实YCM现在完全不需要syntastic.它自己已经有了这样的功能.

下面是我的YCM配置.有很多是摘抄自上面那个链接.

let g:ycm_global_ycm_extra_conf = '/home/alai/.vim/bundle/YouCompleteMe/third_party/ycmd/.ycm_extra_conf.py'    "指定py文件的路径let g:ycm_show_diagnostics_ui = 1    " 开启实时错误或者warning的检测let g:ycm_add_preview_to_completeopt = 0    " 关闭补全预览" 允许 vim 加载 .ycm_extra_conf.py 文件,不再提示let g:ycm_confirm_extra_conf = 0" 补全内容不以分割子窗口形式出现,只显示补全列表set completeopt-=preview" 补全功能在注释中同样有效let g:ycm_complete_in_comments=1" 开启 YCM 标签补全引擎let g:ycm_collect_identifiers_from_tags_files=1" YCM 集成 OmniCppComplete 补全引擎,设置其快捷键inoremap <leader>; <C-x><C-o>" 从第一个键入字符就开始罗列匹配项let g:ycm_min_num_of_chars_for_completion=1" 禁止缓存匹配项,每次都重新生成匹配项let g:ycm_cache_omnifunc=0" 语法关键字补全let g:ycm_seed_identifiers_with_syntax=1" 错误标记let g:ycm_error_symbol = '✗'  "set error or warning signs" warning标记let g:ycm_warning_symbol = '⚠'"highlight YcmErrorSign       标记颜色"highlight YcmWarningSign ctermbg=none"highlight YcmErrorSection      代码中出错字段颜色highlight YcmWarningSection ctermbg=none"highlight YcmErrorLine        出错行颜色"highlight YcmWarningLine

有了这些配置,就可以正常使用补全和代码检测了.

不过有个地方需要主要,这里正常弹出的补全框里面只显示当前文件,系统路径,结构体成员的补全,如果要补全其它文件或者目录的变量,需要借助tags文件,也就是omni补全.上面有个设置其快捷键的选项,所以只需要ctrl + x + o,注意是在插入模式下,这样就可以补全其它路径的文件了.

但是其实这里还有个问题,就是你会发现代码只有错误,没有警告,这让人有点接受不了.好办,只要去上面指定的py文件中,将-werror注释掉就可以了.

当你接触一个稍微正规一点的工程,有代码树那种,你就会发现,ycm的补全几乎发挥不了任何作用.这是为什么呢.因为py文件指定的include路径中.没有你自己自定义的.

这个时候你只要拷贝一份py到你的工程路径,加上include路径就行了.不过这样是不是有点麻烦了.那么现在,还有一个办法, 就是通过脚本来处理.

以下是shell脚本:

#!/bin/bashTARGET="./.ycm_extra_conf.py"YCMPY1="/home/alai/bin/genpy/.ycm_extra_conf.beg"YCMPY2="/home/alai/bin/genpy/.ycm_extra_conf.end"TMP=.tmpPWD=$(pwd)PRJ=$(basename ${PWD})filelist=$(find . | grep -E "^.*\.h$")for file in ${filelist}do    echo $(dirname "${file}") >> ${TMP}donecat ${YCMPY1} > ${TARGET}DIR=$(cat ${TMP} | sort -u)for i in ${DIR}do    echo "'-I'," >> ${TARGET}    echo "'${i}'," >> ${TARGET}donecat ${YCMPY2} >> ${TARGET}rm -rf ${TMP}
最好将这个脚本放到~/bin目录下.这样就会有tab补全了.很方便.另外还有两个文件,其实就是将原来的py文件分成了两部分

/home/alai/bin/genpy/.ycm_extra_conf.beg :

# 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 osimport 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','./ClangCompleter','-isystem','./tests/gmock/gtest','-isystem','./tests/gmock/gtest/include','-isystem','./tests/gmock','-isystem','./tests/gmock/include','-isystem','/usr/include','-isystem','/usr/local/include','-isystem','/home/liyihai/es/qt4.8.3_arm/include/QtGui','-isystem','/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1','-isystem','/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include',

/home/alai/bin/genpy/.ycm_extra_conf.end :

]# 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 = NoneSOURCE_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_flagsdef 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  }
注意这个脚本要在工程的最上层目录执行.这样就可以自动添加include路径了.是不是很方便啊.不过有个缺点,就是如果某个文件存在空格,可能这个脚本会有意想不到的结果.我还没有试过,如果哪位同学遇到了.麻烦告知.谢谢

2. 结合indexer

有个插件叫做indexer.是用来自动生成tag文件的.当你埋头码了很久以后,突然发现,很多新函数找不到了.没关系,这就是indexer能够帮你做的.

他会实时的去根据代码改变生成新的tag文件.是不是很屌.配置也尤其简单.上面那个链接里面也有说明.这里不多说了.

在配置好以后,我们会发现只要新建工程,就得在.indexer_files文件中添加两行.很麻烦.可能我是有点强迫症了,本来也没有多少文件.但是如果有一种方式可以更轻松,何乐而不为呢.

#!/bin/bashINDEX=/home/alai/.indexer_filesecho "please make sure you are in your project dir"read -n 1 -p "only (Y/y) means sure:  " sureecho ""case ${sure} in    y|Y) ;;    *) exit ;;esacecho "building..."path=$(pwd)prj=$(basename ${path})$(grep ${prj} ${INDEX} -q)if [ $? -eq 0 ]then    echo "already added in ${INDEX}"else    echo "" >> ${INDEX}    echo "[${prj}]">> ${INDEX}    echo ${path} >> ${INDEX}fi
同样推荐各位把这段代码放到bin下,好处和上面一样.另外还有一点,这个脚本也要在工程的最高目录执行.


ok,有了这两个脚本,或者可以把它俩弄成一个,就完全不需要操心其它细节了.只要在适当的时候执行一下(也就是说新建工程或者有了新的include文件时),所有的操心迎刃而解.

我的代码树如下:


最后得瑟两张效果图:


希望能够帮助到有需要的同学们.



0 0
原创粉丝点击