使用 vim 文本編輯器比較兩個文件的不同,可以采用兩種打開方式:
方式一,使用 vim 同時打開兩個待比較的文件。
比較通用方式是采用 vim -d 選項,具體命令,如下:
vim -d <file1> <file2>
在 Linux/Mac 下,還可以采用 vimdiff 封裝命令, 具體如下:
vimdiff <file1> <file2>
但在 Window 版本的 gvim(Vi IMproved 8.1 版本) 中,沒有名稱 vimdiff 可以執行文件,可以采用 diff 命令按上面的方式執行,不過只返回命令行界面下的比較結果。
方式二,先用 vim 打開一個文件,然后啟動 diff mode,與另一個文件進行比較。
1) 正常使用 vim 編輯一個文件 oneFile,命令如下:
vim oneFile
2) 然后采用 :diffthis 或 :diffsplit 命令啟動 diff mode。
a) 采用 :diffthis 命令的具體示例
在當前文件 oneFile 中,啟動 diff mode,命令如下:
:diffthis
在新窗口中,打開另一個文件 otherFile。如果采用垂直切分(vertical split)方式打開文件 otherFile,命令如下:
:vs otherFile
如果采用水平切分(horizontal split)方式打開,命令如下:
:split otherFile
在當前文件 otherFile 中,啟動 diff mode,命令如下:
:diffthis
到此,就可以看到兩個文件的差異顯示了。
關閉 diff mode 的命令,如下:
:diffoff
b) 采用 :diffsplit 命令的具體示例
一條命令即可以顯示兩文件之間的差異,如下:
:diffsplit otherFile
注:可以通過 :h diff 或 :h vimdiff 查看更多幫助信息。
diff mode 常用命令速查表(cheat sheet)
[c Jump to the previous diff 跳到前一個不同之處
]c Jump to the next diff 調到下一個不同之處
do diffget: Pull the changes to the current file 將所有的不同之處拉到當前文件,使之與另一個文件內容相同
dp diffput: Push the changes to the other file 將所有的不同之處推到另一個文件
:diffupdate rescan files for differences 重新掃描文件之間的不同之處
Folds 折疊命令
zo/zO Open 打開折疊
zc/zC Close 關閉折疊
za/zA Toggle 在打開折疊和關閉折疊之間進行切換
zv Open folds for this line 為當前行打開折疊
zM Close all 關閉所有折疊
zm Fold more (foldlevel += 1) 更多地折疊
zR Open all 打開所有折疊
zr Fold less (foldlevel -= 1) 更少地折疊
注:通過命令 :h fold-commands 查看更多關於折疊命令的幫助信息。
參考資料
[1] How do I use vim as a diff tool? https://vi.stackexchange.com/questions/625/how-do-i-use-vim-as-a-diff-tool
[2] vim-diff cheatsheet. https://devhints.io/vim-diff
