Recording macros in VIM
For recording a macro:
Type, in normal mode,
qfollowed by a letter to start recording.
Do whatever needs to be done; remove, add and transform text.
Type, again in normal mode,
qto stop recording.
As a reference, the letter typed after
q is the register where the macro is saved.
For applying a macro:
Type @ and the chosen register to apply the recording
Type @@ to apply the last recording
Type n @ @ or n@ and the chosen register to apply recording
As an example, consider the following text file
Hello World test a b c b c a tes a b rem c d no asd asd test test no test
It is possible to replace
rem with the following commands ( POSIX-like, PowerShell, or even cmd):
vi file qa /test<enter> de i rem <esc> q @a 3@@ ZZ
The commands are, literally:
vi file: open file with a vi-like editor
qa: initiate recording on register a
/test<enter>: find text "test"
de: delete until end of word
i: enter insertion mode
rem: write rem
<esc>: enter command mode
q: stop recording
@a: replay macro
3@@: replay macro other three times
ZZ: save and close
In this case, a global substitute is simpler, shorter, faster, less error-prone, and more robust:
vi file :%s/rem/test/g ZZ
but that’s not the point. Macros can be used for codifying more complex actions, or simple actions until one discovers there is another, simpler way to do them.
view a macro
Just show the content of the register. Supposing the macro has been recorded in register
:reg to show all registers, or
Just like macros can be created on the fly, it is possible to edit them (also on the fly). This is particularly useful if the macro is complex enough and has a little error that repeating all the action from start would need more time than editing the existing one.
Supposing the macro has been recorded in register
:let @a='in normal mode (do not press enter!)
Press ctrl+r ctrl+r a to insert the current contents of register
Edit the text as required, for example from
Add a trailing
'to finish the command
persisting a macro
Neovim (and vim since version 8 AFAIK) stores all macros in its cache. Thus without any intervention, it is possible to close and reopen the editor and continue to use the created macro.
Like it is possible to edit a macro, it is also possible to store it in the configuration file, by writing
:let @a='my awesome macro'
Do you want to share your opinion? Or is there an error, same parts that are not clear enough?
You can contact me here.