How do I paste the last Ex command I ran into my buffer?
Answer
":p
Explanation
The : register holds the most recently executed Ex command. Pressing " followed by : and then p pastes that command directly into your buffer. This is invaluable when you want to save a useful command to your vimrc, document it, or tweak it before running it again.
How it works
"tells Vim you are about to specify a register:is the register name — it stores the last Ex command you ranppastes the register contents after the cursor
For example, if your last command was :%s/foo/bar/g, then ":p inserts that exact string into your buffer.
Example
You just ran a complex substitute command:
:%s/\v(\w+)\.(\w+)@(\w+)/\1 [\2] <\3>/g
Now you want to save it. Press ":p and the command text appears in your buffer:
:%s/\v(\w+)\.(\w+)@(\w+)/\1 [\2] <\3>/g
You can then wrap it in a mapping or function and add it to your vimrc.
Tips
- Use
":P(uppercase P) to paste before the cursor instead of after - In insert mode, press
<C-r>:to insert the last command at the cursor without leaving insert mode - The
/register works the same way for search patterns:"/ppastes your last search - The
.register holds the last inserted text:".ppastes whatever you last typed in insert mode - The
%register holds the current filename:"%ppastes the path of the file you are editing - Use
:registers :to inspect the contents of the command register without pasting it - Combine with
@:to execute the last Ex command again — while":ppastes it and@:reruns it