X

使用 vimdiff 來呈現 Git diff 差異

GIT diff 最近一次 commit 到此次更改的所有變動(進階參數, 暫時先不列入此範圍), 呈現結果跟一般 diff 差不多.

  • 註: 若於 .gitconfig 設定下述, 則可多加上顏色區別.

    [color]
    diff = auto

若想要用 vimdiff 來取代 Git diff, 要如何做呢?

2015/5/26 補充:vim - Viewing all git diffs with vimdiff - Stack Overflow 有簡易的作法了。

只要下述三行:

  1. git config --global diff.tool vimdiff
  2. git config --global difftool.prompt false
  3. git config --global alias.d difftool
  4. 就可以使用 git d filename 或 git d # diff all
  5. 註:git config --global alias.diff difftool 這樣子做沒有用,預設的 diff 不會被吃掉,用此作法需要另外換 alias name
  6. 到此即完成

下述留著參考用。

(下述步驟 參考此文: Git Diff with Vimdiff)

設定 vimdiff 取代 Git diff

  1. vim /usr/local/bin/git_diff_wrapper # 此位置只要放在可被執行的路徑即可, 在此先放在 /usr/local/bin/.

    #!/bin/sh
    vimdiff "$2" "$5"

  2. chmod +x /usr/local/bin/git_diff_wrapper
  3. vim ~/.gitconfig # 下述兩行都需要加入, pager 使用 diff 的設定, diff 呼叫外部程式 git_diff_wrapper.

    [diff]
    external = git_diff_wrapper
    [pager]
    diff =

  4. 或 vim ~/.gitconfig (二者挑其一即可)

    [diff]
    external = git_diff_wrapper
    [core]
    pager =

  5. 完成.

上述完成後, 直接於修改過的專案目錄下, 輸入 git diff, 就會於 vimdiff 的畫面 顯示 差異結果.

顯示 預設 git diff 結果

若想要看原始 git diff 的結果, 可用下述做法:

  1. vim ~/.bashrc # 最後一行加入下述

    function git_diff() {
    git diff --no-ext-diff -w "$@" | vim -R -
    }

    Git diff 參數說明
    • --no-ext-diff : 不允許執行外部 diff 命令(防止 call vimdiff)
    • -w : 忽略所有空白
    • -R : 將 vim 設定於唯讀模式(read-only mode)
    • - : 讓 vim 作為 pager
    • 詳細可見: git diff --help
  2. 於修改過的專案目錄 輸入 git_diff, 就會進入 vim 編輯原始 git diff 的結果.

Vimdiff 操作快速鍵

下述部份摘錄自此篇: Quick and Dirty : Vimdiff Tutorial

最常用的是 dp, vimdiff 會顯示左右兩個視窗, 於兩者差異處, 此區塊是要的, 就切換到要的那個視窗, 對想要的那個段落按 dp, 就會自動將此段內容複製到另外一個視窗的對應位置.

  • do - Get changes from other window into the current window.
  • dp - Put the changes from current window into the other window.
  • ]c - Jump to the next change.
  • [c - Jump to the previous change.
  • Ctrl W + Ctrl W - Switch to the other split window.
  • :diffupdate – diff update
  • :syntax off – syntax off
  • zo – open folded text
  • zc – close folded text
Tsung: 對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.
Related Post