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.