Subject: Re: bug#385: [PATCH] comment-indent doesn't respect comment-indent-function

From: "Christopher J. Madsen" <[email-masked]>
Date: Wed, 2 Mar 2016 23:03:37 -0600

On 2/28/2016 10:59 PM, Lars Ingebrigtsen wrote:
> Is this still an issue in Emacs 25? 

Yes.  I built emacs-25.1.50.1 from 04289d1cd and nothing seems to have
changed.  The fundamental problem is that there's no way for a
comment-indent-function to say "Put the comment here, and I really mean
it."  In some situations, comment-indent will always second-guess the
comment-indent-function.  In particular, it insists on aligning the
comment with a comment on the line above even when that's not what I want.

To reproduce this, load this Perl code:

#! /usr/bin/perl

if (1) {
  if (2) {
    if (3) {
      4;
    } # end 3
  } # end 2
} # end 1

And set comment-indent-function to this function:

(defun cjm-perl-comment-indent ()
  (if (and (bolp) (not (eolp)))
      0                                 ;Existing comment at bol stays
there.
    (save-excursion
      ;; endcol is the minimum column number the comment can start at
      ;; and still leave one space after text already on the line
      (skip-chars-backward " \t")
      (let ((endcol (1+ (current-column))))
        (if (= 1 endcol)                ;Don't leave just one space
            (setq endcol 0))            ;at beginning of line
        (beginning-of-line)
        (cond
         ;; CASE 1: A comment following a solitary closing brace should
         ;; have only one space.
         ((looking-at "[ \t]*}[ \t]*\\($\\|#\\)")
          endcol)
         ;; CASE 2: Align with comment on previous line
         ;; unless that's more than 9 chars before comment-column,
         ;; and leave at least one space (unless starting at bol).
         ((and (= 0 (forward-line -1))
               (looking-at ".*[ \t]\\(#\\)")
               (progn
                 (goto-char (match-beginning 1))
                 (> 10 (- comment-column (current-column)))))
          (max (current-column) endcol))
         ;; CASE 3: indent at comment column except leave at least one
         ;; space (unless at bol)
         (t (max endcol comment-column))
         )))))

Put point on the "end 2" line, hit M-; and the comment will be moved to
align with the "end 3 " comment instead of staying where it was.  Repeat
on the "end 1" line and you'll have

    } # end 3
  }   # end 2
}     # end 1

instead of the original code.

(You don't actually need a comment-indent-function this complex to
reproduce the issue, but this is the actual function I use.)

Sorry for the delay in getting back to you.

-- 
Chris Madsen                                           [email-masked]
  --------------------  http://www.cjmweb.net  --------------------