If you have a particularly repetitive text transformation, it's easy to record the commands with a macro and then just execute the macro several times. This is particularly good for things with several incremental steps, where just using query-replace-regexp would be more trouble than it's worth.
- C-x ( -- start recording macro
- C-x ) -- finish macro
- M-Return -- execute last macro (C-x e also works)
- C-u n C-x e: execute macro n times
Also useful are:
- M-x name-last-kbd-macro = give name to macro (for saving)
- M-x insert-kbd-macro = save named macro into file
- M-x load-file = load file and included macro definitions, if any
- M-x macroname = execute macroname
See EmacsWiki for more info.
Example
For my first few weeks here, my computer was rebooting every time it was left idle for greater than about twenty minutes (which apparently was due to a bad USB headset driver :( ). I just got used to going into the directory I was working in and re-opening all the relevant files in the morning and after lunch.
I (scovo) pulled up the directory (audrey) in dired, went to the first CM file, and then pressed
- C-x ( -- (start recording macro)
- enter -- (to open file)
- C-x b, enter -- (to switch back to dired from the file buffer)
- n -- (down one file)
- C-x ) -- (end-kbd-macro)
and then just hit C-u C-u C-u C-u C-x e to have it step down and open everything for me. Scovo 20:44, 10 October 2008 (UTC)
Tips
It's usually a good idea to anchor each execution of a macro to a consistent relative point, such as the beginning of a line or a regexp search result.
If you want to execute it several times, which is the point of a kbd macro, you can either type C-u number C-x e, just hit C-u several times (which starts with a count of 4 and then quadruples the count each successive time), or hit C-x e to execute it once, followed by C-x z (repeat) zzzzzzzzzzzzzzz... (keep repeating for each z). C-u 0 C-x e ("execute zero times") is a special case, meaning, "Keep executing this until there's an error or the end of the buffer is reached".
This is more straightforward than it sounds, and once you've got it in your fingers, you will find plenty of uses for it.
Comments
0 comments
Please sign in to leave a comment.