vim 常用功能

常用功能的 plugin 及快捷鍵:

  • 游標停在字上的時候會自動 highlight 同樣的字
    開啟 vim 後輸入 z/,目前還沒找到怎麼一開 vim 就啟動自動 highlight。
  • 跳到游標所在 variable 或 function 的宣告
  • 在 .cpp 跟 .h 之間切換
    a.vim (:A)
  • 跳到游標所在的 function 的定義
    cscope (ctrl+\ g)
    ctags (g] or ctrl+])
  • 跳到游標所在的 variable local 宣告
    ctags (gd)
  • 跳到游標所在的 variable global 宣告
    ctags (gD)
  • 全 project search
    cscope (ctrl+\ t)
  • 列出 file 中有哪些 function
    taglist (F8)
  • 自動補齊
    於 insert mode ctrl + n
  • 自動補括號
  • hex mode
    :%! xxd
  • 切換 history
    ctrl + i & ctrl + o
  • 多行註解
    ESCctrl + V 選範圍、大寫 I、輸入註解符號、ESC
  • 多行取消註解
    ESCctrl + V 選範圍、delete

My .vimrchttps://github.com/cjwind/dotfiles/blob/master/vimrc

ctags taglist

$ sudo apt-get install ctags

切到 project 資料夾產生 tag 資訊:

$ ctags --extra=+f -R *

加上 --extra=+f 可以在 vim 中使用 :tag <filename> 跳到該檔案,:tag <filename> 後再 ctrl + t 可回原本檔案。

http://www.vim.org/scripts/script.php?script_id=273taglist_45.zip,解開後將 taglist.vim 放到 ~/vim/plugin

~/.vimrc 加入相關設定:

1
2
3
4
5
6
let Tlist_Ctags_Cmd = '/usr/bin/ctags'
let Tlist_Auto_Open = 1 " 讓 Tlist 自動開啟
let Tlist_Show_One_File = 1 " 不同時顯示多個文件的tag,只顯示當前文件的
let Tlist_Exit_OnlyWindow = 1 " 如果taglist窗口是最後一個窗口,則退出vim
let Tlist_Use_Right_Window = 1 " 在右側窗口中顯示taglist窗口
nnoremap <silent> <F8> :TlistToggle<CR> " F8 為開啟/關閉 Tlist 的快速鍵

ctrl + w 再加方向鍵可以切換 window,例如加右鍵就是跳到右邊的 window。

patch

有時候切換 tab 會出現 error Taglist error: Error detected while processing function <SNR>29_Tlist_Refresh_Folds,可用 patch 解決:$ patch -p0 ~/.vim/plugin/taglist.vim taglist.diff

cscope

$ sudo apt-get install cscope

切到 project 的資料夾產生 cscope 資料庫:

$ cscope -RC

之後用 vim 開啟 source code,可用 :cs 指令使用 cscope 的功能。也可以在 ~/.vim/plugin 中放 cscope_map.vim 加快捷鍵:

1
2
3
4
5
6
7
ctrl+\ s "s表Symbol,列出所有參考到游標所在字串的地方,包含定義和呼叫。
ctrl+\ g "Find this definition
ctrl+\ c "c表Call,列出所有以游標所在字串當函數名的地方。
ctrl+\ t "t表Text,列出專案中所有出現游標所在字串的地方。
ctrl+\ f "f表File,以游標所在字串當檔名,開啟之。
ctrl+\ i "i表Include,以游標所在字串當檔名,列出所有include此檔的檔案。
ctrl+\ d "d表calleD,以游標所在字串當函式名,列出所有此函式呼叫的函式。

自動 highlight

.vim/plugin 加入 autohighlight.vim

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
let @/ = ''
if exists('#auto_highlight')
au! auto_highlight
augroup! auto_highlight
setl updatetime=4000
echo 'Highlight current word: off'
return 0
else
augroup auto_highlight
au!
au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
augroup end
setl updatetime=500
echo 'Highlight current word: ON'
return 1
endif
endfunction

輸入 z/ 可開關自動 highlight 的功能。

reference here

a.vim

在 header 及 source 之間切換。script

切換指令為 :A

自動補括號

Auto Pairs

將 script 放到 ~/.vim/plugin/ 底下。

Ref