30

I saw this somewhere, but cannot find it now. Is there a built-in function in emacs, or does someone have elisp, to line up all the equals signs in a series of inititialization statments in cc-mode?

Before:

int t=9;
Graphics g = new Graphics();
List<String> list = new List<String>();

After:

int          t    = 9;
Graphics     g    = new Graphics();
List<String> list = new List<String>();
Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Cheeso
  • 189,189
  • 101
  • 473
  • 713

3 Answers3

46

Use M-x align-regexp (here, M-x align-regexp RET = RET). You can also add an "alignment rule" to the variable align-rules-list, so that in future M-x align will do it. See the documentation (C-h f align) for details.

ShreevatsaR
  • 38,402
  • 17
  • 102
  • 126
  • 1
    Ok, I've bound this to C-x |. How did I use emacs for so long and not know about this? Thanks for the help. – Cheeso May 27 '09 at 18:47
  • The only problem with this is that it "tabifies" the output, which is probably not what you want. Do you know any way to prevent this? – harpo Nov 14 '11 at 19:23
  • 1
    harpo: I've added a new answer for your question. – phils Nov 15 '11 at 00:15
  • This URL helped with making this into a fn: http://stackoverflow.com/questions/3633120/emacs-hotkey-to-align-equal-signs – Nathan Lippi Jul 01 '13 at 17:36
18

This is in response to harpo's comment to ShreevatsaR's answer:

The only problem with this is that it "tabifies" the output, which is probably not what you want. Do you know any way to prevent this?

Here's what I did to resolve that issue:

;; Align with spaces only
(defadvice align-regexp (around align-regexp-with-spaces)
  "Never use tabs for alignment."
  (let ((indent-tabs-mode nil))
    ad-do-it))
(ad-activate 'align-regexp)
phils
  • 71,335
  • 11
  • 153
  • 198
  • 1
    This is not a great answer to the original question, but valuable, valuable, valuable. (I think I just Ballmered.) – JasonFruit Apr 10 '12 at 05:22
  • It took me some time to understand what this [does](http://stackoverflow.com/questions/10921225/what-does-ad-activate-do)... – Michel de Ruiter Jun 06 '12 at 19:56
7

M-x align should do the trick.

Nathaniel Flath
  • 15,477
  • 19
  • 69
  • 94