vim:YCM

vim配置YCM

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

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

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

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

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

1. 配置YCM

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

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

 
  1. let g:ycm_global_ycm_extra_conf = '/home/alai/.vim/bundle/YouCompleteMe/third_party/ycmd/.ycm_extra_conf.py' "指定py文件的路径

  2. let g:ycm_show_diagnostics_ui = 1 " 开启实时错误或者warning的检测

  3. let g:ycm_add_preview_to_completeopt = 0 " 关闭补全预览

  4. " 允许 vim 加载 .ycm_extra_conf.py 文件,不再提示

  5. let g:ycm_confirm_extra_conf = 0

  6. " 补全内容不以分割子窗口形式出现,只显示补全列表

  7. set completeopt-=preview

  8. " 补全功能在注释中同样有效

  9. let g:ycm_complete_in_comments=1

  10. " 开启 YCM 标签补全引擎

  11. let g:ycm_collect_identifiers_from_tags_files=1

  12. " YCM 集成 OmniCppComplete 补全引擎,设置其快捷键

  13. inoremap <leader>; <C-x><C-o>

  14. " 从第一个键入字符就开始罗列匹配项

  15. let g:ycm_min_num_of_chars_for_completion=1

  16. " 禁止缓存匹配项,每次都重新生成匹配项

  17. let g:ycm_cache_omnifunc=0

  18. " 语法关键字补全

  19. let g:ycm_seed_identifiers_with_syntax=1

  20.  
  21. " 错误标记

  22. let g:ycm_error_symbol = '✗' "set error or warning signs

  23.  
  24. " warning标记

  25.  
  26. let g:ycm_warning_symbol = '⚠'

  27.  
  28. "highlight YcmErrorSign 标记颜色

  29. "highlight YcmWarningSign ctermbg=none

  30. "highlight YcmErrorSection 代码中出错字段颜色

  31. highlight YcmWarningSection ctermbg=none

  32. "highlight YcmErrorLine 出错行颜色

  33. "highlight YcmWarningLine

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

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

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

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

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

以下是shell脚本:

 

 
  1. #!/bin/bash

  2.  
  3. TARGET="./.ycm_extra_conf.py"

  4. YCMPY1="/home/alai/bin/genpy/.ycm_extra_conf.beg"

  5. YCMPY2="/home/alai/bin/genpy/.ycm_extra_conf.end"

  6. TMP=.tmp

  7.  
  8. PWD=$(pwd)

  9. PRJ=$(basename ${PWD})

  10.  
  11. filelist=$(find . | grep -E "^.*\.h$")

  12.  
  13. for file in ${filelist}

  14. do

  15. echo $(dirname "${file}") >> ${TMP}

  16. done

  17.  
  18. cat ${YCMPY1} > ${TARGET}

  19. DIR=$(cat ${TMP} | sort -u)

  20. for i in ${DIR}

  21. do

  22. echo "'-I'," >> ${TARGET}

  23. echo "'${i}'," >> ${TARGET}

  24. done

  25. cat ${YCMPY2} >> ${TARGET}

  26.  
  27. rm -rf ${TMP}

最好将这个脚本放到~/bin目录下.这样就会有tab补全了.很方便.另外还有两个文件,其实就是将原来的py文件分成了两部分

 

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

 

 
  1. # This file is NOT licensed under the GPLv3, which is the license for the rest

  2. # of YouCompleteMe.

  3. #

  4. # Here's the license text for this file:

  5. #

  6. # This is free and unencumbered software released into the public domain.

  7. #

  8. # Anyone is free to copy, modify, publish, use, compile, sell, or

  9. # distribute this software, either in source code form or as a compiled

  10. # binary, for any purpose, commercial or non-commercial, and by any

  11. # means.

  12. #

  13. # In jurisdictions that recognize copyright laws, the author or authors

  14. # of this software dedicate any and all copyright interest in the

  15. # software to the public domain. We make this dedication for the benefit

  16. # of the public at large and to the detriment of our heirs and

  17. # successors. We intend this dedication to be an overt act of

  18. # relinquishment in perpetuity of all present and future rights to this

  19. # software under copyright law.

  20. #

  21. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

  22. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

  23. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

  24. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR

  25. # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

  26. # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

  27. # OTHER DEALINGS IN THE SOFTWARE.

  28. #

  29. # For more information, please refer to <http://unlicense.org/>

  30.  
  31. import os

  32. import ycm_core

  33.  
  34. # These are the compilation flags that will be used in case there's no

  35. # compilation database set (by default, one is not set).

  36. # CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.

  37. flags = [

  38. '-Wall',

  39. '-Wextra',

  40. #'-Werror',

  41. '-Wc++98-compat',

  42. '-Wno-long-long',

  43. '-Wno-variadic-macros',

  44. '-fexceptions',

  45. '-DNDEBUG',

  46. # You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM

  47. # source code needs it.

  48. '-DUSE_CLANG_COMPLETER',

  49. # THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which

  50. # language to use when compiling headers. So it will guess. Badly. So C++

  51. # headers will be compiled as C headers. You don't want that so ALWAYS specify

  52. # a "-std=<something>".

  53. # For a C project, you would set this to something like 'c99' instead of

  54. # 'c++11'.

  55. '-std=c++11',

  56. # ...and the same thing goes for the magic -x option which specifies the

  57. # language that the files to be compiled are written in. This is mostly

  58. # relevant for c++ headers.

  59. # For a C project, you would set this to 'c' instead of 'c++'.

  60. '-x',

  61. 'c++',

  62. '-isystem',

  63. '../BoostParts',

  64. '-isystem',

  65. # This path will only work on OS X, but extra paths that don't exist are not

  66. # harmful

  67. '/System/Library/Frameworks/Python.framework/Headers',

  68. '-isystem',

  69. '../llvm/include',

  70. '-isystem',

  71. '../llvm/tools/clang/include',

  72. '-I',

  73. './ClangCompleter',

  74. '-isystem',

  75. './tests/gmock/gtest',

  76. '-isystem',

  77. './tests/gmock/gtest/include',

  78. '-isystem',

  79. './tests/gmock',

  80. '-isystem',

  81. './tests/gmock/include',

  82. '-isystem',

  83. '/usr/include',

  84. '-isystem',

  85. '/usr/local/include',

  86. '-isystem',

  87. '/home/liyihai/es/qt4.8.3_arm/include/QtGui',

  88. '-isystem',

  89. '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1',

  90. '-isystem',

  91. '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include',

 

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

 
  1. ]

  2.  
  3.  
  4. # Set this to the absolute path to the folder (NOT the file!) containing the

  5. # compile_commands.json file to use that instead of 'flags'. See here for

  6. # more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html

  7. #

  8. # You can get CMake to generate this file for you by adding:

  9. # set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )

  10. # to your CMakeLists.txt file.

  11. #

  12. # Most projects will NOT need to set this to anything; you can just change the

  13. # 'flags' list of compilation flags. Notice that YCM itself uses that approach.

  14. compilation_database_folder = ''

  15.  
  16. if os.path.exists( compilation_database_folder ):

  17. database = ycm_core.CompilationDatabase( compilation_database_folder )

  18. else:

  19. database = None

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

  22.  
  23. def DirectoryOfThisScript():

  24. return os.path.dirname( os.path.abspath( __file__ ) )

  25.  
  26.  
  27. def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):

  28. if not working_directory:

  29. return list( flags )

  30. new_flags = []

  31. make_next_absolute = False

  32. path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]

  33. for flag in flags:

  34. new_flag = flag

  35.  
  36. if make_next_absolute:

  37. make_next_absolute = False

  38. if not flag.startswith( '/' ):

  39. new_flag = os.path.join( working_directory, flag )

  40.  
  41. for path_flag in path_flags:

  42. if flag == path_flag:

  43. make_next_absolute = True

  44. break

  45.  
  46. if flag.startswith( path_flag ):

  47. path = flag[ len( path_flag ): ]

  48. new_flag = path_flag + os.path.join( working_directory, path )

  49. break

  50.  
  51. if new_flag:

  52. new_flags.append( new_flag )

  53. return new_flags

  54.  
  55.  
  56. def IsHeaderFile( filename ):

  57. extension = os.path.splitext( filename )[ 1 ]

  58. return extension in [ '.h', '.hxx', '.hpp', '.hh' ]

  59.  
  60.  
  61. def GetCompilationInfoForFile( filename ):

  62. # The compilation_commands.json file generated by CMake does not have entries

  63. # for header files. So we do our best by asking the db for flags for a

  64. # corresponding source file, if any. If one exists, the flags for that file

  65. # should be good enough.

  66. if IsHeaderFile( filename ):

  67. basename = os.path.splitext( filename )[ 0 ]

  68. for extension in SOURCE_EXTENSIONS:

  69. replacement_file = basename + extension

  70. if os.path.exists( replacement_file ):

  71. compilation_info = database.GetCompilationInfoForFile(

  72. replacement_file )

  73. if compilation_info.compiler_flags_:

  74. return compilation_info

  75. return None

  76. return database.GetCompilationInfoForFile( filename )

  77.  
  78.  
  79. def FlagsForFile( filename, **kwargs ):

  80. if database:

  81. # Bear in mind that compilation_info.compiler_flags_ does NOT return a

  82. # python list, but a "list-like" StringVec object

  83. compilation_info = GetCompilationInfoForFile( filename )

  84. if not compilation_info:

  85. return None

  86.  
  87. final_flags = MakeRelativePathsInFlagsAbsolute(

  88. compilation_info.compiler_flags_,

  89. compilation_info.compiler_working_dir_ )

  90.  
  91. # NOTE: This is just for YouCompleteMe; it's highly likely that your project

  92. # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR

  93. # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.

  94. try:

  95. final_flags.remove( '-stdlib=libc++' )

  96. except ValueError:

  97. pass

  98. else:

  99. relative_to = DirectoryOfThisScript()

  100. final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )

  101.  
  102. return {

  103. 'flags': final_flags,

  104. 'do_cache': True

  105. }

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

 

2. 结合indexer

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

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

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

 

 
  1. #!/bin/bash

  2.  
  3. INDEX=/home/alai/.indexer_files

  4.  
  5. echo "please make sure you are in your project dir"

  6. read -n 1 -p "only (Y/y) means sure: " sure

  7. echo ""

  8. case ${sure} in

  9. y|Y) ;;

  10.  
  11. *) exit ;;

  12. esac

  13.  
  14. echo "building..."

  15.  
  16. path=$(pwd)

  17. prj=$(basename ${path})

  18.  
  19. $(grep ${prj} ${INDEX} -q)

  20. if [ $? -eq 0 ]

  21. then

  22. echo "already added in ${INDEX}"

  23. else

  24. echo "" >> ${INDEX}

  25. echo "[${prj}]">> ${INDEX}

  26. echo ${path} >> ${INDEX}

  27. fi

同样推荐各位把这段代码放到bin下,好处和上面一样.另外还有一点,这个脚本也要在工程的最高目录执行.

 

 

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

我的代码树如下:

最后得瑟两张效果图:

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


 

https://blog.csdn.net/cp3alai/article/details/48310833

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值