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

How do I paste my last Ex command into the command line or a buffer?

Answer

<C-r>:

Explanation

Vim stores your last executed Ex command in the read-only : register. You can insert it anywhere you can use <C-r>: in Insert mode, in the command line, or in search. This is handy for reusing complex commands without having to retype them.

How it works

  • <C-r> — in Insert mode or on the command line, insert the contents of a register
  • : — the colon register, which contains the last executed Ex command

On the command line (:), pressing <C-r>: pastes the last command so you can edit it before running it again. In Insert mode, <C-r>: inserts the last command text into the buffer.

Example

You ran :s/foo/bar/g on a file. Later you want to run a variation of it:

:       ← open command line
<C-r>:  ← pastes: s/foo/bar/g

Now you can edit bar to baz and run :s/foo/baz/g without retyping.

Tips

  • In Insert mode, <C-r>: lets you document what command you just ran by pasting it directly into the file
  • Combine with @: to repeat the last command without modification
  • Other useful read-only registers: <C-r>/ (last search pattern), <C-r>. (last inserted text), <C-r>% (current filename)
  • You can also access these registers in Normal mode with ":p, "/p, etc.

Next

How do I visually select a double-quoted string including the quotes themselves?