2

Say that you have the following JavaScript map literal

{a: 1,
 aoeu: 2}

and want the values aligned for readability like

{a:    1,
 aoeu: 2}

Is this possible to do with emacs? I'm currently using js2-mode and M-x align does nothing. M-x align-regexp can in some cases be used when the values all begin with the same prefix or like in this case when they're all numbers, but I've yet to find a generally applicable regexp.

  • Doesn't C-u M-x align-regexp with complex align regexp :\(\s-*\) and default args otherwise (i.e., 1st group for aligning and 1 space) do exactly that? – Tobias Nov 20 '17 at 11:00
  • Unfortunately not. Unless I've managed to miscopy your regexp it seems to have the following result: paste.debian.net/996677 – Rovanion Nov 20 '17 at 12:04
  • You did miss the prefix arg C-u which stands for Control-u. Press Control-u and afterwards Meta-x and input align-regexp enter... – Tobias Nov 20 '17 at 12:08
  • You are so right, thank you. But it is quite the command aint it? – Rovanion Nov 20 '17 at 12:57
  • It would be nice if you could test it with some of your more complicated cases. If it works for you I would write up an answer. – Tobias Nov 20 '17 at 13:10
2

align-regexp is called non-interactively like that:

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

The argument REGEXP of align-regexp is a regexp that should contain at least one group.

For alignment characters are deleted from the back of the substring matching the first group or whitespace is inserted at the back of that substring.

If you call align-regexp interactively without prefix argument the actual argument REGEXP results from prepending the user-input with the string \(\s-*\). The effect is that space is inserted and deleted before the alignment character given in the user-input.

That is not what you want. You actually want :\(\s-*\) as REGEXP.

If you call align-regexp with prefix argument C-u you can input all arguments (required and optional) of align-regexp literally. (BEG and END as beginning and end position of region).

I suggest you call C-u M-x align-regexp with complex align regexp :\(\s-*\) and default args otherwise (i.e., 1st group for aligning and 1 space) to get what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.