Understanding align-regexp of Emacs

Emacs' M-x align-regex is neat when I want to align some similar text, especially when we're coding. I use its trivial version(without prefix arg) regularly on day-to-day programming work before.

For example, I can use it to align below code quickly by:

  1. Choose the region

  2. M-x align-regexp and type = and Enter

aaaaaaaaaaaaaa = fields[0]
bbb = fields[1]
cccccccc = fields[2]

It will be aligned to below code, now it's better to read:

aaaaaaaaaaaaaa = fields[0]
bbb            = fields[1]
cccccccc       = fields[2]

A few days ago, I found myself don't understand how it works when I read the code of smart-align, A simple align-regexp wrapper for easier usage. I was confused by the parameters, especially REGEXP and GROUP, and SPACING, here is its signature:

(align-regexp BEG END REGEXP &optional GROUP SPACING REPEAT)

As for REGEXP and GROUP, as in the above example, I think the regexp should be \(\s-*=\), so that group 1 will be aligned by prepending spaces. In fact, it resulted in removing the = for the first line, so I was wrong. The correct regex for it is \(\s-*\)=.

After reading a related thread 1 on Emacs' Stack Exchange for many times and practicing it along the way, I finally figured out, the key to understanding it is that it works by matching the specified group pattern, then appending it with whitespaces or removing extra whitespaces, so that the alignment character after it, = in this case, will be aligned.

As for the SPACING, it means how many spaces should be kept for the "densest" line, 1 will result in aaaaaaaaaaaaaa = fields[0], 2 will result in aaaaaaaaaaaaaa = fields[0], as so on.


See also

comments powered by Disqus