20230517-repeat_after_me.md (2193B)
1 After learning about [registers](20230511-reg_5_standing_by.html){target="_blank" rel="noreferrer"} in Vim, [macros](https://vim.fandom.com/wiki/Macros){target="_blank" rel="noreferrer"} were a logical next step. 2 3 Macros use registers as well but instead of just saving chunks of text they record repeatable steps meaning the same actions can be performed again and again. 4 5 To start recording a macro, in Normal mode hit `q` and a register, i.e `qa` 6 7 The status line will now show that a recording is taking place 8 ``` 9 recording @a 10 ``` 11 12 Any actions you take now will be recorded to register `a`. To stop a recording hit `q` again. To replay the macro use `@` followed by the register, `@a`. If you want to play the last played macro hit `@@`. 13 14 Sometimes you may want to edit a macro. If it is a lot of steps you won't want to record the whole thing again so it is possible to edit it in Vim's command line. 15 16 1. declare the register you are setting with `:let @a='` 17 2. type Ctrl-r Ctrl-r `a` to paste in the contents of register `a` 18 3. edit as required 19 4. append an apostrophe, `'`, to close the statement and hit Return 20 21 If you need to add a control character within the macro, such as Return, type Ctrl-v followed by the required key. For example _Ctrl-v Return_ produces `^M`. 22 23 To see the Vim help for this method incant 24 ``` 25 :help i_ctrl-v 26 ``` 27 28 As macros are saved in registers viewing them is the same as viewing registers 29 ``` 30 :registers 31 ``` 32 33 It is also possible to declare macros in ~/.vimrc so that they are available to each session. This is done using the same `let` declaration shown above. 34 35 In ~/.vimrc 36 ``` 37 let @t='<macro>' 38 ``` 39 40 For every Vim session opened the `t` register will always be set to this and can be played using `@t`. 41 42 If you want to save a recorded macro to ~/.vimrc, in Insert mode use _Ctrl-r Ctrl-r t_ to paste in the contents, save having to type it all out again. 43 44 Getting the hang of macros can be fun as well as frustrating. Spending longer creating a perfect macro than the time taken to complete the task is probably quite common, but when you get it the satisfaction is "*chefs kiss*". 45 46 To see the Vim help page on macros incant 47 ``` 48 :help recording 49 ```