vi代碼智能提示功能及相關配置


vim是一款支持插件、功能無比強大的編輯器,無論你的系統是linux、unix、mac還是windows,都能夠選擇他來編輯文件或是進行工程級別 的coding。如果能把vim用好了,不僅編程效率能得到大幅度提高,周圍人也會因此而看得頭暈眼花佩服不已,自己心里當然也會心花怒放啦。下面就讓我 來介紹一下如何來進行配置。這些配置所涉及到的內容有:autocomplpop, ctags, TagList,omnicppcomplete

首 先Vim是內建代碼補全功能的,在不需要通過任何設置的情況下就能使用。在您編輯代碼的時候,鍵入 ctrl+x, ctrl+o, ctrl+n, ctrl+p 等快捷鍵,就會彈出智能提示的菜單。但是這仍然不滿足大家的要求。大多數IDE中,只要代碼輸入到相應的位置,補全提示就會自動的彈出來,而vim的這種 補全還需要自己手動的來觸發。那么下面就介紹一種可以自動彈出補全提示的插件 — autocomplpop

== Autocomplpop ==

首先,從http://www.vim.org/scripts/script.php?script_id=1879處 下載autocomplpop.vim文件(我們所說的vim插件就是這樣的*.vim格式的文件),然后將其放入vim文件目錄下的plugin目錄中 (unix/linux平台在/usr/share/vim/vim71中, windows平台在安裝目錄的vim71目錄中),然后重啟一下vim就會發現在編碼時會自動彈出提示了。

細心的朋友會發現,光是利用 autocomplpop這個插件還遠遠達不到要求。比如說:在c++中使用.或是->訪問對象或指針中的成員和函數時還無法自動彈出提示,另外, 即便是自動提示也只能提示我們在當前文檔中已輸入的字符串。針對這種情況,我們就需要安裝ctags工具和OmniCppComplete插件。 ctags是用來對文件做標記的工具,OmniCppComplete是在c和c++語言范疇內,對上述智能補全的增強版。

== ctags ==

ctags在http://ctags.sourceforge.net/下載源碼,編譯后安裝。常規的標記命令為 ctags -R 。"-R"表示遞歸創建,也就包括源代碼根目錄下的所有子目錄下的源程序。

 

== CppCompleete ==

OmniCppComplete在http://www.vim.org/scripts/script.php?script_id=1520下載。下載 好之后根據里面的doc文檔進行安裝和使用。

這樣一來,代碼補全就比較完善了。但是根據以往的經驗,IDE中還有一個功能,那就是函數和變量的跳轉查看。比如代碼中出現
代碼:
if(true){
doThis();
}

我們想知道doThis()函數是如何定義和實現的,那么如何快速的來查看呢?我們就需要安裝Taglist插件

== Taglist ==

插件在http://vim.sourceforge.net/scripts/script.php?script_id=273下載。下載好之后,我們可以根據其中的doc文檔進行安裝和配置。

我們發現其實Taglist的使用也必須要依靠ctags所創建出來的tag文件。當tag文件形成、一切配置都配置完成之后。我們可以ctrl+]來進行函數或者是變量跳轉。好了,從此你就可以開始像IDE一樣來使用vim進行編碼了。

 

正文

1. 引言

可以使用腳本/插件來給vim添加各種神奇的功能,從更換顏色主題、到代碼智能提示,甚至項目管理。無數開發者通過開源社區貢獻自己開發的插件,使得vim有可能變得無比強大。這兒http://vim-scripts.org/vim/scripts.html 是一份vim擴展腳本的列表。

然而,我的思想是盡量不要使用vim插件,除了那些非常優秀且對自己的工作而言所必需的。這樣,當需要配置一台新電腦或者臨時要在別人的電腦上工作時,最起碼能比較方便地配置好環境,或者直接使用默認環境熟練地完成任務,而不是離開了插件什么也不會。

對我自己而言,我基本上只需要4個(種)插件:

  1. 管理插件的插件(插件管理器)
  2. 最喜歡的配色方案
  3. Doxygen注釋自動生成
  4. 代碼智能提示與補全

除了顏色主題因個人喜好和環境不同各不相同外,其余插件我都只會選擇最流行,且公認最優、最好用的那個。下文將分別介紹這幾種插件,並給出在Linux(Ubuntu, CentOS)和Mac OSX上配置的方法。但是在這之前,最好確認以下幾個條件:

  1. 連上寬帶互聯網
  2. 安裝好git
  3. 安裝好vim並確認其版本號至少是7.3.584,且支持python2(這是代碼提示與補全插件要求的)

2. 插件管理器

Vundle是一個流行的vim插件管理器,它的網址是https://github.com/VundleVim/Vundle.vim

以下是安裝步驟:

  1. git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    如果目錄.vim/bundle不存在請先創建
  2. 打開~/.vimrc,在文件頭加入以下內容
    復制代碼
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    " Vundle
    set nocompatible              " be iMproved, required
    filetype off                  " required
    
    " set the runtime path to include Vundle and initialize
    set rtp+=~/.vim/bundle/Vundle.vim
    call vundle#begin()
    " alternatively, pass a path where Vundle should install plugins
    "call vundle#begin('~/some/path/here')
    
    " let Vundle manage Vundle, required
    Plugin 'VundleVim/Vundle.vim'
    
    " The following are examples of different formats supported.
    " Keep Plugin commands between vundle#begin/end.
    " plugin on GitHub repo
    "Plugin 'tpope/vim-fugitive'
    " plugin from http://vim-scripts.org/vim/scripts.html
    "Plugin 'L9'
    " Git plugin not hosted on GitHub
    "Plugin 'git://git.wincent.com/command-t.git'
    " git repos on your local machine (i.e. when working on your own plugin)
    "Plugin 'file:///home/gmarik/path/to/plugin'
    " The sparkup vim script is in a subdirectory of this repo called vim.
    " Pass the path to set the runtimepath properly.
    "Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
    " Avoid a name conflict with L9
    "Plugin 'user/L9', {'name': 'newL9'}
    
    " All of your Plugins must be added before the following line
    call vundle#end()            " required
    filetype plugin indent on    " required
    " To ignore plugin indent changes, instead use:
    "filetype plugin on
    "
    " Brief help
    " :PluginList       - lists configured plugins
    " :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
    " :PluginSearch foo - searches for foo; append `!` to refresh local cache
    " :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
    "
    " see :h vundle for more details or wiki for FAQ
    " Put your non-Plugin stuff after this line
    
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    復制代碼

    從其中的注釋可以知道,Vundle支持多種形式的插件源,並給出了示例。這些插件源包括:github上的插件、http://vim-scripts.org/vim/scripts.html上的插件、非github上的git插件、本地硬盤上的插件等。

  3. 打開vim,運行 :PluginInstall 命令來自動安裝插件,過程中有可能需要輸入github用戶名和密碼。等待Vundle安裝完成即可。

Vundle正在自動安裝在.vimrc中指定的插件:

 

 

3. 配色方案

vim默認有一些配色方案,如果這些都不喜歡,可以從網上下載安裝別的配色方案。solarized和molokai都是流行的配色方案,然而這兩個主題在終端(terminal)模式下或者SecureCRT上使用都會有一些問題,而我目前最喜歡的khaki沒有這個問題,它的樣子如下圖所示(其中設置了行號、當前號高亮、語法高亮等)

安裝步驟:

  1. 在~/.vimrc中的Vundle插件列表區域中添加khaki的源位置
    Plugin 'vim-scripts/khaki.vim' 
    保存后退出,再打開vim,運行:PluginInstall命令安裝。
  2. 在~/.vimrc中,Vundle區域后面的某處,添加
    if !has("gui_running")                                          
        set t_Co=256                                                
    endif                                                                                         
    colorscheme khaki 

    保存后重啟vim即可。

4. Doxygen注釋自動生成

為自己的代碼寫好注釋是一個良好的習慣,而編寫Doxygen風格的注釋更是可以通過doxygen工具為代碼自己生成文檔,非常好用。DoxygenToolkit(https://github.com/vim-scripts/DoxygenToolkit.vim)就是這樣的一個插件。安裝和使用:

  1. 在~/.vimrc中的Vundle插件列表區域中添加DoxygenToolkit的源位置
    Plugin 'vim-scripts/DoxygenToolkit.vim'
    保存后退出,再打開vim,運行:PluginInstall命令安裝
  2. 在~.vimrc中,Vundle區域后的某處,設置DoxygenToolkit插件在@author區域自動填充的作者名稱,比如
    let g:DoxygenToolkit_authorName="zzq@moon.net" 
  3. 使用時,將光標定位到文件首行,輸入:DoxAuthor將插入文件頭注釋骨架(第一次會讓你輸入文件版本號),如下:
    復制代碼
      /**                                                                
       * @file test.cpp                                                  
       * @brief                                                                                       
       * @author zzp@moon.net                                            
       * @version 1.0                                                    
       * @date 2015-08-21                                                
       */  
    復制代碼

    並把光標停留在@brief 后面,等待輸入文件描述。
    在光標定位到數據結構聲明或函數聲明的第一行,運行:Dox,將生成數據結構或函數的注釋骨架,如下:

    復制代碼
    /**                                                             
       * @brief                                                       
       */                                                             
      struct foo                                                      
      {                                                               
          char str;                                                   
          void* ptr;                                                  
      };                                                              
                                                                      
      /**                                                             
       * @brief                                                       
       *                                                                                              
       * @param a                                                     
       * @param b                                                     
       *                                                              
       * @return                                                      
       */                                                             
      int bar(int a, int b)                                           
      {                                                               
          return a+b;                                                 
      }         
    復制代碼

    並把光標定位在@brief 后,期待你輸入具體的注釋內容。

5. 代碼智能提示與補全

寫代碼的時候,變量名、函數名、類名等代碼符號的智能提示和補全功能是非常有用的,可以大大提高編碼效率。然而,在YouCompleteMe(簡稱YCM)這個神奇的插件出現之前,vim一直使用tag機制來完成這個功能。由於tag只會笨拙地分析代碼中的字符串,並不能識別其語法說語義,導致代碼的提示並不好用。隨着clang的出現,使開發人員可以對程序代碼進行事實上的語義分析(調用clang分析器之類的),於是真正的智能提示和補全插件出現了,它就是由 google 的工程師 Strahinja Val Markovic 所開發的YCM(https://github.com/Valloric/YouCompleteMe)。

5.1 YouCompleteMe的安裝與配置

YCM使用C++和python開發,是一個復雜的插件,光是通過Vundle下載的文件就達到120多MB。另外YCM不只是有新的開發的功能,它還包含了其他一些有用的插件。下圖是作者本人提示的演示動圖:

除了代碼提示與補全外,借助libclang強大的語法與語義分析能力,YCM還可以在編輯的時候提示出錯的行與出錯原因,如下圖所示:

另外,YCM還可以補全路徑,文件名等。

 

安裝與配置步驟:

  1. 如果是在Ubuntu 14.04上,運行以下命令安裝
      
    sudo apt-get install vim-addon-manager 
    sudo apt-get install vim-youcompleteme
    vim-addons install youcompleteme
    來安裝YCM插件,非常簡單。否則到2.

    ==2016.12.30補充 在CentOS7上安裝YouCompleteMe==

    1.1.下載Vundle和YouCompleteMe插件

    輸入以下指令,下載Vundle

    git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    下載成功后,在用戶根目錄下面,修改.vimrc文件,追加下面語句以便后續安裝YouCompleteMe插件

    set  nocompatible
    filetype off
    set  rtp+=~/.vim /bundle/Vundle .vim
    call vundle #begin()
    Plugin 'gmarik/Vundle.vim'
    Plugin 'Valloric/YouCompleteMe'
    call vundle #end()
    filetype plugin indent on   

    然后在vim中先按Esc建,並且輸入以下指令安裝插件:

    :PluginInstall 
    1.2.編譯YouCompleteMe

    在編譯之前下載編譯工具,准備編譯YouCompleteMe

    yum install gcc gcc-c++ cmake python-devel
    編譯YouCompleteMe使其支持C/C++ 自動補全

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

     

  2. 如果是Ubuntu 12.04,有好多問題要解決,如果條件允許最好直接用14.04. 否則到3.
    a. 系統自帶的vim版本過低,需要先把版本升級到7.4,目前除了下源碼編譯我不知道有什么別的方法。
    參考:https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source
    b. CMake版本過低,需要升級到2.8.11以上。到http://www.cmake.org/download/ 下一高版本即可。
    c. 有可能沒有安裝ctags,apt-get安裝一個即可,后文要用到。
  3. 與以上插件一樣,在.vimrc中添加 Plugin 'Valloric/YouCompleteMe',並運行:PluginInstall命令安裝。
  4. 下載最新的clang。
    YCM是為clang 3.6設計的,理論上的最低版本不應低於3.2+。YCM使用clang提供的libclang來解析代碼主義等.
    從 http://llvm.org/releases/download.html 下載為你的系統預編譯好的clang。
    但上面的列表並沒有為所有系統提供精確的版本,比如我要在CentOS 7.0 64bit上編譯YCM,但上面沒有,所以只好自己編譯,方法是:
    a. 下載LLVM source code: llvm-3.6.2.src.tar.xz, 解壓到llvm-3.6.2.src
    b. 下載Clang source code: cfe-3.6.2.src.tar.xz, 解壓到llvm-3.6.2.src/tools/clang
    c. 下載Compiler RT source code: compiler-rt-3.6.2.src.tar.xz, 解壓到llvm-3.6.2.src/projects/compiler-rt
    d. 下載Clang tools Extra:clang-tools-extra-3.6.2.src.tar.xz,解壓到llvm-3.6.2.src/tools/clang/tools/extra
    e. 不妨在llvm-3.6.2.src父目錄中建立build目錄並編譯
    mkdir llvm_build; cd llvm_build
    ../llvm-3.6.2.src/configure --enable-optimized --enable-targets=host-only
    make && make install
    這里一定要記得make install,否則clang源碼中的頭文件沒有放到/usr/include相關目錄下,一會編譯YCM庫時會報找不到頭文件的錯誤。(這個編譯的非常慢,生成1.6GB+文件)

  5. 編譯ycm_support_libs。
    a. 這要求系統安裝了cmake, python(2.6+), python-devel(2.6+)等,如果不滿足條件cmake的時候會提示錯誤。
    b. cd~; mkdir ycm_build; cd ycm_build
    c. 如果是安裝了預編譯好的clang,請運行cmake -G "Unix Makefiles" -DPATH_TO_LLVM_ROOT=~/clang+llvm-3.4.2-x86_64-unknown-ubuntu12.04 . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp,生成Makefile。其中clang+llvm-3.4.2-x86_64-unknown-ubuntu12.04是clang預編譯包解壓后的路徑,里面有bin,lib,include等目錄;
    否則,如果是自己在第4步從源碼編譯的clang,則運行 cmake -G "Unix Makefiles" -DEXTERNAL_LIBCLANG_PATH=~/llvm_build/Release+Asserts/lib/libclang.so . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp,生成Makefile。其中~/llvm_build是用於從源碼編譯的build目錄。
    d. 運行 make ycm_support_libs生成YCM支持庫
    這一過程會在~/.vim/bundle/YouCompleteMe/third_party/ycmd/下生成幾個.so。至此,YCM編譯已結束。
  6. 配置YCM
    a. YCM在語義分析時使用libclang,而libclang需要參數選項,這從哪里來呢?YCM通過提供給一個代碼工程一個python文件的方式來通知libclang所需的參數選項,這個文件就是.ycm_extra_conf.py。YCM安裝好后在,在路徑~/.vim/bundle/YouCompleteMe/third_party/ycmd/examples/.ycm_extra_conf.py有一個默認的配置文件,可以把它拷貝到你的代碼所在主目錄下,並進行修改。主要是修改此文件中的flags表,加入自己代碼所在路徑、語言類型(C/C++)等。
    復制代碼
    # 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',
    ]
    復制代碼

    b. 在.vimrc中添加以下配置項(更多項見https://github.com/Valloric/YouCompleteMe#general-usage)。

    復制代碼
    " YCM                                                              
    " 允許自動加載.ycm_extra_conf.py,不再提示                         
    let g:ycm_confirm_extra_conf=0                                     
    " 補全功能在注釋中同樣有效                                         
    let g:ycm_complete_in_comments=1                                   
    " 開啟tags補全引擎                                                 
    let g:ycm_collect_identifiers_from_tags_files=1                    
    " 鍵入第一個字符時就開始列出匹配項                                 
    let g:ycm_min_num_of_chars_for_completion=1                        
    " YCM相關快捷鍵,分別是\gl, \gf, \gg                                                    
    nnoremap <leader>gl :YcmCompleter GoToDeclaration<CR>              
    nnoremap <leader>gf :YcmCompleter GoToDefinition<CR>               
    nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR>
    復制代碼

其中,

  • g:ycm_confirm_extra_conf如果不設為0的話,用vim每次打開代碼文件,YCM都會提示是否確認加載某某.ycm_extra_conf.py文件;
  • ycm_collect_identifiers_from_tags_files設為1,指定YCM收集傳統tags文件的信息,另外當tags改變時,YCM會重新索引它們。YCM對tags文件的格式有特殊的要求: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:<lang> field in the tags output。如有問題請參閱YCM官網相關FAQ;
    比如引入C++tags:
    " 引入 C++ 標准庫tags
    set tags+=/data/misc/vim/stdcpp.tags
  • 3個快捷鍵設置是用來快速跳轉到符號聲明或定義的。我往往只用gg,即將光標定位到某個符號上,按\鍵后(默認的leader鍵是\),快速按兩次g鍵,將跳轉到該符號的聲明或定義位置(Tips: 按<ctrl>+o返回)

其他技巧:

  • 執行:YcmDiags顯示所有錯誤, 它其實是打開了一個location list窗口,也可能通過:lopen打開. 使用:lclose可以關閉
  • 有些系統函數如fopen, strcpy如果不智能提示,可以按<Ctrl>+<Space>鍵。
  • 如果有的文件死活無法正確提示(如果結構體之類),請檢查一下文件編碼,改成utf-8。(vim中 :set fileencoding=utf8)

 

5.2 完善代碼提示與補全

 如5.1所述,YouCompleteMe插件是如此地強大。然而,某些時候它可能還是會有些小問題,比如無法提示宏定義等等,導致無法補全,這時候還是需要借助傳統的tags文件。indexer插件可以針對不同的工程目錄自動地生成、更新和引入不同的tags文件,詳見http://www.vim.org/scripts/script.php?script_id=3221。它需要依賴DfrankUtil和Vimprj 兩個插件,需要一並安裝。

安裝與配置步驟:

1. 在.vimrc的Vundle區域內加入以下內容

Plugin 'DfrankUtil'                                             
Plugin 'vimprj'                                                 
Plugin 'indexer.tar.gz'

之后運行:PluginInstall安裝;

2. 打開.vimrc,加入以下內容:

" indexer                                                       
" 設置indexer 調用 ctags 的參數                                 
" 默認 --c++-kinds=+p+l,重新設置為 --c++-kinds=+p+l+x+c+d+e+f+g+m+n+s+t+u+v
" 默認 --fields=+iaS 不滿足 YCM 要求,需改為 --fields=+iaSl                                       
let g:indexer_ctagsCommandLineOptions="--c++-kinds=+p+l+x+c+d+e+f+g+m+n+s+t+u+v --fields=+iaSl --e
xtra=+q"

3. indexer會根據你的代碼工程的不同,自動生成並在其中的代碼文件被打開時自動加載tags文件。它是通過配置文件來指定工程設置的,此文件為~/.indexer_files。以下是一個配置示例,演示了2個不同的工程的Indexer配置。

復制代碼
[CoolProject] 
/home/user/cool_project 

[AnotherProject] 
option:ctags_params = "--languages=c++" 
/home/user/another_project/src 
/home/user/another_project/lib 
復制代碼

 

6 參考

 

正文

1. 引言

可以使用腳本/插件來給vim添加各種神奇的功能,從更換顏色主題、到代碼智能提示,甚至項目管理。無數開發者通過開源社區貢獻自己開發的插件,使得vim有可能變得無比強大。這兒http://vim-scripts.org/vim/scripts.html 是一份vim擴展腳本的列表。

然而,我的思想是盡量不要使用vim插件,除了那些非常優秀且對自己的工作而言所必需的。這樣,當需要配置一台新電腦或者臨時要在別人的電腦上工作時,最起碼能比較方便地配置好環境,或者直接使用默認環境熟練地完成任務,而不是離開了插件什么也不會。

對我自己而言,我基本上只需要4個(種)插件:

  1. 管理插件的插件(插件管理器)
  2. 最喜歡的配色方案
  3. Doxygen注釋自動生成
  4. 代碼智能提示與補全

除了顏色主題因個人喜好和環境不同各不相同外,其余插件我都只會選擇最流行,且公認最優、最好用的那個。下文將分別介紹這幾種插件,並給出在Linux(Ubuntu, CentOS)和Mac OSX上配置的方法。但是在這之前,最好確認以下幾個條件:

  1. 連上寬帶互聯網
  2. 安裝好git
  3. 安裝好vim並確認其版本號至少是7.3.584,且支持python2(這是代碼提示與補全插件要求的)

2. 插件管理器

Vundle是一個流行的vim插件管理器,它的網址是https://github.com/VundleVim/Vundle.vim

以下是安裝步驟:

  1. git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    如果目錄.vim/bundle不存在請先創建
  2. 打開~/.vimrc,在文件頭加入以下內容
    復制代碼
    """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    " Vundle
    set nocompatible              " be iMproved, required
    filetype off                  " required
    
    " set the runtime path to include Vundle and initialize
    set rtp+=~/.vim/bundle/Vundle.vim
    call vundle#begin()
    " alternatively, pass a path where Vundle should install plugins
    "call vundle#begin('~/some/path/here')
    
    " let Vundle manage Vundle, required
    Plugin 'VundleVim/Vundle.vim'
    
    " The following are examples of different formats supported.
    " Keep Plugin commands between vundle#begin/end.
    " plugin on GitHub repo
    "Plugin 'tpope/vim-fugitive'
    " plugin from http://vim-scripts.org/vim/scripts.html
    "Plugin 'L9'
    " Git plugin not hosted on GitHub
    "Plugin 'git://git.wincent.com/command-t.git'
    " git repos on your local machine (i.e. when working on your own plugin)
    "Plugin 'file:///home/gmarik/path/to/plugin'
    " The sparkup vim script is in a subdirectory of this repo called vim.
    " Pass the path to set the runtimepath properly.
    "Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
    " Avoid a name conflict with L9
    "Plugin 'user/L9', {'name': 'newL9'}
    
    " All of your Plugins must be added before the following line
    call vundle#end()            " required
    filetype plugin indent on    " required
    " To ignore plugin indent changes, instead use:
    "filetype plugin on
    "
    " Brief help
    " :PluginList       - lists configured plugins
    " :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
    " :PluginSearch foo - searches for foo; append `!` to refresh local cache
    " :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
    "
    " see :h vundle for more details or wiki for FAQ
    " Put your non-Plugin stuff after this line
    
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    復制代碼

    從其中的注釋可以知道,Vundle支持多種形式的插件源,並給出了示例。這些插件源包括:github上的插件、http://vim-scripts.org/vim/scripts.html上的插件、非github上的git插件、本地硬盤上的插件等。

  3. 打開vim,運行 :PluginInstall 命令來自動安裝插件,過程中有可能需要輸入github用戶名和密碼。等待Vundle安裝完成即可。

Vundle正在自動安裝在.vimrc中指定的插件:

 

 

3. 配色方案

vim默認有一些配色方案,如果這些都不喜歡,可以從網上下載安裝別的配色方案。solarized和molokai都是流行的配色方案,然而這兩個主題在終端(terminal)模式下或者SecureCRT上使用都會有一些問題,而我目前最喜歡的khaki沒有這個問題,它的樣子如下圖所示(其中設置了行號、當前號高亮、語法高亮等)

安裝步驟:

  1. 在~/.vimrc中的Vundle插件列表區域中添加khaki的源位置
    Plugin 'vim-scripts/khaki.vim' 
    保存后退出,再打開vim,運行:PluginInstall命令安裝。
  2. 在~/.vimrc中,Vundle區域后面的某處,添加
    if !has("gui_running")                                          
        set t_Co=256                                                
    endif                                                                                         
    colorscheme khaki 

    保存后重啟vim即可。

4. Doxygen注釋自動生成

為自己的代碼寫好注釋是一個良好的習慣,而編寫Doxygen風格的注釋更是可以通過doxygen工具為代碼自己生成文檔,非常好用。DoxygenToolkit(https://github.com/vim-scripts/DoxygenToolkit.vim)就是這樣的一個插件。安裝和使用:

  1. 在~/.vimrc中的Vundle插件列表區域中添加DoxygenToolkit的源位置
    Plugin 'vim-scripts/DoxygenToolkit.vim'
    保存后退出,再打開vim,運行:PluginInstall命令安裝
  2. 在~.vimrc中,Vundle區域后的某處,設置DoxygenToolkit插件在@author區域自動填充的作者名稱,比如
    let g:DoxygenToolkit_authorName="zzq@moon.net" 
  3. 使用時,將光標定位到文件首行,輸入:DoxAuthor將插入文件頭注釋骨架(第一次會讓你輸入文件版本號),如下:
    復制代碼
      /**                                                                
       * @file test.cpp                                                  
       * @brief                                                                                       
       * @author zzp@moon.net                                            
       * @version 1.0                                                    
       * @date 2015-08-21                                                
       */  
    復制代碼

    並把光標停留在@brief 后面,等待輸入文件描述。
    在光標定位到數據結構聲明或函數聲明的第一行,運行:Dox,將生成數據結構或函數的注釋骨架,如下:

    復制代碼
    /**                                                             
       * @brief                                                       
       */                                                             
      struct foo                                                      
      {                                                               
          char str;                                                   
          void* ptr;                                                  
      };                                                              
                                                                      
      /**                                                             
       * @brief                                                       
       *                                                                                              
       * @param a                                                     
       * @param b                                                     
       *                                                              
       * @return                                                      
       */                                                             
      int bar(int a, int b)                                           
      {                                                               
          return a+b;                                                 
      }         
    復制代碼

    並把光標定位在@brief 后,期待你輸入具體的注釋內容。

5. 代碼智能提示與補全

寫代碼的時候,變量名、函數名、類名等代碼符號的智能提示和補全功能是非常有用的,可以大大提高編碼效率。然而,在YouCompleteMe(簡稱YCM)這個神奇的插件出現之前,vim一直使用tag機制來完成這個功能。由於tag只會笨拙地分析代碼中的字符串,並不能識別其語法說語義,導致代碼的提示並不好用。隨着clang的出現,使開發人員可以對程序代碼進行事實上的語義分析(調用clang分析器之類的),於是真正的智能提示和補全插件出現了,它就是由 google 的工程師 Strahinja Val Markovic 所開發的YCM(https://github.com/Valloric/YouCompleteMe)。

5.1 YouCompleteMe的安裝與配置

YCM使用C++和python開發,是一個復雜的插件,光是通過Vundle下載的文件就達到120多MB。另外YCM不只是有新的開發的功能,它還包含了其他一些有用的插件。下圖是作者本人提示的演示動圖:

除了代碼提示與補全外,借助libclang強大的語法與語義分析能力,YCM還可以在編輯的時候提示出錯的行與出錯原因,如下圖所示:

另外,YCM還可以補全路徑,文件名等。

 

安裝與配置步驟:

  1. 如果是在Ubuntu 14.04上,運行以下命令安裝
      
    sudo apt-get install vim-addon-manager 
    sudo apt-get install vim-youcompleteme
    vim-addons install youcompleteme
    來安裝YCM插件,非常簡單。否則到2.

    ==2016.12.30補充 在CentOS7上安裝YouCompleteMe==

    1.1.下載Vundle和YouCompleteMe插件

    輸入以下指令,下載Vundle

    git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
    下載成功后,在用戶根目錄下面,修改.vimrc文件,追加下面語句以便后續安裝YouCompleteMe插件

    set  nocompatible
    filetype off
    set  rtp+=~/.vim /bundle/Vundle .vim
    call vundle #begin()
    Plugin 'gmarik/Vundle.vim'
    Plugin 'Valloric/YouCompleteMe'
    call vundle #end()
    filetype plugin indent on   

    然后在vim中先按Esc建,並且輸入以下指令安裝插件:

    :PluginInstall 
    1.2.編譯YouCompleteMe

    在編譯之前下載編譯工具,准備編譯YouCompleteMe

    yum install gcc gcc-c++ cmake python-devel
    編譯YouCompleteMe使其支持C/C++ 自動補全

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

     

  2. 如果是Ubuntu 12.04,有好多問題要解決,如果條件允許最好直接用14.04. 否則到3.
    a. 系統自帶的vim版本過低,需要先把版本升級到7.4,目前除了下源碼編譯我不知道有什么別的方法。
    參考:https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source
    b. CMake版本過低,需要升級到2.8.11以上。到http://www.cmake.org/download/ 下一高版本即可。
    c. 有可能沒有安裝ctags,apt-get安裝一個即可,后文要用到。
  3. 與以上插件一樣,在.vimrc中添加 Plugin 'Valloric/YouCompleteMe',並運行:PluginInstall命令安裝。
  4. 下載最新的clang。
    YCM是為clang 3.6設計的,理論上的最低版本不應低於3.2+。YCM使用clang提供的libclang來解析代碼主義等.
    從 http://llvm.org/releases/download.html 下載為你的系統預編譯好的clang。
    但上面的列表並沒有為所有系統提供精確的版本,比如我要在CentOS 7.0 64bit上編譯YCM,但上面沒有,所以只好自己編譯,方法是:
    a. 下載LLVM source code: llvm-3.6.2.src.tar.xz, 解壓到llvm-3.6.2.src
    b. 下載Clang source code: cfe-3.6.2.src.tar.xz, 解壓到llvm-3.6.2.src/tools/clang
    c. 下載Compiler RT source code: compiler-rt-3.6.2.src.tar.xz, 解壓到llvm-3.6.2.src/projects/compiler-rt
    d. 下載Clang tools Extra:clang-tools-extra-3.6.2.src.tar.xz,解壓到llvm-3.6.2.src/tools/clang/tools/extra
    e. 不妨在llvm-3.6.2.src父目錄中建立build目錄並編譯
    mkdir llvm_build; cd llvm_build
    ../llvm-3.6.2.src/configure --enable-optimized --enable-targets=host-only
    make && make install
    這里一定要記得make install,否則clang源碼中的頭文件沒有放到/usr/include相關目錄下,一會編譯YCM庫時會報找不到頭文件的錯誤。(這個編譯的非常慢,生成1.6GB+文件)

  5. 編譯ycm_support_libs。
    a. 這要求系統安裝了cmake, python(2.6+), python-devel(2.6+)等,如果不滿足條件cmake的時候會提示錯誤。
    b. cd~; mkdir ycm_build; cd ycm_build
    c. 如果是安裝了預編譯好的clang,請運行cmake -G "Unix Makefiles" -DPATH_TO_LLVM_ROOT=~/clang+llvm-3.4.2-x86_64-unknown-ubuntu12.04 . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp,生成Makefile。其中clang+llvm-3.4.2-x86_64-unknown-ubuntu12.04是clang預編譯包解壓后的路徑,里面有bin,lib,include等目錄;
    否則,如果是自己在第4步從源碼編譯的clang,則運行 cmake -G "Unix Makefiles" -DEXTERNAL_LIBCLANG_PATH=~/llvm_build/Release+Asserts/lib/libclang.so . ~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp,生成Makefile。其中~/llvm_build是用於從源碼編譯的build目錄。
    d. 運行 make ycm_support_libs生成YCM支持庫
    這一過程會在~/.vim/bundle/YouCompleteMe/third_party/ycmd/下生成幾個.so。至此,YCM編譯已結束。
  6. 配置YCM
    a. YCM在語義分析時使用libclang,而libclang需要參數選項,這從哪里來呢?YCM通過提供給一個代碼工程一個python文件的方式來通知libclang所需的參數選項,這個文件就是.ycm_extra_conf.py。YCM安裝好后在,在路徑~/.vim/bundle/YouCompleteMe/third_party/ycmd/examples/.ycm_extra_conf.py有一個默認的配置文件,可以把它拷貝到你的代碼所在主目錄下,並進行修改。主要是修改此文件中的flags表,加入自己代碼所在路徑、語言類型(C/C++)等。
    復制代碼
    # 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',
    ]
    復制代碼

    b. 在.vimrc中添加以下配置項(更多項見https://github.com/Valloric/YouCompleteMe#general-usage)。

    復制代碼
    " YCM                                                              
    " 允許自動加載.ycm_extra_conf.py,不再提示                         
    let g:ycm_confirm_extra_conf=0                                     
    " 補全功能在注釋中同樣有效                                         
    let g:ycm_complete_in_comments=1                                   
    " 開啟tags補全引擎                                                 
    let g:ycm_collect_identifiers_from_tags_files=1                    
    " 鍵入第一個字符時就開始列出匹配項                                 
    let g:ycm_min_num_of_chars_for_completion=1                        
    " YCM相關快捷鍵,分別是\gl, \gf, \gg                                                    
    nnoremap <leader>gl :YcmCompleter GoToDeclaration<CR>              
    nnoremap <leader>gf :YcmCompleter GoToDefinition<CR>               
    nnoremap <leader>gg :YcmCompleter GoToDefinitionElseDeclaration<CR>
    復制代碼

其中,

  • g:ycm_confirm_extra_conf如果不設為0的話,用vim每次打開代碼文件,YCM都會提示是否確認加載某某.ycm_extra_conf.py文件;
  • ycm_collect_identifiers_from_tags_files設為1,指定YCM收集傳統tags文件的信息,另外當tags改變時,YCM會重新索引它們。YCM對tags文件的格式有特殊的要求: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:<lang> field in the tags output。如有問題請參閱YCM官網相關FAQ;
    比如引入C++tags:
    " 引入 C++ 標准庫tags
    set tags+=/data/misc/vim/stdcpp.tags
  • 3個快捷鍵設置是用來快速跳轉到符號聲明或定義的。我往往只用gg,即將光標定位到某個符號上,按\鍵后(默認的leader鍵是\),快速按兩次g鍵,將跳轉到該符號的聲明或定義位置(Tips: 按<ctrl>+o返回)

其他技巧:

  • 執行:YcmDiags顯示所有錯誤, 它其實是打開了一個location list窗口,也可能通過:lopen打開. 使用:lclose可以關閉
  • 有些系統函數如fopen, strcpy如果不智能提示,可以按<Ctrl>+<Space>鍵。
  • 如果有的文件死活無法正確提示(如果結構體之類),請檢查一下文件編碼,改成utf-8。(vim中 :set fileencoding=utf8)

 

5.2 完善代碼提示與補全

 如5.1所述,YouCompleteMe插件是如此地強大。然而,某些時候它可能還是會有些小問題,比如無法提示宏定義等等,導致無法補全,這時候還是需要借助傳統的tags文件。indexer插件可以針對不同的工程目錄自動地生成、更新和引入不同的tags文件,詳見http://www.vim.org/scripts/script.php?script_id=3221。它需要依賴DfrankUtil和Vimprj 兩個插件,需要一並安裝。

安裝與配置步驟:

1. 在.vimrc的Vundle區域內加入以下內容

Plugin 'DfrankUtil'                                             
Plugin 'vimprj'                                                 
Plugin 'indexer.tar.gz'

之后運行:PluginInstall安裝;

2. 打開.vimrc,加入以下內容:

" indexer                                                       
" 設置indexer 調用 ctags 的參數                                 
" 默認 --c++-kinds=+p+l,重新設置為 --c++-kinds=+p+l+x+c+d+e+f+g+m+n+s+t+u+v
" 默認 --fields=+iaS 不滿足 YCM 要求,需改為 --fields=+iaSl                                       
let g:indexer_ctagsCommandLineOptions="--c++-kinds=+p+l+x+c+d+e+f+g+m+n+s+t+u+v --fields=+iaSl --e
xtra=+q"

3. indexer會根據你的代碼工程的不同,自動生成並在其中的代碼文件被打開時自動加載tags文件。它是通過配置文件來指定工程設置的,此文件為~/.indexer_files。以下是一個配置示例,演示了2個不同的工程的Indexer配置。

復制代碼
[CoolProject] 
/home/user/cool_project 

[AnotherProject] 
option:ctags_params = "--languages=c++" 
/home/user/another_project/src 
/home/user/another_project/lib 
復制代碼

 

6 參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM