]> code.delx.au - gnu-emacs/blobdiff - lisp/newcomment.el
* ediff-init.el (ediff-get-next-window): bug fix.
[gnu-emacs] / lisp / newcomment.el
index c13a5d898263b9ec1dec1f889e40437716c3c259..b44f63db903c8f2b5b885d57067e98339a13e026 100644 (file)
@@ -1,12 +1,10 @@
 ;;; newcomment.el --- (un)comment regions of buffers
 
-;; Copyright (C) 1999-2000  Free Software Foundation Inc.
+;; Copyright (C) 19992000  Free Software Foundation Inc.
 
 ;; Author: code extracted from Emacs-20's simple.el
 ;; Maintainer: Stefan Monnier <monnier@cs.yale.edu>
 ;; Keywords: comment uncomment
-;; Version: $Name:  $
-;; Revision: $Id: newcomment.el,v 1.13 2000/05/22 04:23:37 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.
 
+;; - when auto-filling a comment, try to move the comment to the left
+;;   rather than break it (if possible).
+;; - sometimes default the comment-column to the same
+;;   one used on the preceding line(s).
+
 ;;; Code:
 
+;;;###autoload
 (defalias 'indent-for-comment 'comment-indent)
+;;;###autoload
 (defalias 'set-comment-column 'comment-set-column)
+;;;###autoload
 (defalias 'kill-comment 'comment-kill)
+;;;###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)
 
 (defvar comment-use-syntax 'undecided
@@ -74,40 +87,46 @@ 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
 (defvar comment-start nil
   "*String to insert to start a new comment, or nil if no comment syntax.")
 
+;;;###autoload
 (defvar comment-start-skip nil
   "*Regexp to match the start of a comment plus everything up to its body.
 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
 at the place matched by the close of the first pair.")
 
+;;;###autoload
 (defvar comment-end-skip nil
   "Regexp to match the end of a comment plus everything up to its body.")
 
+;;;###autoload
 (defvar comment-end ""
   "*String to insert to end a new comment.
 Should be an empty string if comments are terminated by end-of-line.")
 
-(defvar comment-indent-hook nil
-  "Obsolete variable for function to compute desired indentation for a comment.
-This function is called with no args with point at the beginning of
-the comment's starting delimiter.")
-
-(defvar comment-indent-function
-  (lambda () comment-column)
+;;;###autoload
+(defvar comment-indent-function 'comment-indent-default
   "Function to compute desired indentation for a comment.
 This function is called with no args with point at the beginning of
-the comment's starting delimiter.")
+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'.")
 
 (defvar block-comment-start nil)
 (defvar block-comment-end nil)
@@ -150,26 +169,29 @@ EXTRA specifies that an extra line should be used before and after the
 INDENT specifies that the `comment-start' markers should not be put at the
   left margin but at the current indentation of the region to comment.")
 
+;;;###autoload
 (defcustom comment-style 'plain
   "*Style to be used for `comment-region'.
 See `comment-styles' for a list of available styles."
-  :group 'comment
-  :type `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles)))
+  :type (if (boundp 'comment-styles)
+           `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles))
+         'symbol))
 
-(defcustom comment-padding 1
+;;;###autoload
+(defcustom comment-padding " "
   "Padding string that `comment-region' puts between comment chars and text.
 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 \\[indent-new-comment-line] should continue same comment
-on new line, with no new terminator or starter.
+  "*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)
 
 ;;;;
 ;;;; Helpers
@@ -186,6 +208,7 @@ 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"))
     ;; comment-use-syntax
@@ -202,6 +225,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
@@ -211,18 +235,30 @@ 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<+\\|"
                   (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))
@@ -330,15 +366,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.
@@ -348,10 +399,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))))
 
@@ -379,9 +431,20 @@ Point is assumed to be just at the end of a comment."
 ;;;; Commands
 ;;;;
 
+;;;###autoload
+(defun comment-indent-default ()
+  "Default for `comment-indent-function'."
+  (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
+          (or (match-end 1) (/= (current-column) (current-indentation))))
+      0
+    (when (or (/= (current-column) (current-indentation))
+             (and (> comment-add 0) (looking-at "\\s<\\S<")))
+      comment-column)))
+
+;;;###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."
+If CONTINUE is non-nil, use the `comment-continue' markers if any."
   (interactive "*")
   (comment-normalize-vars)
   (let* ((empty (save-excursion (beginning-of-line)
@@ -390,34 +453,52 @@ If CONTINUE is non-nil, use the `comment-continuation' markers if any."
                      (and empty block-comment-start) comment-start))
         (ender (or (and continue comment-continue "")
                    (and empty block-comment-end) comment-end)))
-    (cond
-     ((null starter)
-      (error "No comment syntax defined"))
-     (t (let* ((eolpos (line-end-position))
-               cpos indent begpos)
-          (beginning-of-line)
-          (if (not (setq begpos (comment-search-forward eolpos t)))
-             (setq begpos (point))
+    (unless starter (error "No comment syntax defined"))
+    (beginning-of-line)
+    (let* ((eolpos (line-end-position))
+          (begpos (comment-search-forward eolpos t))
+          cpos indent)
+      ;; An existing comment?
+      (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.
+         (save-excursion
+           ;; Some comment-indent-function insist on not moving comments that
+           ;; are in column 0, so we first go to the likely target column.
+           (indent-to comment-column)
+           (setq begpos (point))
+           (insert starter)
            (setq cpos (point-marker))
-           (goto-char begpos))
-          ;; Compute desired indent.
-          (if (= (current-column)
-                 (setq indent (if comment-indent-hook
-                                  (funcall comment-indent-hook)
-                                (funcall comment-indent-function))))
-              (goto-char begpos)
-            ;; If that's different from current, change it.
-            (skip-chars-backward " \t")
-            (delete-region (point) begpos)
-            (indent-to indent))
-          ;; An existing comment?
-          (if cpos
-              (progn (goto-char cpos) (set-marker cpos nil))
-            ;; No, insert one.
-            (insert starter)
-            (save-excursion
-              (insert ender))))))))
-
+           (insert ender)))
+      (goto-char begpos)
+      ;; Compute desired indent.
+      (setq indent (save-excursion (funcall comment-indent-function)))
+      (if (not indent)
+         ;; comment-indent-function refuses: delegate to indent.
+         (indent-according-to-mode)
+       ;; Avoid moving comments past the fill-column.
+       (unless (save-excursion (skip-chars-backward " \t") (bolp))
+         (setq indent
+               (min indent
+                    (+ (current-column)
+                       (- (or comment-fill-column fill-column)
+                          (save-excursion (end-of-line) (current-column)))))))
+       (unless (= (current-column) indent)
+         ;; If that's different from current, change it.
+         (delete-region (point) (progn (skip-chars-backward " \t") (point)))
+         (indent-to (if (bolp) indent
+                      (max indent (1+ (current-column)))))))
+      (goto-char cpos)
+      (set-marker cpos nil))))
+
+;;;###autoload
 (defun comment-set-column (arg)
   "Set the comment column based on point.
 With no ARG, set the comment column to the current column.
@@ -439,6 +520,7 @@ With any other arg, set comment column to indentation of the previous comment
    (t (setq comment-column (current-column))
       (message "Comment column set to %d" comment-column))))
 
+;;;###autoload
 (defun comment-kill (arg)
   "Kill the comment on this line, if any.
 With prefix ARG, kill comments on that many lines starting with this one."
@@ -529,8 +611,9 @@ If N is `re', a regexp is returned instead, that would match
                (if multi (concat (regexp-quote (string c)) "*"))
                (regexp-quote s))))))
 
+;;;###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")
@@ -539,31 +622,36 @@ comment markers."
   (save-excursion
     (goto-char beg)
     (setq end (copy-marker end))
-    (let ((numarg (prefix-numeric-value arg))
-         spt)
+    (let* ((numarg (prefix-numeric-value arg))
+           (ccs comment-continue)
+           (srei (comment-padright ccs '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 (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 "\\)"))))
+       (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)
+              (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)))
@@ -576,10 +664,10 @@ comment markers."
            ;; 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 (= (- (point-max) (point)) 1) (> (point) 7)
-                      (save-excursion (backward-char 7)
-                                      (looking-at "=\\{7\\}")))
-             (skip-chars-backward "="))
+           (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))
@@ -604,7 +692,7 @@ comment markers."
                         (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.
+           ;; Go to the end for the next comment.
            (goto-char (point-max)))))
       (set-marker end nil))))
 
@@ -625,23 +713,32 @@ 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))))
        (save-restriction
@@ -668,7 +765,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).
@@ -744,13 +841,15 @@ rather than at left margin."
                (end-of-line)
                (not (or (eobp) (progn (forward-line) nil))))))))))
 
+;;;###autoload
 (defun comment-region (beg end &optional arg)
   "Comment or uncomment each line in the region.
-With just \\[universal-prefix] 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.
-Comments are terminated on each line, even for syntax in which newline does
-not end the comment.  Blank lines do not get comments.
+By default, comments start at the left margin, are terminated on each line,
+even for syntax in which newline does not end the comment and blank lines
+do not get comments.  This can be changed with `comment-style'.
 
 The strings used as comment starts are built from
 `comment-start' without trailing spaces and `comment-padding'."
@@ -782,8 +881,8 @@ The strings used as comment starts are built from
                    (>= (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)))))
+            (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))
@@ -809,7 +908,7 @@ The strings used as comment starts are built from
        (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")
@@ -817,10 +916,25 @@ 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")
+  (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).
 If the region is active and `transient-mark-mode' is on, call
-  `comment-region' (unless it only consists in comments, in which
+  `comment-region' (unless it only consists of comments, in which
   case it calls `uncomment-region').
 Else, if the current line is empty, insert a comment and indent it.
 Else if a prefix ARG is specified, call `comment-kill'.
@@ -828,20 +942,16 @@ 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.
        (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
       (let ((add (if arg (prefix-numeric-value arg)
                   (if (= (length comment-start) 1) comment-add 0))))
+       ;; Some modes insist on keeping column 0 comment in column 0
+       ;; so we need to move away from it before inserting the comment.
+       (indent-according-to-mode)
        (insert (comment-padright comment-start add))
        (save-excursion
          (unless (string= "" comment-end)
@@ -851,9 +961,17 @@ 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 (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 "\\)")
+                fill-prefix)))
 
+;;;###autoload
 (defun comment-indent-new-line (&optional soft)
   "Break line at point and indent, continuing comment if within one.
 This indents the body of the continued comment
@@ -875,34 +993,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-region (progn (skip-chars-backward " \t") (point))
-                    (progn (skip-chars-forward  " \t") (point)))
+      ;; 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 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))))))
@@ -924,154 +1057,26 @@ 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)
 
-;;; Change Log:
-;; $Log: newcomment.el,v $
-;; Revision 1.13  2000/05/22 04:23:37  monnier
-;; (comment-region-internal): Go back to BEG after quoting
-;; the nested comment markers.
-;;
-;; Revision 1.12  2000/05/21 00:27:31  monnier
-;; (comment-styles): New `box-multi'.
-;; (comment-normalize-vars): Better default for comment-continue to
-;; avoid whitespace-only continuations.
-;; (comment-search-forward): Always move even in the no-syntax case.
-;; (comment-padright): Only obey N if it's only obeyed for padleft.
-;; (comment-make-extra-lines): Better handling of empty continuations.
-;; Use `=' for the filler if comment-start has only one character.
-;; (uncomment-region): Try handling the special `=' filler.
-;; (comment-region): Allow LINES even if MULTI is nil.
-;; (comment-box): Choose box style based on comment-style.
-;;
-;; Revision 1.11  2000/05/19 15:37:41  monnier
-;; Fix license text and author.
-;; Move aliases (indent-for-comment, set-comment-column, kill-comment
-;; and indent-new-comment-line) to the beginning of the file.
-;; Get rid of the last few CLisms.
-;; (comment-forward): Avoid decf.
-;; (comment-make-extra-lines): Comment-out asserts.
-;; (comment-with-narrowing): Properly create uninterned symbol.
-;; (comment-region-internal): Comment-out asserts.  Avoid incf and decf.
-;; (comment-indent-new-line): Fix bug where compt could be set but
-;; not comstart.  Set comment-column more carefully.
-;;
-;; Revision 1.10  2000/05/17 19:32:32  monnier
-;; (comment-beginning): Handle unclosed comment.
-;; (comment-auto-fill-only-comments): New var.
-;; (comment-indent-new-line): Obey comment-auto-fill-only-comments.
-;;   Align with comment-column rather than previous comment if previous
-;;   comment's indentation is greater than comment-column.
-;;
-;; Revision 1.9  2000/05/16 22:02:37  monnier
-;; (comment-string-strip): Strip terminating newlines.
-;; (comment-search-forward): Make LIMIT compulsory.
-;;   If an unterminated string (rather than a comment) is found, try again,
-;;   assuming that the region starts inside a string.
-;; (comment-beginning): Make sure we don't move if we find a comment but
-;;   it's not the one we're in.
-;; (comment-enter-backward): Handle the case where comment-end-skip fails.
-;; (comment-indent): Normalize variables and use line-end-position.
-;; (comment-kill): Use line-end-position.
-;; (comment-spill): Remove.
-;; (comment-indent-new-line): Renamed from indent-new-comment-line.
-;;   Cleaned up old commented-out code.
-;;   Reset comment-continue and comment-end before calling comment-indent.
-;;
-;; Revision 1.8  2000/05/14 00:56:10  monnier
-;; (comment-start, comment-start-skip, comment-end): Made `defvar'.
-;; (comment-style): Extract the choice out of comment-styles.
-;; (comment-continue): Just a simple string now.
-;; (comment-normalize-vars): Update for the new comment-continue.
-;; (until, comment-end-quote-re): Removed.
-;; (comment-quote-re, comment-quote-nested): New functions for quoting.
-;;   These quote both the end and the start and also work for single-chars.
-;; (comment-padright): Added lots of comments.
-;; (comment-padleft): Added more comments.  Check comment-end rather than
-;;   STR to determine whether N can be applied or not.
-;; (uncomment-region): Rename BLOCK to BOX.
-;;   Use the new comment-quote-nested.
-;;   Use only one marker and properly set it back to nil.
-;;   Be more picky when eliminating continuation markers.
-;;
-;; Revision 1.7  2000/05/13 19:41:08  monnier
-;; (comment-use-syntax): Change `maybe' to `undecided'.
-;; (comment-quote-nested): New.  Replaces comment-nested.
-;; (comment-add): Turn into a mere defvar or a integer.
-;; (comment-style): Change default to `plain'.
-;; (comment-styles): Rename `plain' to `indent' and create a new plainer `plain'
-;; (comment-string-reverse): Use nreverse.
-;; (comment-normalize-vars): Change `maybe' to `undecided', add comments.
-;;   Don't infer the setting of comment-nested anymore (the default for
-;;   comment-quote-nested is safe).  Use comment-quote-nested.
-;; (comment-end-quote-re): Use comment-quote-nested.
-;; (comment-search-forward): Obey LIMIT.
-;; (comment-indent): Don't skip forward further past comment-search-forward.
-;; (comment-padleft): Use comment-quote-nested.
-;; (comment-make-extra-lines): Use `cons' rather than `values'.
-;; (comment-region-internal): New arg INDENT.  Use line-end-position.
-;;   Avoid multiple-value-setq.
-;; (comment-region): Follow the new comment-add semantics.
-;;   Don't do box comments any more.
-;; (comment-box): New function.
-;; (comment-dwim): Only do the region stuff is transient-mark-active.
-;;
-;; Revision 1.6  1999/12/08 00:19:51  monnier
-;; various fixes and gratuitous movements.
-;;
-;; Revision 1.5  1999/11/30 16:20:55  monnier
-;; (comment-style(s)): Replaces comment-extra-lines (and comment-multi-line).
-;; (comment-use-syntax): Whether to use the syntax-table or just the regexps.
-;; (comment-end-skip): To find the end of the text.
-;; ...
-;;
-;; Revision 1.4  1999/11/29 01:31:47  monnier
-;; (comment-find): New function.
-;; (indent-for-comment, set-comment-column, kill-comment): use it.
-;;
-;; Revision 1.3  1999/11/29 00:49:18  monnier
-;; (kill-comment): Fixed by rewriting it with syntax-tables rather than regexps
-;; (comment-normalize-vars): Set default (cdr comment-continue)
-;; (comment-end-quote-re): new function taken out of `comment-region-internal'
-;; (uncomment-region): Rewritten using syntax-tables.  Also unquotes
-;;   nested comment-ends and eliminates continuation markers.
-;; (comment-region-internal): Don't create a default for cce.
-;;   Use `comment-end-quote-re'.
-;;
-;; Revision 1.2  1999/11/28 21:33:55  monnier
-;; (comment-make-extra-lines): Moved out of comment-region-internal.
-;; (comment-with-narrowing): New macro.  Provides a way to preserve
-;;   indentation inside narrowing.
-;; (comment-region-internal): Add "\n" to close the comment if necessary.
-;;   Correctly handle commenting-out when BEG is not bolp.
-;;
-;; Revision 1.1  1999/11/28 18:51:06  monnier
-;; First "working" version:
-;; - uncomment-region doesn't work for some unknown reason
-;; - comment-multi-line allows the use of multi line comments
-;; - comment-extra-lines allows yet another style choice
-;; - comment-add allows to default to `;;'
-;; - comment-region on a comment calls uncomment-region
-;; - C-u C-u comment-region aligns comment end markers
-;; - C-u C-u C-u comment-region puts the comment inside a rectangle
-;; - comment-region will try to quote comment-end markers inside the region
-;; - comment-start markers are placed at the indentation level
-;;
-
 ;;; newcomment.el ends here