Thursday, July 9, 2009

Emacs Example Tutorial: replace words text with a regexp

In Emacs' normal find-and-replace mode you can't replace special characters like "beginning of line" or "end of line" with anything because it treats the special characters representing end of line (^ and $, respectively) as regular characters - a literal ^ and a literal $.

If you want to replace the beginning of line or end of line with another string (and this can come in extremely handy some times) you have to use a different kind of replace: RegExp replace (regexp stands for the term regular expression, which is a phrase used to describe computer pattern matching code or directions. Think "filters"). To get Emacs into this mode type:

M-x replace-regexp

Remember, M is the meta key, which is usually equal to holding down the alt key or tapping on the escape key. So you can think of this as:

ALT x

Emacs will prompt you that it is waiting for more instructions by displaying "M-x". Then you type in:

replace-regexp

and hit enter. Emacs will now ask you "Replace regexp: " - it is waiting to know the regular expression that matches the characters you want to replace.

So let's say you have a file of information - a list of names of employees, for example. This hypothetical list contains nothing but their names. Let's say you want to add a note at the end of the line that reads "Note: give this employee a new mouse pad:."

While emacs is sitting there asking you "Replace regexp: " type in just the dollar sign and then hit enter: $

Now Emacs will ask you "Replace regexp $ with: "

You can now type in any text you want, and then hit enter - Emacs will append that text to the end of the line. Unlike the regular find-and-replace, replace-regexp does not ask you for confirmation one line at a time, it will simply apply this "replacement" to every line of the file at the end-of-line mark.

As a very cool side benefit, you can combine this with block editing mode to constrain the replacement to a fixed block of lines. For more on block editing mode and how to define a block, see this article on emacs block editing.

No comments: