Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Ubuntu 下為 Vim 加上 C++ 智慧補全的完整設定

Vim 本身對 C++ 的補全能力相當有限,但只要裝上 OmniCppComplete 並餵給它一份標頭檔產生的 tags,就能獲得接近 IDE 的成員提示體驗。以下是在 Ubuntu 上的完整做法。

先確認現況

用 Vim 開啟 .cc 或 .cpp 檔案,在指令模式下輸入:

:set omnifunc?

若輸出為 omnifunc=ccomplete#Complete,代表目前只有最基本的關鍵字補全,確實有必要做下面的設定。

1. 安裝 OmniCppComplete

插件下載頁:
https://www.vim.org/scripts/script.php?script_id=1520

Ubuntu 下為 Vim 加上 C++ 智慧補全的完整設定

安裝方式與多數 Vim 插件相同——切換到 ~/.vim/ 目錄,把下載的壓縮檔直接解開即可。

2. 建立 tags 子目錄

mkdir -p ~/.vim/tags

3. 產生 stdc++ 的 tags

A)先下載社群整理過、可直接使用的 libstdc++ 標頭檔:
https://www.vim.org/scripts/script.php?script_id=2358

Ubuntu 下為 Vim 加上 C++ 智慧補全的完整設定

下載後解壓到 ~/.vim/tags。

B)接著用 ctags 掃出索引:

$ cd ~/.vim/tags
$ ctags -R --c++-kinds=+p --fields=+iaS --extra=+q --language-force=C++ cpp_src
$ mv tags cpp

4. 修改 ~/.vimrc

把下列內容加進設定檔:

" configure tags - add additional tags here or comment out not-used ones
set tags+=~/.vim/tags/cpp
set tags+=~/.vim/tags/gl
set tags+=~/.vim/tags/fl

" build tags of your own project with CTRL+F12
map <C-F12> :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q .<CR>

" OmniCppComplete
let OmniCpp_NamespaceSearch = 1
let OmniCpp_GlobalScopeSearch = 1
let OmniCpp_ShowAccess = 1
let OmniCpp_ShowPrototypeInAbbr = 1 " show function parameters
let OmniCpp_MayCompleteDot = 1 " autocomplete after .
let OmniCpp_MayCompleteArrow = 1 " autocomplete after ->
let OmniCpp_MayCompleteScope = 1 " autocomplete after ::
let OmniCpp_DefaultNamespaces = ["std", "_GLIBCXX_STD"]

" automatically open and close the popup menu / preview window
au CursorMovedI,InsertLeave * if pumvisible() == 0|silent! pclose|endif
set completeopt=menuone,menu,longest,preview

其中 OmniCpp_MayCompleteDot、MayCompleteArrow、MayCompleteScope 分別對應 .、->、:: 三種觸發情境,是體感提升最明顯的三行;Ctrl+F12 則是替自己的專案快速建 tags 的快捷鍵。

5. 驗證成果

用 Vim 打開任一 cpp 檔,先輸入:

std::

這時會列出 std 命名空間下的所有標識符,用 Ctrl+N/Ctrl+P 挑選。再繼續輸入 std::vector 與一個變數名 vi,接著打 vi.,Vim 便會自動提示該物件可用的成員。

Copyright © Linux教程網 All Rights Reserved