Vim 配合 ctags(符號定義跳轉) 與 cscope(呼叫關係、引用搜尋),可達到甚至超越 Source Insight 的程式碼瀏覽能力。本文以 Ubuntu 20.04/22.04 為例,示範從安裝、資料庫建立、Vim 整合、快捷鍵映射到多專案管理的完整流程。
sudo apt update && sudo apt install -y vim-gtk3 exuberant-ctags cscope
# vim-gtk3 提供 +clipboard +python3 支援,適合圖形環境
cd /path/to/project
ctags -R --c++-kinds=+p --fields=+iaS --extra=+q .
# -R 遞迴、--c++-kinds=+p 函式原型、--fields=+iaS 繼承/存取/簽名、--extra=+q 類成員標識
~/.vimrc)" 快速重建 tags(F5)
nnoremap <F5> :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q .<CR><CR>
" 多專案 tags 疊加搜尋
set tags+=/path/to/project1/tags
set tags+=/path/to/project2/tags
" 或使用 tags=./tags; 向上遞迴尋找
| 鍵 | 動作 |
|---|---|
| Ctrl+] | 跳至定義 |
| gCtrl+] | 多重定義時列出清單選擇 |
| Ctrl+t | 返回上一層(標籤堆疊) |
| :ts | 列出所有匹配標籤 |
| :tn / :tp | 下一個/上一個匹配 |
cd /path/to/project
cscope -Rbq
# -R 遞迴、-b 只建庫不進入介面、-q 建立倒排索引加速
# 產生 cscope.out、cscope.in.out、cscope.po.out
" 自動載入專案 cscope.out
if has("cscope")
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
" 加入目前目錄 cscope.out
if filereadable("cscope.out")
cs add cscope.out
elseif filereadable("/path/to/project/cscope.out")
cs add /path/to/project/cscope.out
endif
endif
" 快捷鍵映射(Leader 鍵預設 \)
nmap <Leader>cs :cs find s <C-R>=<C-W><CR><CR> " 找呼叫此函式的地方
nmap <Leader>cg :cs find g <C-R>=<C-W><CR><CR> " 找全域定義
nmap <Leader>cc :cs find c <C-R>=<C-W><CR><CR> " 找呼叫此函式的函式
nmap <Leader>ct :cs find t <C-R>=<C-W><CR><CR> " 找文字字串
nmap <Leader>ce :cs find e <C-R>=<C-W><CR><CR> " 找 EGrep 模式
nmap <Leader>cf :cs find f <C-R>=<C-W><CR><CR> " 找檔案
nmap <Leader>ci :cs find i ^<C-R>=<C-W><CR>$<CR> " 找 include 的檔案
nmap <Leader>cd :cs find d <C-R>=<C-W><CR><CR> " 找被此函式呼叫的函式
安裝 vim-gutentags 外掛(需 Vim 8+ / Neovim),自動在專案根目錄建立/更新 tags 與 cscope.out:
Plug 'ludovicchabant/vim-gutentags'
let g:gutentags_modules = ['ctags', 'cscope']
let g:gutentags_ctags_extra_args = ['--c++-kinds=+p', '--fields=+iaS', '--extra=+q']
let g:gutentags_cscope_build_inverted_index = 1
tags、cscope.out。~/.vimrc 用 set tags+=/proj1/tags 疊加,或依賴 gutentags 自動偵測專案根目錄(含 .git、compile_commands.json、CMakeLists.txt 等標記)。:cs reset 清除舊資料庫,再 :cs add /new/proj/cscope.out。| 現象 | 原因與對策 |
|---|---|
| Ctrl+] 無反應 | 未建立 tags、或 tags 路徑不在 &tags 中,執行 :set tags? 檢查 |
| cscope 提示 "no connections" | Vim 未編譯 +cscope 支援,改裝 vim-gtk3 或 vim-nox |
| 符號搜尋不全 | 原始碼編碼非 UTF-8,需在 ctags/cscope 參數加 -I 或統一轉碼 |
| 大專案建庫極慢 | 排除 build/、.git/、第三方庫目錄:ctags -R --exclude=build --exclude=.git . |
完成上述配置後,Vim 即具備「跳轉定義、尋找引用、呼叫圖、全域搜尋」完整 IDE 級導航能力,且保留 Vim 極速編輯與鍵盤中心操作優勢。
Linux 系統下使用 FPM 快速構建 RPM 包實戰指南
CentOS 6.4 部署 GlusterFS 分布式存儲:從安裝到多節點複製卷實戰
Yum 指令完整功能速查表:查詢、安裝、更新、移除、快取與倉庫控制
Linux 服務器中毒應急響應:find + grep 快速定位 Webshell 與後門
Linux 虛擬機安裝 Windows 10 完整教學:VirtualBox 部署、BIOS 虛擬化啟用、CMPXCHG16B 修正
Ubuntu 安裝 Xtreme Download Manager (XDM) 完整教學
Linux SSH 免密碼登入完整設定指南:RSA 金鑰對產生、authorized_keys 部署、權限修復與 ssh-copy-id 快速部署