vimtricks.wiki Concise Vim tricks, one at a time.

How do I view a file as it existed at a previous Git commit in Vim?

Answer

:Gedit HEAD~3:%

Explanation

The vim-fugitive plugin lets you open any version of any file from your Git history directly in a Vim buffer using the :Gedit command. The special % symbol represents the current file's path, making it easy to time-travel through a file's history without leaving your editor.

How it works

The :Gedit command accepts a Git object reference. The format revision:path loads a specific file at a specific commit:

  • HEAD~3 means "three commits before the current HEAD"
  • % expands to the current file's path in the repository

So :Gedit HEAD~3:% loads the current file as it existed three commits ago.

Common revision formats

:Gedit HEAD~1:%        " one commit ago
:Gedit HEAD~5:%        " five commits ago
:Gedit main:%          " file as it exists on the main branch
:Gedit abc1234:%       " file at a specific commit SHA
:Gedit HEAD^:%         " parent of HEAD (same as HEAD~1)
:Gedit v2.0.0:%        " file at a tagged release
:Gedit stash@{0}:%     " file as it exists in the top stash

Opening in splits

Fugitive provides split variants so you can compare versions side by side:

:Gsplit HEAD~1:%       " open in a horizontal split
:Gvsplit HEAD~1:%      " open in a vertical split
:Gtabedit HEAD~1:%     " open in a new tab

Browsing any file in the repo

You are not limited to the current file. Specify any path relative to the repository root:

:Gedit main:src/app.js
:Gedit HEAD~2:README.md

Diffing against an older version

Combine with :Gdiffsplit to see exactly what changed:

:Gdiffsplit HEAD~3:%   " diff current file against 3 commits ago
:Gvdiffsplit main:%    " vertical diff against the main branch

Tips

  • The historical file opens in a read-only buffer — you cannot accidentally edit it
  • Use :Gedit :0:% to view the staged (index) version of the current file
  • Press C on any fugitive object buffer to jump to the commit that introduced it
  • Combine :Gedit with :Git log --oneline % to first find the commit SHA you want, then open the file at that revision

Next

How do I edit multiple lines at once using multiple cursors in Vim?