Ads by Google

Monday, July 7, 2008

Learning to use the Emacs keyboard macro system effectively

The Emacs macro system is probably the least used feature by newbies and intermediate users. Which is a shame as it's a really neat piece of code and the learning overhead is very small.

The latest versions of Emacs has the keys F3 and F4 mapped to start and end of the macro recording. And the next invocation of F4, runs the last created macro.

Recording a macro is easy. Hit F3 and start working. Of course, the idea of a macro is to do repetitive tasks and one needs to record the steps and apply it to the buffer text.

Here's where it is important to get things right.

One,don't worry about efficiency or the least number of keystrokes to achieve the task. Most times, the macros are one off and will rarely be suitable for another task later in the day or week. I've rarely had the chance to reuse any of the macros I've written. And every piece of "similar" text you receive, the odds are better that you do the macro from scratch again.

Second, use the emacs provided line commands instead of counting words, letters and spaces. Your macro is more robust if it is recorded in emacs contextual fragments i.e



Counting characters instead of using Emacs word boundary definition will lead you astray. Your macro will work for some cases and break in case of the others.

Three, once you get the hang of this, you can edit the macro by M-x edit-last-kbd-macro and delete/add additional corrections you want, and make it available by hitting C-c C-c to recompile the macro.

Try it on a couple of lines of text by hitting F4 and see where the point ends. That typically will tell you what happens if the results are not what you expected when you run the macro. You might have to add a C-n or C-j to move or create a newline.

Once you get the hang of simple macros, you can then move on to more difficult versions of the same. I've once used macros to copy stuff across 2 buffers back and forth. The more you use macros, the more natural it will be to use it for any and every repetitive tasks.

You'll find it really useful when editing UNIX shell scripts, data files and configuration files


Anonymous said...

Thanks for this!

I use emacs a whole whole lot and I know about macros, but I haven't gotten around to using them like I should. What a helpful post to remind me how important they are :)

Unknown said...

Here's another cool thing about keyboard macros I just found out last week: if you give f4 (or C-x e, which it used to be) a prefix argument of zero (M-0 f4) Emacs will repeat the last macro until an error occurs.

Unknown said...

hi i have mandriva linux and i dont know hot to run emacs in this linus.every time i write this code(emacs file.txt) it sasys that emacs command not found...can u help