ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial

Emacs Keyboard Macro Example: Adding HTML Attribute

,

This page shows a real world example of emacs keyboard macro use. If you are not familiar with keyboard macro, see: Emacs Keyboard Macro Examples.

Problem Description

I have a HTML page of Printed References On Plane Curves. In that page, there are a list of 34 books with this HTML format:

<span class="title">Geometry: Euclid and Beyond</span>
<a class="amz" href="http://www.amazon.com/dp/0387986502/?tag=abc-20">amazon</a>

I need the amazon link to contain a “title” attribute. Like this:

<span class="title">Geometry: Euclid and Beyond</span>
<a class="amz" href="http://www.amazon.com/dp/0387986502/?tag=abc-20" title="Geometry: Euclid and Beyond">amazon</a>

To manually fix this, i use isearch to find a amazon link, then search backward looking for the class="title"> to find the title of the book. Move cursor into the markup to copy the title. Search forward to the amazon link again, type title=" then paste, then type ". But i need to do this 34 times?

Solution

Emacs keyboard macro came to rescue me!

Here are exact steps of the keyboard macro:

Then, i move cursor to the top of page, then press 【Ctrl+x e】 to run my kmacro. Each time i do this, one link is fixed. About 30 keystrokes is reduced to just 2 key strokes. I can run my kmacro once for every link to fix, a total of 34 times, or, i can just press 【Ctrl+u 34】 then 【Ctrl+x e】, fixing all links in one shot.

In this case, i actually did it one by one, instead of one-shot, because, often i do not know that the page necessarily have a uniform format. So, doing it one at a time lets me eyeball the change.

This is the beauty of emacs, where everything is interactive. When you work with computer language source code, or sys admin scripts, the texts are almost never in some uniform format. With emacs, you edit the text as usual, but as soon as you see a pattern, you can start a keyboard macro, or even write a simple elisp command, that lets you automate all possible mechanical steps. When you find the format changes, you can manually fix some irregularity, or just start a new keyboard macro when you see a new pattern. See: Why Emacs is Still so Useful Today and Emacs Lisp Power: Text-Soup Automation.

blog comments powered by Disqus