I have C comments like this:

 *                   Includes                                                 *

I want to be able to center within the *'s like this:

 *                                  Includes                                  *

I've been unable to do this. If I try M-x narrow-to-region and use M-x center-line, it deletes all the spaces on the right hand side instead of preserving them. Using M-x picture-mode does not improve matters. I tried moving to the fill column using M-x move-to-column hoping it would fill in the spaces, but it stops at the current length in both picture and non-picture mode.

  • There's rebox which looks quite powerful. 8 years old, so handle with care. There's rebox2 in melpa. – Juancho Jun 30 '20 at 16:38
  • @Juancho does Rebox have any documentation? It looks like you have to set a numeric style for comments, and it's some number, but I can't find the number assignments. I played around it with but couldn't get it to work. – eewanco Jul 7 '20 at 13:23

I never found what I was looking for, so I ended up hacking the center-line elisp code like so:

(defun c-center-comment (&optional nlines)
  "Center the boxed comment point is on, within the width specified by `fill-column'.
This means adjusting the space around the comment enclosed by asterisks (*) so that it equals
the distance between the end of the text and `fill-column'.
The argument NLINES says how many lines to center."
  (interactive "P")
  (if nlines (setq nlines (prefix-numeric-value nlines)))
  (while (not (eq nlines 0))
      (let ((lm (current-left-margin))
        (delete-char 1)
        (forward-char -1)
        (delete-char 1)
    (setq line-length (current-column))
    (if (> (- fill-column lm line-length) 0)
        (progn (indent-line-to
                 (+ lm (/ (- (- fill-column 1) lm line-length) 2)))
              (if (< (% (- (- fill-column 1) lm line-length) 2) 1)
                    (delete-char 1))
              (insert-char ?\*)
              (insert-char ?\ (+ lm (/ (- (- fill-column 1) lm line-length) 2)))
              (insert-char ?\*)))))
    (cond ((null nlines)
       (setq nlines 0))
      ((> nlines 0)
       (setq nlines (1- nlines))
       (forward-line 1))
      ((< nlines 0)
       (setq nlines (1+ nlines))
       (forward-line -1)))))

Note that this is very primitive. It assumes the line already starts and ends with an asterisk (change the insert-char commands to modify the character). If you want to center a new line, surround it with any sacrificial character, but I only wrote this for fixing existing comments, not for composing new ones.

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.