# Aligning Text With Regular Expressions in Emacs

This is really a note to myself. A while ago I ran across this post over at RAW SYNTAX about the Emacs command align-regexp. I don't require this functionality very often but when I do, align-regexp is just what I need. Unfortunately, I keep forgetting about it so I'm writing this post in the hopes that it will help me remember (or at least give me a place to find the name of the function)

The simplest, and probably most common, use case is to align on a particular character. The canonical example is a telephone number list. We just mark the region to align, type 【Meta+xalign-regexp, and then ( when prompted for the regular expression

# Original list

Joe (555) 111-2222
Mary  (555) 222-1212
Alexandra 123-4567
Francis (555) 333-2121

# After align-regexp

Joe     (555) 111-2222
Mary    (555) 222-1212
Alexandra 123-4567
Francis (555) 333-2121


That's not quite what we want, though, because Alexandra's number doesn't have an area code so there is no open parenthesis to align on. To fix this, we have to use the more complicated version of align-regexp by giving the invocation a prefix arg: 【Ctrl+u Meta+xalign-regexp. This time we specify .+?$+$.+ as the regular expression, choose 1 as the group to modify, 1 as the amount of spacing, and no as to whether we should repeat the rule throughout the line. The result is:

Joe       (555) 111-2222
Mary      (555) 222-1212
Alexandra 123-456
Francis   (555) 333-2121


That's better but what we really want is to align on the -. If we do that directly using the simple case, we get

Joe (555) 111     -2222
Mary  (555) 222   -1212
Alexandra 123     -4567
Francis (555) 333 -2121


which is definitely not what we want. Instead we use the regular expression .+? +$.*$ and specify -1 as the group to modify or justify. That gives us

Joe        (555) 111-2222
Mary       (555) 222-1212
Alexandra        123-4567
Francis    (555) 333-2121


which is just what we want.

Update: lower case the key sequences.

Update 2: prefix tag → prefix arg

This entry was posted in General and tagged . Bookmark the permalink.

### 2 Responses to Aligning Text With Regular Expressions in Emacs

1. Sue D. Nymme says:

\$latex? Is that some sort of unwanted auto-substitution?

• jcs says:

Yup. I had a $in that comment to avoid messing up the syntax highlighting. That worked OK but Org mode uses$ to indicate LaTeX code. I hunted around in the Org export code and figured out how to turn it off. I don't remember the details but I can look them up if you're interested.