若想讓檔案中的所有 tag 都上色,可以設定這兩個映射:
<F11> -- 依 tags 檔生成 tags.vim 並高亮
<F12> -- 只依既有的 tags.vim 高亮
:map <F11> :sp tags<CR>:%s/^\([^ :]*:\)\=\([^ ]*\).*/syntax keyword Tag \2/<CR>:wq! tags.vim<CR>/^<CR><F12>
:map <F12> :so tags.vim<CR>
警告:tags 檔越長,速度越慢,Vim 吃掉的記憶體也越多。
這裡只處理 typedef,也可以自行擴充到 union 與 struct。前提是安裝 Exuberant ctags(https://ctags.sf.net)。在 Makefile 中加入:
# 建立 types 的高亮檔,需要 Exuberant ctags 與 awk
types: types.vim
types.vim: *.[ch]
ctags -i=gstuS -o- *.[ch] |\
awk 'BEGIN{printf("syntax keyword Type\t")}\
{printf("%s ", $$1)}END{print ""}' > $@
再在 .vimrc 中加入:
" 載入 types.vim 高亮檔,若存在的話
autocmd BufRead,BufNewFile *.[ch] let fname = expand('<afile>:p:h') . '/types.vim'
autocmd BufRead,BufNewFile *.[ch] if filereadable(fname)
autocmd BufRead,BufNewFile *.[ch] exe 'so ' . fname
autocmd BufRead,BufNewFile *.[ch] endif
原版 F11 只抓得到函式內部的定義與函式名,抓不到巨集。改成下面這版即可:
" 依 tags 檔生成高亮檔 tags.vim
map <F11> :sp tags<CR>:set nohls<CR>:%s/file/file/<CR>:%s/^\([^ :]*:\)\=\([^ ]*\).*/syntax keyword Tag \2/<CR>:wq! tags.vim<CR>/^<CR><F12>
" 高亮檔案裡的所有標籤
map <F12> :so tags.vim<CR>
關鍵差別在於 ctags 產生的 tags 內容與正則替換的處理方式,調整後巨集名稱也能被納入高亮。