modeller
modeller

Reputation: 3850

How to nicely format header comments in C++ mode of emacs?

Here the "header comments" refers to:

/* Program Name: Foo                */
/* Author:       Jane Doe           */
/* Date:         06/29/2014         */
/* Rev:          1.0                */

The tricky parts are:

  1. Hard to align the ending */ in each line if to use M-;
  2. If possible, I'd like to align the content after : in each line.

Thanks in advance.

Upvotes: 0

Views: 424

Answers (1)

Chris
Chris

Reputation: 137070

You can do this with two invocations of align-regexp, though it's a bit tricky to type:

/* Program Name: Foo */
/* Author: Jane Doe */
/* Date: 06/29/2014 */
/* Rev: 1.0 */

Select the region you wish to modify, then do your first align-regexp with a prefix argument:

C-u M-x align-regexp RET :\(\s-*\) RET RET RET n

This version of align-regexp uses a regular expression matching the colon character, followed by any amount of whitespace. Then we

  • accept the default option of modifying capture group 1 (the whitespace),
  • then the default of leaving at least one space when we adjust,
  • then tell Emacs not to repeat for the whole line, as we don't need that feature.

This should leave you with

/* Program Name: Foo */
/* Author:       Jane Doe */
/* Date:         06/29/2014 */
/* Rev:          1.0 */

Now, C-x C-x to swap point and mark, reselecting your text, and do another align-regexp. This one doesn't need a prefix argument:

 M-x align-regexp RET \*/ RET

This version is much simpler. We provide a regular expression that matches the close comment indicator */, escaping the asterisk.

And you should be done! The final result looks like this:

/* Program Name: Foo        */
/* Author:       Jane Doe   */
/* Date:         06/29/2014 */
/* Rev:          1.0        */

Edit:

You should be able to write a function to automate this process. I'm no elisp expert, but this seems to do the trick:

(defun my-align-c-comment-block ()
  (interactive)
  (when (use-region-p)
    (align-regexp (region-beginning) (region-end) ":\\(\\s-*\\)")
    (exchange-point-and-mark)
    (align-regexp (region-beginning) (region-end) "\\(\\s-*\\)\\*/")))

Upvotes: 3

Related Questions