Tips for Creating Good Macros
Tips for Creating Good Macros
It’s easy to learn how to record and reuse your keystrokes. However, if you’re a typical new user, you’ll make a few mistakes: you’ll create a macro, use it, and then find out that it didn’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 are ones that work in all the situations that you want them to. 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 ESC 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 defined the macro and the time you executed 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 ...
Get Learning GNU Emacs, Second 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.