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

How do I paste the current Git commit hash directly from Vim using the expression register?

Answer

"=system('git rev-parse --short HEAD')->trim()<CR>p

Explanation

If you frequently write commit references in notes, code comments, or release docs, you can avoid shell context switches and paste the hash straight from Vim. The expression register evaluates Vimscript on demand, so you can run a shell command, clean its output, and insert it in one sequence. This is fast in review/debug workflows where you need a precise revision ID repeatedly.

How it works

"=system('git rev-parse --short HEAD')->trim()<CR>p
  • "= opens the expression register prompt
  • system('git rev-parse --short HEAD') runs Git and captures stdout
  • ->trim() removes the trailing newline from shell output
  • <CR> confirms the expression and stores the result in the expression register
  • p puts the resulting text after the cursor

Example

Before:

Investigated regression in parser, fixed in commit: [cursor]

After (example hash):

Investigated regression in parser, fixed in commit: a1b2c3d

Tips

  • Use P instead of p when you want insertion before the cursor
  • The same pattern works for other dynamic values, for example branch names (git branch --show-current)
  • If the current file is not in a Git repo, the command returns an error string; run it only in repository buffers

Next

How do I jump to the top of a file without creating a new jumplist entry?