20

Sometimes I create macros. Sometimes I create the same macro multiple times.

Sometimes I get tired of creating the same macro over again. Can I store macros? Can I load a preset of macros? Can I make a macro and save it forever?

1 Answer 1

19

Yes, you can! There are a couple ways to do this. By default, all registers will be saved into your viminfo file, and loaded once you start vim. This is the easiest way. However, it's not foolproof. Each register will be lost if you accidentally record/yank over it.

The better way to save a specific macro is to put it in your .vimrc. For example, let's say you want foo to be saved into macro a. This could be achieved with:

let @a='foo'

in your vimrc. If you have your macros already made, you could type

ilet @a='<C-r><C-r>a'<esc>

to paste the current contents of the macro, if you don't feel like typing it all out again.


Thanks to Andrew Keeton for pointing out <C-r><C-r>

5
  • 3
    You'll probably want to use <C-r><C-r> (two, instead of one) to insert the text literally Commented Mar 20, 2019 at 16:51
  • 1
    @AndrewKeeton Ooh, great improvement. Thanks for letting me know about that
    – DJMcMayhem
    Commented Apr 12, 2019 at 16:38
  • 1
    <c-r><c-r> won't work if your macro contains special key sequence such as <c-right>, "ap don't have this problem.
    – dedowsdi
    Commented Nov 7, 2019 at 6:08
  • 2
    note you can map the string, e.g. `nnoremap <Leader>fo foo' in your vimrc so that you establish a direct keybinding. The advantage is that you keep your registers clean. Commented Oct 22, 2020 at 13:43
  • An advice I give all you is to use double quotes so you can use things like \<c-a>\<esc>, otherwise your control characters must be typed literally. Commented Sep 5, 2021 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.