Mac – Using Emacs align-regexp to format tables

emacsvim

Vim has the neat Tabular plugin that allows you to quickly align some text. I use it a lot to align blocks of code along a certain character (mostly things like = and =>). But it also does a very good job at ad-hoc tables. Given something like

|Name|Rank|No.|
|Stan Ridgway|Private First Class|8797|
|John Rambo|Private|889897|
|George S. Patton|General|0879797|

it's easy to get it to end up like this:

| Name             | Rank                | No.     |
| Stan Ridgway     | Private First Class | 8797    |
| John Rambo       | Private             | 889897  |
| George S. Patton | General             | 0879797 |

Select it (or simply place the cursor on the first line), then execute :Tabularize /|.

As I'm currently trying to cross-pollinate Emacs and Vi a bit, stealing from both sides, looking for matching plugins, etc., I'd like to do the same in Emacs. Now, for the aforementioned =/=> stuff, align works very well, and even does most things pretty automagically.

And for the more complicated stuff, there's align-regexp. I would dare a guess that it's probably just the matter of getting the right regexp to feed to it (probably in the C-u prefixed extended version).

Any suggestions in this direction or other functions/packages?

Best Answer

Type M-x orgtbl-mode, then C-c C-c

| Name             | Rank                |     No. |
| Stan Ridgway     | Private First Class |    8797 |
| John Rambo       | Private             |  889897 |
| George S. Patton | General             | 0879797 |
Related Question