1

I'm looking for a way in emacs to format a code like this:

// param1, param2, param3, param4
foo(9, 8, "bar", 3)

to this:

//  param1, param2, param3, param4
foo(9,      8,      "bar",  3)

I guess it should be feasible with align-regexp but I have troubles to express the regexp to use in this case (actually I don't really understand what the regexp is supposed to match). Any idea?

2

With indent-tabs-mode set to nil1, the following will do most of that:

C-uM-x align-regexp RET ,\(\s-*\) RET RET y

Dealing with the initial parameter is decidedly trickier. If you can guarantee the presence of a space after each comma, then you could use the following regexp along with 0 for the "Amount of spacing" question:

\(?:, \|^\(?://\|.*?(\)\)\(\s-*\)

You may prefer to use a two-step process, though. e.g.:

  • ^\(?://\|.*?(\)\(\s-*\) with spacing = 0, and not repeating; followed by
  • ,\(\s-*\) with spacing = 1, and repeating

You should probably elaborate on the kind of workflow you're looking for, though. Are you looking for a command to call manually? Automated alignment rules? Something to use occasionally via a keyboard macro? Other?


1 I would recommend using the following in general:

;; 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)
  • Thanks for your answer @phils. Actually I usually need this in a very specific case where I want to initialize some large chunk of data in unit tests with a function that takes many parameters: having comments and parameters aligned helps a lot for readability. – dlgd Jun 10 '17 at 20:57

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.