Emacs Macros and the Power-Macros Package

Writing Emacs macros doesn't have to be hard—Mr. Pedersen helps you get “more power”.

People sometimes tend to forget that computers are tools that can make their lives much easier. One of the things computers are especially good at, and which is easy to teach them is monotonous, repetitive work. It gets even better. This kind of work also seems to be the work humans are worst at doing; that is, monotonous, repetitive work tends to be very error-prone. Emacs can eliminate repetitive work with a very useful concept called macros. Macros are basically keystrokes that Emacs types for you.

This article will describe Emacs macros and show you a number of useful examples. Furthermore, it will discuss an Emacs package I have written called power-macros, which makes it very easy to bind macros to keys and save them to a file for use in later Emacs sessions.

Defining an Emacs Macro

Defining an Emacs macro is done by pressing CTRL-x (. That is, press CTRL, hold it down and press x, release both, then press the open parenthesis. The subsequent keystrokes will be part of your macro; that is, when you ask Emacs to execute your macro, these keystrokes will be typed for you. When you are done defining the macro, press CTRL-x ).

When a macro has been defined, you can ask Emacs to imitate your keystrokes as often as you want simply by pressing CTRL-x e.

Two Cent Tip

If you need to repeat a macro several times, it might be quite annoying to have to press two keys to execute it. A solution to this is to bind a command to “execute-last-defined-keyboard macro” to a single key press. For example, you could bind this command to SHIFT-F1 by inserting the following code into your .emacs file:

(global-set-key [(shift f1)] 'call-last-kbd-macro)
Example: Making the Current Word Bold

Those are the macro basics. I'm fairly sure you don't yet have the feeling this would change your world much, right? Therefore, here is a small example to whet your appetite. More will follow later.

Imagine that you often want to make the current word in boldface. In HTML documents, you could do that simply by inserting <b> and </b> around the word. That's no big job, but if you are copy-editing a book and need to make words in boldface hundreds of times each hour, a macro to do this can save you a lot of time.

The macro is easily recorded: press CTRL-x (, go to the beginning of the word, type <b>, go to the end of the word, type </b>, CTRL-x ), then press CTRL-x e at the beginning of each word you wish to bold in the document.

There is one very important point to notice about this: you are not allowed to go to the beginning or end of the word by pressing the arrow key a number of times! Why not? Well, if you do, the macro will fail to find the border of the word if your word is of a different length than the word used when defining the macro. You must instead use the commands forward-word and backward-word. These commands are bound to CTRL and the arrow keys. Thus, to go to the end of a word, simply press CTRL and the right-arrow key.

Basically, there are two kinds of macros: those used infrequently, and those used many times in a row and then never used again. The “make word bold” example is a macro of the first kind. The description of the second kind is outside the scope of this article, but one example could be a macro that added /* REMOVE: to the beginning of a line, and */ to the end of a line. You may use such a macro a number of times in a row to comment out a whole function in C for later removal.

Making Macros More General

In some C++ programs, you will often find constructs which resemble the following:

for (bool
...
}

The only difference from one occasion to the next is the set of names: cont, iterator, value and the content in between the curly brackets.

If you insert the above code often, you may wish to build a macro to help you with this. Your first attempt may be to define a macro, which simply inserts:

for (bool =.First(); ; =.Next()) {
}

That is, a macro that simply leaves out all the parts that may change from time to time. This is, however, not as useful as it could be, simply because you would need to type cont three times and iterator and value two times each. What you really would like is to have Emacs ask you which names to use. You can do that with macros. The trick is called “recursive editing”. With recursive editing, you can tell Emacs to stop at a specific place in the macro, do some editing, and when done, tell Emacs to continue with the macro.

When you record macros, you tell Emacs to enter recursive editing by pressing CRTL-u CTRL-x q. Then whenever you execute the macro, Emacs will stop macro execution at that point to let you do some editing, and then the macro will continue when you press CTRL-META-c. (If there is no META key on your keyboard, it is most likely the ALT key instead.)

While you record the macro, Emacs will also enter recursive editing at that point. That is, the editing you do from the point you press CTRL-u CTRL-x q until you press CTRL-META-c will not be part of the macro.

We are almost ready to develop a neat and useful macro, but first let's exercise what we've learned so far with a simple example. Type the following: CTRL-x ( Type a word ==> CTRL-u CTRL-x q.

Now type Hello World, and when done, continue typing the following: CTRL-META-CTRL <== CTRL-x )

The above inserted the following text into your buffer:

Type a word ==>Hello World<==
Furthermore, it also defined a macro, which inserts this text except for the words “Hello World”. Whenever you execute the just-defined macro, Emacs will pause after having inserted Type a word ==>, and when you press CTRL-META-c, it will continue with the macro, which means it will insert the text <==.

Can you see where we are heading? Now we have the tools to ask the user for the three names needed, so now all we need is a way to fetch the information he typed and insert it at the appropriate places.

Fetching the information could be done several ways. The simplest (that is, the one which requires the least knowledge of Emacs) would simply be to switch to a temporary buffer, let the user type in the information there, and whenever one of the words is needed, simply go to this buffer and fetch it there.

A much smarter way is to use registers. A register is a container where you may save the text of the current region for later use. To insert text into a register, mark a region and press CTRL-x r s and a letter (the letter indicates the register in which to save the information). Later, you may insert the contents of the register into the buffer by pressing CTRL-x r i and pressing the letter you typed above.

Listing 1

Listing 1 shows all the keystrokes needed to record this macro. Text in between quotes should be typed literally, and text in italics is comments, which should not be typed. It may seem like a lot of typing to obtain this, but on the other hand, when you are done, you will have a very user-friendly interface to inserting the given for-loops.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Scribbled notes

thomasn's picture

* To run a command stored by "C-x (", use "C-x e". To run it again, just tap "e".

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState