Recording macros in VIM
This is a short introduction to how to use vim macros, also known as records. (Not to be confused with Vim records)
A macro is a sequence of commands that can be saved, edited, and applied to a file.
Vim makes it actually very easy to create and apply such records.
TL;DR
For recording a macro:
Type, in normal mode,
qfollowed by another letter of your choice to start recording.Do whatever needs to be done; remove, add, and transform text.
Type, again in normal mode, press
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
ntimes
An example
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
testIt is possible to replace test with rem with the following commands in the terminal (with a POSIX-like shell, such as bash, PowerShell, or even cmd):
vi file<enter>
qa
/test<enter>
de
i
rem
<esc>
q
@a
3@@
ZZThe commands are, literally:
vi file<enter>: open the file with a vi-like editorqa: initiate recording on register a/test<enter>: find the text "test"de: delete until the end of the wordi: enter insertion moderem: write rem<esc>: enter command modeq: stop recording@a: replay macro3@@: replay macro other three timesZZ: save and close
In this case, a global substitute is simpler, shorter, faster, less error-prone, and more robust:
vi file<enter>
:%s/rem/test/g<enter>
ZZBut 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 a, use :reg to show all registers, or :reg a.
Edit recording
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 actions from the start would need more time than editing the existing one.
Supposing the macro has been recorded in register a
Type
:let @a='in normal mode (do not press ↵ Enter!)Press Ctrl+R Ctrl+R A to insert the current contents of register
a.Edit the text as required, for example from
:let @a='/test^Mdeirem^[<80><fd>ato:let @a='/test^Mdeiremoved^[<80><fd>aAdd a trailing
'to finish the commandpress ↵ Enter
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'

If you have questions, comments, or found typos, the notes are not clear, or there are some errors; then just contact me.