Emacs: Align Text Column

By Xah Lee. Date: . Last updated: .

Align Text

Alt+x align-regexp to align text.

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 Alt+x 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²

you want to align the numbers, and sort the lines, like this:

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

  1. First, we align the text.
  2. Select the text first, then press Ctrl+u then Alt+x align-regexp
  3. give the regexp .* \([0-9,]+\).*
  4. then choose -1 for group
  5. 1 for spacing
  6. 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 by Column

2011-11-02 Big thanks to Jon Snader and “jm” for the excellent solutions.

Emacs, Comment, Uncomment, Rectangle Edit

Emacs, Work on Lines