Emacs: Align Text

By Xah Lee. Date: . Last updated: .

Emacs has several commands that's helpful for alignment. One of the most useful is align-regexp. For example, suppose you have:

tom = 5
jenny = 8
mary = 7

and you want to align them by the equal sign. Just select the text, then call align-regexp then give “=”. Then you get:

tom   = 5
jenny = 8
mary  = 7

The following is more advanced use of align and sort commands.

Problem

You have this list:

California 423,970 km²
Taiwan 36,008 km²
Japan 377,944 km²
Germany 357,021 km²
Iraq 438,317 km²
Iran 1,648,195 km²
Korea (North+South) 219,140 km²
Mexico 1,964,375 km²

change it to this form:

Taiwan                 36,008 km²
Korea (North+South)   219,140 km²
Japan                 377,944 km²
Germany               357,021 km²
California            423,970 km²
Iraq                  438,317 km²
Iran                1,648,195 km²
Mexico              1,964,375 km²

Solution

Jon Snader and “jm”, provided the following solution.

align-regexp

First, we align the text. Select the text first, then press 【Ctrl+u】 then call align-regexp, with the regexp .* \([0-9,]+\).* then choose -1 for group, 1 for spacing, and n for repeat.

Here's what it means. align-regexp lets you align a region by a regex in complex ways.

The result is this:

California             423,970 km²
Taiwan                  36,008 km²
Japan                  377,944 km²
Germany                357,021 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Korea (North+South)    219,140 km²
Mexico               1,964,375 km²

sort-regexp-fields, sort-columns

To sort it, there are 2 methods. One is using sort-regexp-fields, with this regex ^.*\([0-9 ,]\{9\}\) km²$.

Another method is simply use sort-columns. This command sort lines by using a vertical column of text as sort key. The column is specified by the position of mark and cursor. So, place the cursor at the upper right, mark it, then move to lower left of our number, like this:

California             423,970 km²▮
Taiwan                  36,008 km²
Japan                  377,944 km²
Germany                357,021 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Korea (North+South)    219,140 km²
Mexico              ▮1,964,375 km²

Then call sort-columns. We got our desired result:

Taiwan                  36,008 km²
Korea (North+South)    219,140 km²
Japan                  377,944 km²
Germany                357,021 km²
California             423,970 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Mexico               1,964,375 km²

All these commands: {align-regexp, sort-regexp-fields, sort-columns} will be quite useful when you need it. (Big thanks to Jon Snader and “jm” for the excellent solutions.)

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs