4

I have a bunch of single line comment blocks in C-code that I want to change to multiline. Example:

// foo
// bar

should become:

/* foo
 * bar
 */

How can I do this easily in Emacs?

Arne
  • 409
  • 3
  • 12

1 Answers1

1

Try this:

(defun ph/switch-inline-c-comments-to-block (beg end)
  "Change whole-line inline C comments between BEG and END to block comments.

If the region contains any lines which are not whole-line inline C comments
then the behavior of this command is undefined."
  (interactive "*r")
  (narrow-to-region beg end)
  (unwind-protect
      (let ((whole-line-inline-comment "^[[:space:]]*//\\(.*\\)$"))
        (goto-char (point-min))
        (replace-regexp whole-line-inline-comment "/*\\1" nil (point)
                        (line-end-position))
        (forward-line)
        (replace-regexp whole-line-inline-comment " *\\1")
        (when (eolp)
          (open-line 1)
          (forward-line))
        (insert " */"))
    (widen)))

To use it, first evaluate the defun, then mark the sequence of whole-line inline comments you want to change to a K&R-style comment and execute M-x ph/switch-inline-c-comments-to-block RET (or bind it to a key of your choice).

Phil Hudson
  • 1,651
  • 10
  • 13