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

How do I execute the contents of a register as an Ex command?

Answer

:@a

Explanation

How it works

The command :@a executes the contents of register a as an Ex command. This is different from @a (without the colon), which executes the register as normal-mode keystrokes. With :@a, Vim interprets the register contents as if you typed them on the command line after :.

This is useful when you have stored Ex commands in a register and want to run them. Each line in the register is executed as a separate Ex command.

You can also use :@: to repeat the last Ex command (equivalent to @:), and :@@ to repeat whatever register was last executed with :@.

Example

Suppose you want to create a reusable formatting command:

  1. Write the Ex command in your buffer: %s/\s\+$//e
  2. Yank it into register a: "ayy
  3. Now run it with :@a -- this strips trailing whitespace from the entire file

You can store multiple commands by putting them on separate lines:

set tabstop=4
set shiftwidth=4
retab

Yank all three lines into register b with "b3yy, then run :@b to execute all three commands in sequence. This converts tabs to spaces using 4-space indentation.

This technique is especially powerful for creating ad-hoc scripts. You can write commands in a scratch buffer, edit them until they are correct, yank them into a register, and execute them. It bridges the gap between interactive Ex commands and full Vimscript files.

Next

How do you yank a single word into a named register?