To start defining a keyboard macro, type C-x (
start-kbd-macro). From then on, anything you type continues to be
executed, but also becomes part of the definition of the macro. ‘Def’
appears in the mode line to remind you of what is going on. When you are
finished, the C-x ) command (
end-kbd-macro) terminates the
definition, without becoming part of it.
C-x ( M-f foo C-x )
defines a macro to move forward a word and then insert ‘foo’.
You can give C-x ) a repeat count as an argument, in which case it repeats the macro that many times right after defining it, but defining the macro counts as the first repetition (since it is executed as you define it). If you give C-x ) an argument of 4, it executes the macro immediately 3 additional times. An argument of zero to C-x e or C-x ) means repeat the macro indefinitely (until it gets an error or you type C-g).
Once you have defined a macro, you can invoke it again with the
C-x e command (
call-last-kbd-macro). You can give the
command a repeat count numeric argument to execute the macro many times.
To repeat an operation at regularly spaced places in the text, define a macro and include as part of the macro the commands to move to the next place you want to use it. For example, if you want to change each line, you should position point at the start of a line, and define a macro to change that line and leave point at the start of the next line. Repeating the macro will then operate on successive lines.
After you have terminated the definition of a keyboard macro, you can add to the end of its definition by typing C-u C-x (. This is equivalent to plain C-x ( followed by retyping the whole definition so far. As a consequence it re-executes the macro as previously defined.