*** empty log message ***
[bpt/emacs.git] / lisp / newcomment.el
index f67e81b..9194350 100644 (file)
@@ -1,11 +1,10 @@
 ;;; newcomment.el --- (un)comment regions of buffers
 
-;; Copyright (C) 1999, 2000  Free Software Foundation Inc.
+;; Copyright (C) 1999,2000,2003  Free Software Foundation Inc.
 
 ;; Author: code extracted from Emacs-20's simple.el
 ;; Maintainer: Stefan Monnier <monnier@cs.yale.edu>
 ;; Keywords: comment uncomment
-;; Revision: $Id: newcomment.el,v 1.28 2000/12/11 21:41:35 monnier Exp $
 
 ;; This file is part of GNU Emacs.
 
 
 ;;; Bugs:
 
+;; - boxed comments in Perl are not properly uncommented because they are
+;;   uncommented one-line at a time.
+;; - nested comments in sgml-mode are not properly quoted.
 ;; - single-char nestable comment-start can only do the "\\s<+" stuff
 ;;   if the corresponding closing marker happens to be right.
-;; - comment-box in TeXinfo generate bogus comments @ccccc@
 ;; - uncomment-region with a numeric argument can render multichar
 ;;   comment markers invalid.
 ;; - comment-indent or comment-region when called inside a comment
 
 ;;; Todo:
 
-;; - try to align tail comments
-;; - check what c-comment-line-break-function has to say
-;; - spill auto-fill of comments onto the end of the next line
+;; - rebox.el-style refill.
+;; - quantized steps in comment-alignment.
+;; - try to align tail comments.
+;; - check what c-comment-line-break-function has to say.
+;; - spill auto-fill of comments onto the end of the next line.
 ;; - uncomment-region with a consp (for blocks) or somehow make the
-;;   deletion of continuation markers less dangerous
-;; - drop block-comment-<foo> unless it's really used
-;; - uncomment-region on a subpart of a comment
-;; - support gnu-style "multi-line with space in continue"
+;;   deletion of continuation markers less dangerous.
+;; - drop block-comment-<foo> unless it's really used.
+;; - uncomment-region on a subpart of a comment.
+;; - support gnu-style "multi-line with space in continue".
 ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
 ;;   is not turned on.
 
 ;;;###autoload
 (defalias 'indent-new-comment-line 'comment-indent-new-line)
 
-;;;###autoload
 (defgroup comment nil
   "Indenting and filling of comments."
   :prefix "comment-"
   :version "21.1"
   :group 'fill)
 
+;; Autoload this to avoid warnings, since some major modes define it.
+;;;###autoload
 (defvar comment-use-syntax 'undecided
   "Non-nil if syntax-tables can be used instead of regexps.
 Can also be `undecided' which means that a somewhat expensive test will
@@ -84,14 +88,18 @@ be used to try to determine whether syntax-tables should be trusted
 to understand comments or not in the given buffer.
 Major modes should set this variable.")
 
+(defcustom comment-fill-column nil
+  "Column to use for `comment-indent'.  If nil, use `fill-column' instead."
+  :type '(choice (const nil) integer))
+
 ;;;###autoload
 (defcustom comment-column 32
   "*Column to indent right-margin comments to.
-Setting this variable automatically makes it local to the current buffer.
 Each mode establishes a different default value for this variable; you
-can set the value for a particular mode using that mode's hook."
-  :type 'integer
-  :group 'comment)
+can set the value for a particular mode using that mode's hook.
+Comments might be indented to a value smaller than this in order
+not to go beyond `comment-fill-column'."
+  :type 'integer)
 (make-variable-buffer-local 'comment-column)
 
 ;;;###autoload
@@ -121,6 +129,31 @@ the comment's starting delimiter and should return either the desired
 column indentation or nil.
 If nil is returned, indentation is delegated to `indent-according-to-mode'.")
 
+;;;###autoload
+(defvar comment-insert-comment-function nil
+  "Function to insert a comment when a line doesn't contain one.
+The function has no args.
+
+Applicable at least in modes for languages like fixed-format Fortran where
+comments always start in column zero.")
+
+(defvar comment-region-function nil
+  "Function to comment a region.
+Its args are the same as those of `comment-region', but BEG and END are
+guaranteed to be correctly ordered.  It is called within `save-excursion'.
+
+Applicable at least in modes for languages like fixed-format Fortran where
+comments always start in column zero.")
+
+(defvar uncomment-region-function nil
+  "Function to uncomment a region.
+Its args are the same as those of `uncomment-region', but BEG and END are
+guaranteed to be correctly ordered.  It is called within `save-excursion'.
+
+Applicable at least in modes for languages like fixed-format Fortran where
+comments always start in column zero.")
+
+;; ?? never set
 (defvar block-comment-start nil)
 (defvar block-comment-end nil)
 
@@ -166,7 +199,6 @@ INDENT specifies that the `comment-start' markers should not be put at the
 (defcustom comment-style 'plain
   "*Style to be used for `comment-region'.
 See `comment-styles' for a list of available styles."
-  :group 'comment
   :type (if (boundp 'comment-styles)
            `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles))
          'symbol))
@@ -178,14 +210,23 @@ Can also be an integer which will be automatically turned into a string
 of the corresponding number of spaces.
 
 Extra spacing between the comment characters and the comment text
-makes the comment easier to read.  Default is 1.  nil means 0.")
+makes the comment easier to read.  Default is 1.  nil means 0."
+  :type '(choice string integer (const nil)))
 
 ;;;###autoload
 (defcustom comment-multi-line nil
   "*Non-nil means \\[comment-indent-new-line] continues comments, with no new terminator or starter.
 This is obsolete because you might as well use \\[newline-and-indent]."
-  :type 'boolean
-  :group 'comment)
+  :type 'boolean)
+
+(defcustom comment-empty-lines nil
+  "If nil, `comment-region' does not comment out empty lines.
+If t, it always comments out empty lines.
+if `eol' it only comments out empty lines if comments are
+terminated by the end of line (i.e. `comment-end' is empty)."
+  :type '(choice (const :tag "Never" nil)
+         (const :tag "Always" t)
+         (const :tag "EOl-terminated" 'eol)))
 
 ;;;;
 ;;;; Helpers
@@ -202,8 +243,16 @@ This is obsolete because you might as well use \\[newline-and-indent]."
   "Return the mirror image of string S, without any trailing space."
   (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
 
+;;;###autoload
 (defun comment-normalize-vars (&optional noerror)
-  (if (not comment-start) (or noerror (error "No comment syntax is defined"))
+  "Check and setup the variables needed by other commenting functions.
+Functions autoloaded from newcomment.el, being entry points, should call
+this function before any other, so the rest of the code can assume that
+the variables are properly set."
+  (unless (and (not comment-start) noerror)
+    (unless comment-start
+      (set (make-local-variable 'comment-start)
+          (read-string "No comment syntax is defined.  Use: ")))
     ;; comment-use-syntax
     (when (eq comment-use-syntax 'undecided)
       (set (make-local-variable 'comment-use-syntax)
@@ -218,6 +267,7 @@ This is obsolete because you might as well use \\[newline-and-indent]."
               (goto-char (point-min))
               (and (forward-comment 1) (eobp))))))
     ;; comment-padding
+    (unless comment-padding (setq comment-padding 0))
     (when (integerp comment-padding)
       (setq comment-padding (make-string comment-padding ? )))
     ;; comment markers
@@ -227,23 +277,35 @@ This is obsolete because you might as well use \\[newline-and-indent]."
     (unless (or comment-continue (string= comment-end ""))
       (set (make-local-variable 'comment-continue)
           (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
-                  (substring comment-start 1))))
+                  (substring comment-start 1)))
+      ;; Hasn't been necessary yet.
+      ;; (unless (string-match comment-start-skip comment-continue)
+      ;;       (kill-local-variable 'comment-continue))
+      )
     ;; comment-skip regexps
-    (unless comment-start-skip
+    (unless (and comment-start-skip
+                ;; In case comment-start has changed since last time.
+                (string-match comment-start-skip comment-start))
       (set (make-local-variable 'comment-start-skip)
-          (concat "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
+          (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
                   (regexp-quote (comment-string-strip comment-start t t))
-                  "+\\)\\s-*")))
-    (unless comment-end-skip
+                  ;; Let's not allow any \s- but only [ \t] since \n
+                  ;; might be both a comment-end marker and \s-.
+                  "+\\)[ \t]*")))
+    (unless (and comment-end-skip
+                ;; In case comment-end has changed since last time.
+                (string-match comment-end-skip comment-end))
       (let ((ce (if (string= "" comment-end) "\n"
                  (comment-string-strip comment-end t t))))
        (set (make-local-variable 'comment-end-skip)
-            (concat "\\s-*\\(\\s>" (if comment-quote-nested "" "+")
+            ;; We use [ \t] rather than \s- because we don't want to
+            ;; remove ^L in C mode when uncommenting.
+            (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
                     "\\|" (regexp-quote (substring ce 0 1))
                     (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
                     (regexp-quote (substring ce 1))
                     "\\)"))))))
+
 (defun comment-quote-re (str unp)
   (concat (regexp-quote (substring str 0 1))
          "\\\\" (if unp "+" "*")
@@ -346,15 +408,30 @@ and raises an error or returns nil of NOERROR is non-nil."
   "Find the beginning of the enclosing comment.
 Returns nil if not inside a comment, else moves point and returns
 the same as `comment-search-forward'."
-  (let ((pt (point))
-       (cs (comment-search-backward nil t)))
-    (when cs
-      (if (save-excursion
-           (goto-char cs)
-           (if (comment-forward 1) (> (point) pt) (eobp)))
-         cs
-       (goto-char pt)
-       nil))))
+  ;; HACK ATTACK!
+  ;; We should really test `in-string-p' but that can be expensive.
+  (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
+    (let ((pt (point))
+         (cs (comment-search-backward nil t)))
+      (when cs
+       (if (save-excursion
+             (goto-char cs)
+             (and
+              ;; For modes where comment-start and comment-end are the same,
+              ;; the search above may have found a `ce' rather than a `cs'.
+              (or (not (looking-at comment-end-skip))
+                  ;; Maybe font-lock knows that it's a `cs'?
+                  (eq (get-text-property (match-end 0) 'face)
+                      'font-lock-comment-face)
+                  (unless (eq (get-text-property (point) 'face)
+                              'font-lock-comment-face)
+                    ;; Let's assume it's a `cs' if we're on the same line.
+                    (>= (line-end-position) pt)))
+              ;; Make sure that PT is not past the end of the comment.
+              (if (comment-forward 1) (> (point) pt) (eobp))))
+           cs
+         (goto-char pt)
+         nil)))))
 
 (defun comment-forward (&optional n)
   "Skip forward over N comments.
@@ -364,10 +441,11 @@ and can use regexps instead of syntax."
   (if (< n 0) (error "No comment-backward")
     (if comment-use-syntax (forward-comment n)
       (while (> n 0)
-       (skip-syntax-forward " ")
        (setq n
-             (if (and (looking-at comment-start-skip)
-                      (re-search-forward comment-end-skip nil 'move))
+             (if (or (forward-comment 1)
+                     (and (looking-at comment-start-skip)
+                          (goto-char (match-end 0))
+                          (re-search-forward comment-end-skip nil 'move)))
                  (1- n) -1)))
       (= n 0))))
 
@@ -407,8 +485,8 @@ Point is assumed to be just at the end of a comment."
 
 ;;;###autoload
 (defun comment-indent (&optional continue)
-  "Indent this line's comment to comment column, or insert an empty comment.
-If CONTINUE is non-nil, use the `comment-continuation' markers if any."
+  "Indent this line's comment to `comment-column', or insert an empty comment.
+If CONTINUE is non-nil, use the `comment-continue' markers if any."
   (interactive "*")
   (comment-normalize-vars)
   (let* ((empty (save-excursion (beginning-of-line)
@@ -423,33 +501,76 @@ If CONTINUE is non-nil, use the `comment-continuation' markers if any."
           (begpos (comment-search-forward eolpos t))
           cpos indent)
       ;; An existing comment?
-      (if begpos (setq cpos (point-marker))
+      (if begpos
+         (progn
+           (if (and (not (looking-at "[\t\n ]"))
+                    (looking-at comment-end-skip))
+               ;; The comment is empty and we have skipped all its space
+               ;; and landed right before the comment-ender:
+               ;; Go back to the middle of the space.
+               (forward-char (/ (skip-chars-backward " \t") -2)))
+           (setq cpos (point-marker)))
          ;; If none, insert one.
+       (if comment-insert-comment-function
+           (funcall comment-insert-comment-function)
          (save-excursion
-           ;; Some comment-indent-function insist on not moving comments that
-           ;; are in column 0, so we insert a space to avoid this special case
-           (insert " ")
+           ;; Some `comment-indent-function's insist on not moving
+           ;; comments that are in column 0, so we first go to the
+           ;; likely target column.
+           (indent-to comment-column)
+           ;; Ensure there's a space before the comment for things
+           ;; like sh where it matters (as well as being neater).
+           (unless (memq (char-before) '(nil ?\n ?\t ?\ ))
+             (insert ?\ ))
            (setq begpos (point))
            (insert starter)
            (setq cpos (point-marker))
-           (insert ender)))
+           (insert ender))))
       (goto-char begpos)
       ;; Compute desired indent.
       (setq indent (save-excursion (funcall comment-indent-function)))
+      ;; If `indent' is nil and there's code before the comment, we can't
+      ;; use `indent-according-to-mode', so we default to comment-column.
+      (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
+       (setq indent comment-column))
       (if (not indent)
-         ;; comment-indent-function refuses delegates to indent.
+         ;; comment-indent-function refuses: delegate to line-indent.
          (indent-according-to-mode)
-       ;; Avoid moving comments past the fill-column.
-       (setq indent
-             (min indent
-                  (+ (current-column)
-                     (- fill-column
-                        (save-excursion (end-of-line) (current-column))))))
-       (if (= (current-column) indent)
-           (goto-char begpos)
+       ;; If the comment is at the left of code, adjust the indentation.
+       (unless (save-excursion (skip-chars-backward " \t") (bolp))
+         ;; Avoid moving comments past the fill-column.
+         (let ((max (+ (current-column)
+                       (- (or comment-fill-column fill-column)
+                          (save-excursion (end-of-line) (current-column))))))
+           (if (<= max indent)
+               (setq indent max)       ;Don't move past the fill column.
+             ;; We can choose anywhere between indent..max.
+             ;; Let's try to align to a comment on the previous line.
+             (let ((other nil)
+                   (min (max indent
+                             (save-excursion (skip-chars-backward " \t")
+                                             (1+ (current-column))))))
+               (save-excursion
+                 (when (and (zerop (forward-line -1))
+                            (setq other (comment-search-forward
+                                        (line-end-position) t)))
+                   (goto-char other) (setq other (current-column))))
+               (if (and other (<= other max) (>= other min))
+                   ;; There is a comment and it's in the range: bingo.
+                   (setq indent other)
+                 ;; Let's try to align to a comment on the next line, then.
+                 (let ((other nil))
+                   (save-excursion
+                     (when (and (zerop (forward-line 1))
+                                (setq other (comment-search-forward
+                                            (line-end-position) t)))
+                       (goto-char other) (setq other (current-column))))
+                   (if (and other (<= other max) (> other min))
+                       ;; There is a comment and it's in the range: bingo.
+                       (setq indent other))))))))
+       (unless (= (current-column) indent)
          ;; If that's different from current, change it.
-         (skip-chars-backward " \t")
-         (delete-region (point) begpos)
+         (delete-region (point) (progn (skip-chars-backward " \t") (point)))
          (indent-to (if (bolp) indent
                       (max indent (1+ (current-column)))))))
       (goto-char cpos)
@@ -466,6 +587,7 @@ With any other arg, set comment column to indentation of the previous comment
   (cond
    ((eq arg '-) (comment-kill nil))
    (arg
+    (comment-normalize-vars)
     (save-excursion
       (beginning-of-line)
       (comment-search-backward)
@@ -482,6 +604,7 @@ With any other arg, set comment column to indentation of the previous comment
   "Kill the comment on this line, if any.
 With prefix ARG, kill comments on that many lines starting with this one."
   (interactive "P")
+  (comment-normalize-vars)
   (dotimes (_ (prefix-numeric-value arg))
     (save-excursion
       (beginning-of-line)
@@ -570,83 +693,132 @@ If N is `re', a regexp is returned instead, that would match
 
 ;;;###autoload
 (defun uncomment-region (beg end &optional arg)
-  "Uncomment each line in the BEG..END region.
+  "Uncomment each line in the BEG .. END region.
 The numeric prefix ARG can specify a number of chars to remove from the
 comment markers."
   (interactive "*r\nP")
   (comment-normalize-vars)
-  (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
+  (when (> beg end) (setq beg (prog1 end (setq end beg))))
   (save-excursion
-    (goto-char beg)
-    (setq end (copy-marker end))
-    (let ((numarg (prefix-numeric-value arg))
-         spt)
-      (while (and (< (point) end)
-                 (setq spt (comment-search-forward end t)))
-       (let* ((ipt (point))
-              ;; Find the end of the comment.
-              (ept (progn
-                     (goto-char spt)
-                     (unless (comment-forward)
-                       (error "Can't find the comment end"))
-                     (point)))
-              (box nil)
-              (ccs comment-continue)
-              (srei (comment-padright ccs 're))
-              (sre (and srei (concat "^\\s-*?\\(" srei "\\)"))))
-         (save-restriction
-           (narrow-to-region spt ept)
-           ;; Remove the comment-start.
-           (goto-char ipt)
+    (if uncomment-region-function
+       (funcall uncomment-region-function beg end arg)
+      (goto-char beg)
+      (setq end (copy-marker end))
+      (let* ((numarg (prefix-numeric-value arg))
+            (ccs comment-continue)
+            (srei (comment-padright ccs 're))
+            (csre (comment-padright comment-start 're))
+            (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
+            spt)
+       (while (and (< (point) end)
+                   (setq spt (comment-search-forward end t)))
+         (let ((ipt (point))
+               ;; Find the end of the comment.
+               (ept (progn
+                      (goto-char spt)
+                      (unless
+                          (or
+                           (comment-forward)
+                           ;; Allow eob as comment-end instead of \n.
+                           (and
+                            (eobp)
+                            (let ((s1 (aref (syntax-table) (char-after spt)))
+                                  (s2 (aref (syntax-table)
+                                            (or (char-after (1+ spt)) 0)))
+                                  (sn (aref (syntax-table) ?\n))
+                                  (flag->b (car (string-to-syntax "> b")))
+                                  (flag-1b (car (string-to-syntax "  1b")))
+                                  (flag-2b (car (string-to-syntax "  2b"))))
+                              (cond
+                               ;; One-character comment-start terminated by
+                               ;; \n.
+                               ((and
+                                 (equal sn (string-to-syntax ">"))
+                                 (equal s1 (string-to-syntax "<")))
+                                (insert-char ?\n 1)
+                                t)
+                               ;; Two-character type b comment-start
+                               ;; terminated by \n.
+                               ((and
+                                 (= (logand (car sn) flag->b) flag->b)
+                                 (= (logand (car s1) flag-1b) flag-1b)
+                                 (= (logand (car s2) flag-2b) flag-2b))
+                                (insert-char ?\n 1)
+                                t)))))
+                        (error "Can't find the comment end"))
+                      (point)))
+               (box nil)
+               (box-equal nil)) ;Whether we might be using `=' for boxes.
+           (save-restriction
+             (narrow-to-region spt ept)
+
+             ;; Remove the comment-start.
+             (goto-char ipt)
            (skip-syntax-backward " ")
-           ;; Check for special `=' used sometimes in comment-box.
-           (when (and (= (- (point) (point-min)) 1) (looking-at "=\\{7\\}"))
-             (skip-chars-forward "="))
            ;; A box-comment starts with a looong comment-start marker.
-           (when (> (- (point) (point-min) (length comment-start)) 7)
+           (when (and (or (and (= (- (point) (point-min)) 1)
+                               (setq box-equal t)
+                               (looking-at "=\\{7\\}")
+                               (not (eq (char-before (point-max)) ?\n))
+                               (skip-chars-forward "="))
+                          (> (- (point) (point-min) (length comment-start)) 7))
+                      (> (count-lines (point-min) (point-max)) 2))
              (setq box t))
-           (when (looking-at (regexp-quote comment-padding))
-             (goto-char (match-end 0)))
+           ;; Skip the padding.  Padding can come from comment-padding and/or
+           ;; from comment-start, so we first check comment-start.
+           (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
+                   (looking-at (regexp-quote comment-padding)))
+               (goto-char (match-end 0)))
            (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
              (goto-char (match-end 0)))
            (if (null arg) (delete-region (point-min) (point))
              (skip-syntax-backward " ")
-             (delete-char (- numarg)))
-
-           ;; Remove the end-comment (and leading padding and such).
-           (goto-char (point-max)) (comment-enter-backward)
-           ;; Check for special `=' used sometimes in comment-box.
-           (when (= (- (point-max) (point)) 1)
-             (let ((pos (point)))
-               ;; skip `=' but only if there are at least 7.
-               (when (> (skip-chars-backward "=") -7) (goto-char pos))))
-           (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
-             (when (and (bolp) (not (bobp))) (backward-char))
-             (if (null arg) (delete-region (point) (point-max))
-               (skip-syntax-forward " ")
-               (delete-char numarg)))
-
-           ;; Unquote any nested end-comment.
-           (comment-quote-nested comment-start comment-end t)
-
-           ;; Eliminate continuation markers as well.
-           (when sre
-             (let* ((cce (comment-string-reverse (or comment-continue
-                                                     comment-start)))
-                    (erei (and box (comment-padleft cce 're)))
-                    (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
-               (goto-char (point-min))
-               (while (progn
-                        (if (and ere (re-search-forward
-                                      ere (line-end-position) t))
-                            (replace-match "" t t nil (if (match-end 2) 2 1))
-                          (setq ere nil))
-                        (forward-line 1)
-                        (re-search-forward sre (line-end-position) t))
-                 (replace-match "" t t nil (if (match-end 2) 2 1)))))
-           ;; Go the the end for the next comment.
-           (goto-char (point-max)))))
-      (set-marker end nil))))
+                 (delete-char (- numarg))
+                 (unless (or (bobp)
+                             (save-excursion (goto-char (point-min))
+                                             (looking-at comment-start-skip)))
+                   ;; If there's something left but it doesn't look like
+                   ;; a comment-start any more, just remove it.
+                   (delete-region (point-min) (point))))
+
+               ;; Remove the end-comment (and leading padding and such).
+               (goto-char (point-max)) (comment-enter-backward)
+               ;; Check for special `=' used sometimes in comment-box.
+               (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
+                 (let ((pos (point)))
+                   ;; skip `=' but only if there are at least 7.
+                   (when (> (skip-chars-backward "=") -7) (goto-char pos))))
+               (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
+                 (when (and (bolp) (not (bobp))) (backward-char))
+                 (if (null arg) (delete-region (point) (point-max))
+                   (skip-syntax-forward " ")
+                   (delete-char numarg)
+                   (unless (or (eobp) (looking-at comment-end-skip))
+                     ;; If there's something left but it doesn't look like
+                     ;; a comment-end any more, just remove it.
+                     (delete-region (point) (point-max)))))
+
+               ;; Unquote any nested end-comment.
+               (comment-quote-nested comment-start comment-end t)
+
+               ;; Eliminate continuation markers as well.
+               (when sre
+                 (let* ((cce (comment-string-reverse (or comment-continue
+                                                         comment-start)))
+                        (erei (and box (comment-padleft cce 're)))
+                        (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
+                   (goto-char (point-min))
+                   (while (progn
+                            (if (and ere (re-search-forward
+                                          ere (line-end-position) t))
+                                (replace-match "" t t nil (if (match-end 2) 2 1))
+                              (setq ere nil))
+                            (forward-line 1)
+                            (re-search-forward sre (line-end-position) t))
+                     (replace-match "" t t nil (if (match-end 2) 2 1)))))
+               ;; Go to the end for the next comment.
+               (goto-char (point-max)))))))
+      (set-marker end nil)))
 
 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
   "Make the leading and trailing extra lines.
@@ -665,27 +837,36 @@ This is used for `extra-line' style (or `box' style if BLOCK is specified)."
             (s (concat cs "a=m" cce))
             (e (concat ccs "a=m" ce))
             (c (if (string-match ".*\\S-\\S-" cs)
-                   (aref cs (1- (match-end 0))) ?=))
-            (_ (string-match "\\s-*a=m\\s-*" s))
+                   (aref cs (1- (match-end 0)))
+                 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
+                     (aref cs (1- (match-end 0))) ?=)))
+            (re "\\s-*a=m\\s-*")
+            (_ (string-match re s))
+            (lcs (length cs))
             (fill
              (make-string (+ width (- (match-end 0)
-                                      (match-beginning 0) (length cs) 3)) c)))
+                                      (match-beginning 0) lcs 3)) c)))
        (setq cs (replace-match fill t t s))
-       (string-match "\\s-*a=m\\s-*" e)
+       (when (and (not (string-match comment-start-skip cs))
+                  (string-match "a=m" s))
+         ;; The whitespace around CS cannot be ignored: put it back.
+         (setq re "a=m")
+         (setq fill (make-string (- width lcs) c))
+         (setq cs (replace-match fill t t s)))
+       (string-match re e)
        (setq ce (replace-match fill t t e))))
     (cons (concat cs "\n" (make-string min-indent ? ) ccs)
          (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
 
-(def-edebug-spec comment-with-narrowing t)
-(put 'comment-with-narrowing 'lisp-indent-function 2)
 (defmacro comment-with-narrowing (beg end &rest body)
   "Execute BODY with BEG..END narrowing.
 Space is added (and then removed) at the beginning for the text's
 indentation to be kept as it was before narrowing."
+  (declare (debug t) (indent 2))
   (let ((bindent (make-symbol "bindent")))
-    `(let ((,bindent (save-excursion (goto-char beg) (current-column))))
+    `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
        (save-restriction
-        (narrow-to-region beg end)
+        (narrow-to-region ,beg ,end)
         (goto-char (point-min))
         (insert (make-string ,bindent ? ))
         (prog1
@@ -708,7 +889,7 @@ indentation to be kept as it was before narrowing."
 
 (defun comment-region-internal (beg end cs ce
                                    &optional ccs cce block lines indent)
-  "Comment region BEG..END.
+  "Comment region BEG .. END.
 CS and CE are the comment start resp end string.
 CCS and CCE are the comment continuation strings for the start resp end
 of lines (default to CS and CE).
@@ -719,7 +900,8 @@ of the region for CE and CS.
 INDENT indicates to put CS and CCS at the current indentation of the region
 rather than at left margin."
   ;;(assert (< beg end))
-  (let ((no-empty t))
+  (let ((no-empty (not (or (eq comment-empty-lines t)
+                          (and comment-empty-lines (zerop (length ce)))))))
     ;; Sanitize CE and CCE.
     (if (and (stringp ce) (string= "" ce)) (setq ce nil))
     (if (and (stringp cce) (string= "" cce)) (setq cce nil))
@@ -733,7 +915,7 @@ rather than at left margin."
     (unless block (setq cce nil))
     ;; Continuation defaults to the same as CS and CE.
     (unless ccs (setq ccs cs cce ce))
-    
+
     (save-excursion
       (goto-char end)
       ;; If the end is not at the end of a line and the comment-end
@@ -755,7 +937,7 @@ rather than at left margin."
                (end-of-line)
                (setq max-indent (max max-indent (current-column)))
                (not (or (eobp) (progn (forward-line) nil)))))
-         
+
          ;; Inserting ccs can change max-indent by (1- tab-width).
          (setq max-indent
                (+ max-indent (max (length cs) (length ccs)) tab-width -1))
@@ -768,7 +950,7 @@ rather than at left margin."
                    cs ce ccs cce min-indent max-indent block)))
              (setq cs (car csce))
              (setq ce (cdr csce))))
-         
+
          (goto-char (point-min))
          ;; Loop over all lines from BEG to END.
          (while
@@ -787,7 +969,7 @@ rather than at left margin."
 ;;;###autoload
 (defun comment-region (beg end &optional arg)
   "Comment or uncomment each line in the region.
-With just \\[universal-argument] prefix arg, uncomment each line in region BEG..END.
+With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
 Numeric prefix arg ARG means use ARG comment characters.
 If ARG is negative, delete that many comment characters instead.
 By default, comments start at the left margin, are terminated on each line,
@@ -806,52 +988,55 @@ The strings used as comment starts are built from
         (block (nth 1 style))
         (multi (nth 0 style)))
     (save-excursion
-      ;; we use `chars' instead of `syntax' because `\n' might be
-      ;; of end-comment syntax rather than of whitespace syntax.
-      ;; sanitize BEG and END
-      (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
-      (setq beg (max beg (point)))
-      (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
-      (setq end (min end (point)))
-      (if (>= beg end) (error "Nothing to comment"))
-
-      ;; sanitize LINES
-      (setq lines
-           (and
-            lines ;; multi
-            (progn (goto-char beg) (beginning-of-line)
-                   (skip-syntax-forward " ")
-                   (>= (point) beg))
-            (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
-                   (<= (point) end))
-            (or (not (string= "" comment-end)) block)
-            (progn (goto-char beg) (search-forward "\n" end t)))))
-
-    ;; don't add end-markers just because the user asked for `block'
-    (unless (or lines (string= "" comment-end)) (setq block nil))
-
-    (cond
-     ((consp arg) (uncomment-region beg end))
-     ((< numarg 0) (uncomment-region beg end (- numarg)))
-     (t
-      (setq numarg (if (and (null arg) (= (length comment-start) 1))
-                      add (1- numarg)))
-      (comment-region-internal
-       beg end
-       (let ((s (comment-padright comment-start numarg)))
-        (if (string-match comment-start-skip s) s
-          (comment-padright comment-start)))
-       (let ((s (comment-padleft comment-end numarg)))
-        (and s (if (string-match comment-end-skip s) s
-                 (comment-padright comment-end))))
-       (if multi (comment-padright comment-continue numarg))
-       (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
-       block
-       lines
-       (nth 3 style))))))
+      (if comment-region-function
+         (funcall comment-region-function beg end arg)
+       ;; we use `chars' instead of `syntax' because `\n' might be
+       ;; of end-comment syntax rather than of whitespace syntax.
+       ;; sanitize BEG and END
+       (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
+       (setq beg (max beg (point)))
+       (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
+       (setq end (min end (point)))
+       (if (>= beg end) (error "Nothing to comment"))
+
+       ;; sanitize LINES
+       (setq lines
+             (and
+              lines ;; multi
+              (progn (goto-char beg) (beginning-of-line)
+                     (skip-syntax-forward " ")
+                     (>= (point) beg))
+              (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
+                     (<= (point) end))
+              (or block (not (string= "" comment-end)))
+              (or block (progn (goto-char beg) (search-forward "\n" end t))))))
+
+      ;; don't add end-markers just because the user asked for `block'
+      (unless (or lines (string= "" comment-end)) (setq block nil))
+
+      (cond
+       ((consp arg) (uncomment-region beg end))
+       ((< numarg 0) (uncomment-region beg end (- numarg)))
+       (t
+       (setq numarg (if (and (null arg) (= (length comment-start) 1))
+                        add (1- numarg)))
+       (comment-region-internal
+        beg end
+        (let ((s (comment-padright comment-start numarg)))
+          (if (string-match comment-start-skip s) s
+            (comment-padright comment-start)))
+        (let ((s (comment-padleft comment-end numarg)))
+          (and s (if (string-match comment-end-skip s) s
+                   (comment-padright comment-end))))
+        (if multi (comment-padright comment-continue numarg))
+        (if multi
+            (comment-padleft (comment-string-reverse comment-continue) numarg))
+        block
+        lines
+        (nth 3 style)))))))
 
 (defun comment-box (beg end &optional arg)
-  "Comment out the BEG..END region, putting it inside a box.
+  "Comment out the BEG .. END region, putting it inside a box.
 The numeric prefix ARG specifies how many characters to add to begin- and
 end- comment markers additionally to what `comment-add' already specifies."
   (interactive "*r\np")
@@ -859,6 +1044,21 @@ end- comment markers additionally to what `comment-add' already specifies."
                           'box-multi 'box)))
     (comment-region beg end (+ comment-add arg))))
 
+
+;;;###autoload
+(defun comment-or-uncomment-region (beg end &optional arg)
+  "Call `comment-region', unless the region only consists of comments,
+in which case call `uncomment-region'.  If a prefix arg is given, it
+is passed on to the respective function."
+  (interactive "*r\nP")
+  (comment-normalize-vars)
+  (funcall (if (save-excursion ;; check for already commented region
+                (goto-char beg)
+                (comment-forward (point-max))
+                (<= end (point)))
+              'uncomment-region 'comment-region)
+          beg end arg))
+
 ;;;###autoload
 (defun comment-dwim (arg)
   "Call the comment command you want (Do What I Mean).
@@ -871,14 +1071,7 @@ Else, call `comment-indent'."
   (interactive "*P")
   (comment-normalize-vars)
   (if (and mark-active transient-mark-mode)
-      (let ((beg (min (point) (mark)))
-           (end (max (point) (mark))))
-       (if (save-excursion ;; check for already commented region
-             (goto-char beg)
-             (comment-forward (point-max))
-             (<= end (point)))
-           (uncomment-region beg end arg)
-         (comment-region beg end arg)))
+      (comment-or-uncomment-region (region-beginning) (region-end) arg)
     (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
        ;; FIXME: If there's no comment to kill on this line and ARG is
        ;; specified, calling comment-kill is not very clever.
@@ -897,8 +1090,15 @@ Else, call `comment-indent'."
 (defcustom comment-auto-fill-only-comments nil
   "Non-nil means to only auto-fill inside comments.
 This has no effect in modes that do not define a comment syntax."
-  :type 'boolean
-  :group 'comment)
+  :type 'boolean)
+
+(defun comment-valid-prefix-p (prefix compos)
+  (or
+   ;; Accept any prefix if the current comment is not EOL-terminated.
+   (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
+   ;; Accept any prefix that starts with a comment-start marker.
+   (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
+                prefix)))
 
 ;;;###autoload
 (defun comment-indent-new-line (&optional soft)
@@ -922,33 +1122,49 @@ unless optional argument SOFT is non-nil."
     ;; don't do anything (unless no comment syntax is defined).
     (unless (and comment-start
                 comment-auto-fill-only-comments
+                (not (interactive-p))
                 (not (save-excursion
                        (prog1 (setq compos (comment-beginning))
                          (setq comin (point))))))
 
       ;; Now we know we should auto-fill.
-      (delete-horizontal-space)
+      ;; Insert the newline before removing empty space so that markers
+      ;; get preserved better.
       (if soft (insert-and-inherit ?\n) (newline 1))
-      (if fill-prefix
+      (save-excursion (forward-char -1) (delete-horizontal-space))
+      (delete-horizontal-space)
+
+      (if (and fill-prefix (not adaptive-fill-mode))
+         ;; Blindly trust a non-adaptive fill-prefix.
          (progn
            (indent-to-left-margin)
-           (insert-and-inherit fill-prefix))
+           (insert-before-markers-and-inherit fill-prefix))
 
        ;; If necessary check whether we're inside a comment.
-       (unless (or comment-multi-line compos (null comment-start))
+       (unless (or compos (null comment-start))
          (save-excursion
            (backward-char)
            (setq compos (comment-beginning))
            (setq comin (point))))
 
-       ;; If we're not inside a comment, just try to indent.
-       (if (not compos) (indent-according-to-mode)
+       (cond
+        ;; If there's an adaptive prefix, use it unless we're inside
+        ;; a comment and the prefix is not a comment starter.
+        ((and fill-prefix
+              (or (not compos)
+                  (comment-valid-prefix-p fill-prefix compos)))
+         (indent-to-left-margin)
+         (insert-and-inherit fill-prefix))
+        ;; If we're not inside a comment, just try to indent.
+        ((not compos) (indent-according-to-mode))
+        (t
          (let* ((comment-column
                  ;; The continuation indentation should be somewhere between
                  ;; the current line's indentation (plus 2 for good measure)
                  ;; and the current comment's indentation, with a preference
                  ;; for comment-column.
                  (save-excursion
+                   ;; FIXME: use prev line's info rather than first line's.
                    (goto-char compos)
                    (min (current-column) (max comment-column
                                               (+ 2 (current-indentation))))))
@@ -970,22 +1186,27 @@ unless optional argument SOFT is non-nil."
                          (point))
                         nil t)))))
                 (comment-start comstart)
+                (continuep (or comment-multi-line
+                               (cadr (assoc comment-style comment-styles))))
                 ;; Force comment-continue to be recreated from comment-start.
+                ;; FIXME: wrong if comment-continue was set explicitly!
+                ;; FIXME: use prev line's continuation if available.
                 (comment-continue nil))
-           (insert-and-inherit ?\n)
-           (forward-char -1)
-           (comment-indent (cadr (assoc comment-style comment-styles)))
-           (save-excursion
-             (let ((pt (point)))
-               (end-of-line)
-               (let ((comend (buffer-substring pt (point))))
-                 ;; The 1+ is to make sure we delete the \n inserted above.
-                 (delete-region pt (1+ (point)))
-                 (beginning-of-line)
-                 (backward-char)
-                 (insert comend)
-                 (forward-char))))))))))
+           (if (and comment-multi-line (> (length comment-end) 0))
+               (indent-according-to-mode)
+             (insert-and-inherit ?\n)
+             (forward-char -1)
+             (comment-indent continuep)
+             (save-excursion
+               (let ((pt (point)))
+                 (end-of-line)
+                 (let ((comend (buffer-substring pt (point))))
+                   ;; The 1+ is to make sure we delete the \n inserted above.
+                   (delete-region pt (1+ (point)))
+                   (end-of-line 0)
+                   (insert comend))))))))))))
 
 (provide 'newcomment)
 
+;;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
 ;;; newcomment.el ends here