Tips for Creating Good Macros

It's easy to learn how to record and reuse your keystrokes. However, when you're starting out, you make a few mistakes: you create a macro, use it, and then find out that it doesn't do exactly what you thought. With a little care, it's easy to make your macros more useful and less vulnerable to mistakes.

Good macros work in all situations. Therefore, within a macro, you should use commands that are absolute rather than relative. For example, if you write a macro that puts a formatting string around the word the cursor is on, you want the macro to work no matter how long the word is. Therefore, you would use an absolute command such as M-f (for forward-word) rather than a few C-fs to move forward one character at a time. Similarly, commands such as C-e and C-a are good for finding the beginning or end of a line rather than moving the cursor forward or backward.

Often, macros start with a search command that brings you to the place in the file you want the macro to start. It's a good idea to type the search argument (as in C-s searchstring) rather than using the command to repeat the last search (C-s C-s). You may have changed the search string between the time you define the macro and the time you execute it, and C-s C-s remembers only what the last search string was.

It is often a good idea to add extra commands (typically C-a and C-e) that aren't strictly necessary, just to make sure that you're positioned correctly on the line. The fewer assumptions ...

Get Learning GNU Emacs, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.