newcomment.el 62.3 KB
Newer Older
1
;;; newcomment.el --- (un)comment regions of buffers -*- lexical-binding: t -*-
Stefan Monnier's avatar
Stefan Monnier committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1999-2020 Free Software Foundation, Inc.
Stefan Monnier's avatar
Stefan Monnier committed
4

Stefan Monnier's avatar
Stefan Monnier committed
5
;; Author: code extracted from Emacs-20's simple.el
6
;; Maintainer: Stefan Monnier <monnier@gnu.org>
Stefan Monnier's avatar
Stefan Monnier committed
7
;; Keywords: comment uncomment
8
;; Package: emacs
Stefan Monnier's avatar
Stefan Monnier committed
9

Stefan Monnier's avatar
Stefan Monnier committed
10 11
;; This file is part of GNU Emacs.

12
;; GNU Emacs is free software: you can redistribute it and/or modify
Stefan Monnier's avatar
Stefan Monnier committed
13
;; it under the terms of the GNU General Public License as published by
14 15
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Stefan Monnier's avatar
Stefan Monnier committed
16 17

;; GNU Emacs is distributed in the hope that it will be useful,
Stefan Monnier's avatar
Stefan Monnier committed
18 19 20
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
Stefan Monnier's avatar
Stefan Monnier committed
21

Stefan Monnier's avatar
Stefan Monnier committed
22
;; You should have received a copy of the GNU General Public License
23
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
Stefan Monnier's avatar
Stefan Monnier committed
24 25 26

;;; Commentary:

27 28 29 30 31 32 33
;; This library contains functions and variables for commenting and
;; uncommenting source code.

;; Prior to calling any `comment-*' function, you should ensure that
;; `comment-normalize-vars' is first called to set up the appropriate
;; variables; except for the `comment-*' commands, which call
;; `comment-normalize-vars' automatically as a subroutine.
Stefan Monnier's avatar
Stefan Monnier committed
34 35 36

;;; Bugs:

37 38
;; - boxed comments in Perl are not properly uncommented because they are
;;   uncommented one-line at a time.
Stefan Monnier's avatar
Stefan Monnier committed
39
;; - nested comments in sgml-mode are not properly quoted.
40 41
;; - single-char nestable comment-start can only do the "\\s<+" stuff
;;   if the corresponding closing marker happens to be right.
42 43
;; - uncomment-region with a numeric argument can render multichar
;;   comment markers invalid.
44 45 46 47 48
;; - comment-indent or comment-region when called inside a comment
;;   will happily break the surrounding comment.
;; - comment-quote-nested will not (un)quote properly all nested comment
;;   markers if there are more than just comment-start and comment-end.
;;   For example, in Pascal where {...*) and (*...} are possible.
Stefan Monnier's avatar
Stefan Monnier committed
49 50 51

;;; Todo:

52 53 54 55 56
;; - 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.
57
;; - uncomment-region with a consp (for blocks) or somehow make the
58 59 60 61
;;   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".
62 63
;; - somehow allow comment-dwim to use the region even if transient-mark-mode
;;   is not turned on.
Stefan Monnier's avatar
Stefan Monnier committed
64

65 66 67 68 69
;; - 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).

Stefan Monnier's avatar
Stefan Monnier committed
70 71
;;; Code:

72 73 74
(eval-when-compile
  (require 'subr-x))

75
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
76
(defalias 'indent-for-comment 'comment-indent)
77
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
78
(defalias 'set-comment-column 'comment-set-column)
79
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
80
(defalias 'kill-comment 'comment-kill)
81
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
82
(defalias 'indent-new-comment-line 'comment-indent-new-line)
Stefan Monnier's avatar
Stefan Monnier committed
83

84 85 86
(defgroup comment nil
  "Indenting and filling of comments."
  :prefix "comment-"
87
  :version "21.1"
88 89
  :group 'fill)

90 91
;; Autoload this to avoid warnings, since some major modes define it.
;;;###autoload
92 93 94 95
(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
be used to try to determine whether syntax-tables should be trusted
96 97
to understand comments or not in the given buffer.
Major modes should set this variable.")
98

99 100
(defcustom comment-fill-column nil
  "Column to use for `comment-indent'.  If nil, use `fill-column' instead."
101 102
  :type '(choice (const nil) integer)
  :group 'comment)
103

104
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
105
(defcustom comment-column 32
Stefan Monnier's avatar
Stefan Monnier committed
106
  "Column to indent right-margin comments to.
107
Each mode may establish a different default value for this variable; you
108
can set the value for a particular mode using that mode's hook.
109 110
Comments might be indented to a different value in order not to go beyond
`comment-fill-column' or in order to align them with surrounding comments."
111 112
  :type 'integer
  :group 'comment)
Stefan Monnier's avatar
Stefan Monnier committed
113
(make-variable-buffer-local 'comment-column)
114 115
;;;###autoload
(put 'comment-column 'safe-local-variable 'integerp)
Stefan Monnier's avatar
Stefan Monnier committed
116

117
;;;###autoload
118
(defvar comment-start nil
119
  "String to insert to start a new comment, or nil if no comment syntax.")
120 121
;;;###autoload
(put 'comment-start 'safe-local-variable 'string-or-null-p)
Stefan Monnier's avatar
Stefan Monnier committed
122

123
;;;###autoload
124
(defvar comment-start-skip nil
125
  "Regexp to match the start of a comment plus everything up to its body.
126 127 128
If there are any \\(...\\) pairs and `comment-use-syntax' is nil,
the comment delimiter text is held to begin at the place matched
by the close of the first pair.")
129
;;;###autoload
130
(put 'comment-start-skip 'safe-local-variable 'stringp)
131

132
;;;###autoload
133
(defvar comment-end-skip nil
134
  "Regexp to match the end of a comment plus everything back to its body.")
135
;;;###autoload
136
(put 'comment-end-skip 'safe-local-variable 'stringp)
Stefan Monnier's avatar
Stefan Monnier committed
137

138
;;;###autoload
139
(defvar comment-end (purecopy "")
140
  "String to insert to end a new comment.
141
Should be an empty string if comments are terminated by end-of-line.")
142
;;;###autoload
143
(put 'comment-end 'safe-local-variable 'stringp)
Stefan Monnier's avatar
Stefan Monnier committed
144

145
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
146
(defvar comment-indent-function 'comment-indent-default
Stefan Monnier's avatar
Stefan Monnier committed
147
  "Function to compute desired indentation for a comment.
148 149 150 151
This function is called with no args with point at the beginning
of the comment's starting delimiter and should return either the
desired column indentation, a range of acceptable
indentation (MIN . MAX), or nil.
Stefan Monnier's avatar
Stefan Monnier committed
152
If nil is returned, indentation is delegated to `indent-according-to-mode'.")
Stefan Monnier's avatar
Stefan Monnier committed
153

154 155 156 157 158 159 160 161
;;;###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.")

162 163 164 165 166 167 168 169
(defvar-local comment-combine-change-calls t
  "If non-nil (the default), use `combine-change-calls' around
  calls of `comment-region-function' and
  `uncomment-region-function'.  This Substitutes a single call to
  each of the hooks `before-change-functions' and
  `after-change-functions' in place of those hooks being called
  for each individual buffer change.")

170
(defvar comment-region-function 'comment-region-default
171 172 173 174 175 176 177
  "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.")

178
(defvar uncomment-region-function 'uncomment-region-default
179 180 181 182 183 184 185 186
  "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
187 188
(defvar block-comment-start nil)
(defvar block-comment-end nil)
Stefan Monnier's avatar
Stefan Monnier committed
189

190 191 192 193
(defvar comment-quote-nested t
  "Non-nil if nested comments should be quoted.
This should be locally set by each major mode if needed.")

194 195 196 197 198
(defvar comment-quote-nested-function #'comment-quote-nested-default
  "Function to quote nested comments in a region.
It takes the same arguments as `comment-quote-nested-default',
and is called with the buffer narrowed to a single comment.")

199
(defvar comment-continue nil
200 201 202 203 204 205 206 207 208
  "Continuation string to insert for multiline comments.
This string will be added at the beginning of each line except the very
first one when commenting a region with a commenting style that allows
comments to span several lines.
It should generally have the same length as `comment-start' in order to
preserve indentation.
If it is nil a value will be automatically derived from `comment-start'
by replacing its first character with a space.")

209
(defvar comment-add 0
210 211
  "How many more comment chars should be inserted by `comment-region'.
This determines the default value of the numeric argument of `comment-region'.
212 213
The `plain' comment style doubles this value.

214
This should generally stay 0, except for a few modes like Lisp where
215
it is 1 so that regions are commented with two or three semi-colons.")
216

217
;;;###autoload
218
(defconst comment-styles
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  '((plain      nil nil nil nil
                "Start in column 0 (do not indent), as in Emacs-20")
    (indent-or-triple nil nil nil multi-char
              "Start in column 0, but only for single-char starters")
    (indent     nil nil nil t
                "Full comment per line, ends not aligned")
    (aligned	nil t   nil t
                "Full comment per line, ends aligned")
    (box	nil t   t   t
                "Full comment per line, ends aligned, + top and bottom")
    (extra-line	t   nil t   t
                "One comment for all lines, end on a line by itself")
    (multi-line	t   nil nil t
                "One comment for all lines, end on last commented line")
    (box-multi	t   t   t   t
                "One comment for all lines, + top and bottom"))
  "Comment region style definitions.
Each style is defined with a form (STYLE . (MULTI ALIGN EXTRA INDENT DOC)).
DOC should succinctly describe the style.
238 239
STYLE should be a mnemonic symbol.
MULTI specifies that comments are allowed to span multiple lines.
240 241 242 243 244 245 246 247
  e.g. in C it comments regions as
     /* blabla
      * bli */
  rather than
     /* blabla */
     /* bli */
  if `comment-end' is empty, this has no effect.

248
ALIGN specifies that the `comment-end' markers should be aligned.
249 250 251 252 253 254 255 256
  e.g. in C it comments regions as
     /* blabla */
     /* bli    */
  rather than
     /* blabla */
     /* bli */
  if `comment-end' is empty, this has no effect, unless EXTRA is also set,
  in which case the comment gets wrapped in a box.
257

258 259
EXTRA specifies that an extra line should be used before and after the
  region to comment (to put the `comment-end' and `comment-start').
260 261 262 263 264 265 266 267 268 269 270
  e.g. in C it comments regions as
     /*
      * blabla
      * bli
      */
  rather than
     /* blabla
      * bli */
  if the comment style is not multi line, this has no effect, unless ALIGN
  is also set, in which case the comment gets wrapped in a box.

271
INDENT specifies that the `comment-start' markers should not be put at the
272 273 274
  left margin but at the current indentation of the region to comment.
If INDENT is `multi-char', that means indent multi-character
  comment starters, but not one-character comment starters.")
275

276
;;;###autoload
277
(defcustom comment-style 'indent
Stefan Monnier's avatar
Stefan Monnier committed
278
  "Style to be used for `comment-region'.
279
See `comment-styles' for a list of available styles."
280
  :type (if (boundp 'comment-styles)
281 282 283 284 285
	    `(choice
              ,@(mapcar (lambda (s)
                          `(const :tag ,(format "%s: %s" (car s) (nth 5 s))
                                  ,(car s)))
                        comment-styles))
286
	  'symbol)
287
  :version "23.1"
288
  :group 'comment)
289

290
;;;###autoload
291
(defcustom comment-padding (purecopy " ")
292 293 294
  "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.
295 296

Extra spacing between the comment characters and the comment text
297
makes the comment easier to read.  Default is 1.  nil means 0."
298 299
  :type '(choice string integer (const nil))
  :group 'comment)
300

301 302
(defcustom comment-inline-offset 1
  "Inline comments have to be preceded by at least this many spaces.
303
This is useful when style-conventions require a certain minimal offset.
304 305
Python's PEP8 for example recommends two spaces, so you could do:

306 307
\(add-hook \\='python-mode-hook
   (lambda () (set (make-local-variable \\='comment-inline-offset) 2)))
308 309

See `comment-padding' for whole-line comments."
310
  :version "24.3"
311 312 313
  :type 'integer
  :group 'comment)

314
;;;###autoload
315
(defcustom comment-multi-line nil
Stefan Monnier's avatar
Stefan Monnier committed
316
  "Non-nil means `comment-indent-new-line' continues comments.
Luc Teirlinck's avatar
Luc Teirlinck committed
317 318 319 320 321 322
That is, it inserts no new terminator or starter.
This affects `auto-fill-mode', which is the main reason to
customize this variable.

It also affects \\[indent-new-comment-line].  However, if you want this
behavior for explicit filling, you might as well use \\[newline-and-indent]."
323
  :type 'boolean
324
  :safe #'booleanp
325
  :group 'comment)
326

327 328 329
(defcustom comment-empty-lines nil
  "If nil, `comment-region' does not comment out empty lines.
If t, it always comments out empty lines.
330 331
If `eol', it only comments out empty lines if comments are
terminated by the end of line (i.e., `comment-end' is empty)."
332
  :type '(choice (const :tag "Never" nil)
333 334
                 (const :tag "Always" t)
                 (const :tag "EOL-terminated" eol))
335
  :group 'comment)
336

337 338 339 340
;;;;
;;;; Helpers
;;;;

341 342 343
(defun comment-string-strip (str beforep afterp)
  "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
  (string-match (concat "\\`" (if beforep "\\s-*")
344
			"\\(.*?\\)" (if afterp "\\s-*\n?")
345 346 347 348
			"\\'") str)
  (match-string 1 str))

(defun comment-string-reverse (s)
349
  "Return the mirror image of string S, without any trailing space."
350
  (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
351

352
;;;###autoload
353
(defun comment-normalize-vars (&optional noerror)
354 355 356 357 358
  "Check and set up variables needed by other commenting functions.
All the `comment-*' commands call this function to set up various
variables, like `comment-start', to ensure that the commenting
functions work correctly.  Lisp callers of any other `comment-*'
function should first call this function explicitly."
359 360
  (unless (and (not comment-start) noerror)
    (unless comment-start
361 362 363 364 365
      (let ((cs (read-string "No comment syntax is defined.  Use: ")))
	(if (zerop (length cs))
	    (error "No comment syntax defined")
	  (set (make-local-variable 'comment-start) cs)
	  (set (make-local-variable 'comment-start-skip) cs))))
366
    ;; comment-use-syntax
367
    (when (eq comment-use-syntax 'undecided)
368 369 370 371
      (set (make-local-variable 'comment-use-syntax)
	   (let ((st (syntax-table))
		 (cs comment-start)
		 (ce (if (string= "" comment-end) "\n" comment-end)))
372 373
	     ;; Try to skip over a comment using forward-comment
	     ;; to see if the syntax tables properly recognize it.
374 375 376 377 378 379
	     (with-temp-buffer
	       (set-syntax-table st)
	       (insert cs " hello " ce)
	       (goto-char (point-min))
	       (and (forward-comment 1) (eobp))))))
    ;; comment-padding
380
    (unless comment-padding (setq comment-padding 0))
381 382 383 384 385 386
    (when (integerp comment-padding)
      (setq comment-padding (make-string comment-padding ? )))
    ;; comment markers
    ;;(setq comment-start (comment-string-strip comment-start t nil))
    ;;(setq comment-end (comment-string-strip comment-end nil t))
    ;; comment-continue
387
    (unless (or comment-continue (string= comment-end ""))
388
      (set (make-local-variable 'comment-continue)
389
	   (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
390 391 392
		   (substring comment-start 1)))
      ;; Hasn't been necessary yet.
      ;; (unless (string-match comment-start-skip comment-continue)
393
      ;;	(kill-local-variable 'comment-continue))
394
      )
395
    ;; comment-skip regexps
396 397 398
    (unless (and comment-start-skip
		 ;; In case comment-start has changed since last time.
		 (string-match comment-start-skip comment-start))
399
      (set (make-local-variable 'comment-start-skip)
400 401 402
	   (concat (unless (eq comment-use-syntax t)
                     ;; `syntax-ppss' will detect escaping.
                     "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)")
403
                   "\\(?:\\s<+\\|"
404
		   (regexp-quote (comment-string-strip comment-start t t))
405 406 407
		   ;; Let's not allow any \s- but only [ \t] since \n
		   ;; might be both a comment-end marker and \s-.
		   "+\\)[ \t]*")))
408 409
    (unless (and comment-end-skip
		 ;; In case comment-end has changed since last time.
410 411
		 (string-match comment-end-skip
                               (if (string= "" comment-end) "\n" comment-end)))
412 413 414
      (let ((ce (if (string= "" comment-end) "\n"
		  (comment-string-strip comment-end t t))))
	(set (make-local-variable 'comment-end-skip)
415 416 417
	     ;; 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 "" "+")
418
		     "\\|" (regexp-quote (substring ce 0 1))
419
		     (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
420 421
		     (regexp-quote (substring ce 1))
		     "\\)"))))))
422

423 424 425 426 427 428 429 430 431 432
(defun comment-quote-re (str unp)
  (concat (regexp-quote (substring str 0 1))
	  "\\\\" (if unp "+" "*")
	  (regexp-quote (substring str 1))))

(defun comment-quote-nested (cs ce unp)
  "Quote or unquote nested comments.
If UNP is non-nil, unquote nested comment markers."
  (setq cs (comment-string-strip cs t t))
  (setq ce (comment-string-strip ce t t))
433 434 435 436 437 438 439 440 441
  (when (and comment-quote-nested
	     (> (length ce) 0))
    (funcall comment-quote-nested-function cs ce unp)))

(defun comment-quote-nested-default (cs ce unp)
  "Quote comment delimiters in the buffer.
It expects to be called with the buffer narrowed to a single comment.
It is used as a default for `comment-quote-nested-function'.

442 443
The arguments CS and CE are strings matching comment starting and
ending delimiters respectively.
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470

If UNP is non-nil, comments are unquoted instead.

To quote the delimiters, a \\ is inserted after the first
character of CS or CE.  If CE is a single character it will
change CE into !CS."
  (let ((re (concat (comment-quote-re ce unp)
		    "\\|" (comment-quote-re cs unp))))
    (goto-char (point-min))
    (while (re-search-forward re nil t)
      (goto-char (match-beginning 0))
      (forward-char 1)
      (if unp (delete-char 1) (insert "\\"))
      (when (= (length ce) 1)
	;; If the comment-end is a single char, adding a \ after that
	;; "first" char won't deactivate it, so we turn such a CE
	;; into !CS.  I.e. for pascal, we turn } into !{
	(if (not unp)
	    (when (string= (match-string 0) ce)
	      (replace-match (concat "!" cs) t t))
	  (when (and (< (point-min) (match-beginning 0))
		     (string= (buffer-substring (1- (match-beginning 0))
						(1- (match-end 0)))
			      (concat "!" cs)))
	    (backward-char 2)
	    (delete-char (- (match-end 0) (match-beginning 0)))
	    (insert ce)))))))
471 472 473 474 475

;;;;
;;;; Navigation
;;;;

476
(defvar comment-use-global-state t
477 478
  "Non-nil means that the global syntactic context is used.
More specifically, it means that `syntax-ppss' is used to find out whether
479 480 481 482 483 484
point is within a string or not.  Major modes whose syntax is not faithfully
described by the syntax-tables (or where `font-lock-syntax-table' is radically
different from the main syntax table) can set this to nil,
then `syntax-ppss' cache won't be used in comment-related routines.")

(make-obsolete-variable 'comment-use-global-state 'comment-use-syntax "24.4")
485

486
(defun comment-search-forward (limit &optional noerror)
487 488 489
  "Find a comment start between point and LIMIT.
Moves point to inside the comment and returns the position of the
comment-starter.  If no comment is found, moves point to LIMIT
490 491 492
and raises an error or returns nil if NOERROR is non-nil.

Ensure that `comment-normalize-vars' has been called before you use this."
493
  (if (not comment-use-syntax)
494 495 496 497
      (if (re-search-forward comment-start-skip limit noerror)
	  (or (match-end 1) (match-beginning 0))
	(goto-char limit)
	(unless noerror (error "No comment")))
498 499
    (let* ((pt (point))
	   ;; Assume (at first) that pt is outside of any string.
500 501 502 503
	   (s (parse-partial-sexp pt (or limit (point-max)) nil nil
				  (if comment-use-global-state (syntax-ppss pt))
				  t)))
      (when (and (nth 8 s) (nth 3 s) (not comment-use-global-state))
504 505 506 507 508 509
	;; The search ended at eol inside a string.  Try to see if it
	;; works better when we assume that pt is inside a string.
	(setq s (parse-partial-sexp
		 pt (or limit (point-max)) nil nil
		 (list nil nil nil (nth 3 s) nil nil nil nil)
		 t)))
510 511 512
      (if (or (not (and (nth 8 s) (not (nth 3 s))))
	      ;; Make sure the comment starts after PT.
	      (< (nth 8 s) pt))
513 514
	  (unless noerror (error "No comment"))
	;; We found the comment.
515
	(let ((pos (point))
516
	      (start (nth 8 s))
517
	      (bol (line-beginning-position))
518 519 520 521 522
	      (end nil))
	  (while (and (null end) (>= (point) bol))
	    (if (looking-at comment-start-skip)
		(setq end (min (or limit (point-max)) (match-end 0)))
	      (backward-char)))
523
	  (goto-char (or end pos))
524
	  start)))))
525 526 527

(defun comment-search-backward (&optional limit noerror)
  "Find a comment start between LIMIT and point.
528 529
Moves point to inside the comment and returns the position of the
comment-starter.  If no comment is found, moves point to LIMIT
530 531 532
and raises an error or returns nil if NOERROR is non-nil.

Ensure that `comment-normalize-vars' has been called before you use this."
533 534 535 536 537
  ;; FIXME: If a comment-start appears inside a comment, we may erroneously
  ;; stop there.  This can be rather bad in general, but since
  ;; comment-search-backward is only used to find the comment-column (in
  ;; comment-set-column) and to find the comment-start string (via
  ;; comment-beginning) in indent-new-comment-line, it should be harmless.
538
  (if (not (re-search-backward comment-start-skip limit 'move))
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
      (unless noerror (error "No comment"))
    (beginning-of-line)
    (let* ((end (match-end 0))
	   (cs (comment-search-forward end t))
	   (pt (point)))
      (if (not cs)
	  (progn (beginning-of-line)
		 (comment-search-backward limit noerror))
	(while (progn (goto-char cs)
		      (comment-forward)
		      (and (< (point) end)
			   (setq cs (comment-search-forward end t))))
	  (setq pt (point)))
	(goto-char pt)
	cs))))
554 555

(defun comment-beginning ()
556 557
  "Find the beginning of the enclosing comment.
Returns nil if not inside a comment, else moves point and returns
558
the same as `comment-search-backward'."
559
  (if (and comment-use-syntax comment-use-global-state)
560 561 562 563
      (let ((state (syntax-ppss)))
        (when (nth 4 state)
          (goto-char (nth 8 state))
          (prog1 (point)
564 565 566 567 568
            (when (save-restriction
                    ;; `comment-start-skip' sometimes checks that the
                    ;; comment char is not escaped.  (Bug#16971)
                    (narrow-to-region (point) (point-max))
                    (looking-at comment-start-skip))
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
              (goto-char (match-end 0))))))
    ;; Can't rely on the syntax table, let's guess based on font-lock.
    (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 (if comment-end-skip (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))))))
593 594 595 596 597 598 599 600 601

(defun comment-forward (&optional n)
  "Skip forward over N comments.
Just like `forward-comment' but only for positive N
and can use regexps instead of syntax."
  (setq n (or n 1))
  (if (< n 0) (error "No comment-backward")
    (if comment-use-syntax (forward-comment n)
      (while (> n 0)
Stefan Monnier's avatar
Stefan Monnier committed
602
	(setq n
603 604 605 606
	      (if (or (forward-comment 1)
		      (and (looking-at comment-start-skip)
			   (goto-char (match-end 0))
			   (re-search-forward comment-end-skip nil 'move)))
Stefan Monnier's avatar
Stefan Monnier committed
607
		  (1- n) -1)))
608 609 610 611
      (= n 0))))

(defun comment-enter-backward ()
  "Move from the end of a comment to the end of its content.
612
Point is assumed to be just at the end of a comment."
613 614 615
  (if (bolp)
      ;; comment-end = ""
      (progn (backward-char) (skip-syntax-backward " "))
Stefan Monnier's avatar
Stefan Monnier committed
616
    (cond
617 618 619 620 621
     ((save-excursion
        (save-restriction
          (narrow-to-region (line-beginning-position) (point))
          (goto-char (point-min))
          (re-search-forward (concat comment-end-skip "\\'") nil t)))
Stefan Monnier's avatar
Stefan Monnier committed
622
      (goto-char (match-beginning 0)))
623 624 625 626 627 628 629 630 631 632 633
     ;; comment-end-skip not found probably because it was not set
     ;; right.  Since \\s> should catch the single-char case, let's
     ;; check that we're looking at a two-char comment ender.
     ((not (or (<= (- (point-max) (line-beginning-position)) 1)
               (zerop (logand (car (syntax-after (- (point) 1)))
                              ;; Here we take advantage of the fact that
                              ;; the syntax class " " is encoded to 0,
                              ;; so "  4" gives us just the 4 bit.
                              (car (string-to-syntax "  4"))))
               (zerop (logand (car (syntax-after (- (point) 2)))
                              (car (string-to-syntax "  3"))))))
Stefan Monnier's avatar
Stefan Monnier committed
634 635
      (backward-char 2)
      (skip-chars-backward (string (char-after)))
636 637 638 639 640
      (skip-syntax-backward " "))
     ;; No clue what's going on: maybe we're really not right after the
     ;; end of a comment.  Maybe we're at the "end" because of EOB rather
     ;; than because of a marker.
     (t (skip-syntax-backward " ")))))
641 642 643 644 645

;;;;
;;;; Commands
;;;;

646
;;;###autoload
Stefan Monnier's avatar
Stefan Monnier committed
647 648
(defun comment-indent-default ()
  "Default for `comment-indent-function'."
649 650 651
  (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
	   (or (match-end 1) (/= (current-column) (current-indentation))))
      0
Stefan Monnier's avatar
Stefan Monnier committed
652
    (when (or (/= (current-column) (current-indentation))
653
	      (and (> comment-add 0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
Stefan Monnier's avatar
Stefan Monnier committed
654 655
      comment-column)))

656 657 658 659 660 661 662 663
(defun comment-choose-indent (&optional indent)
  "Choose the indentation to use for a right-hand-side comment.
The criteria are (in this order):
- try to keep the comment's text within `comment-fill-column'.
- try to align with surrounding comments.
- prefer INDENT (or `comment-column' if nil).
Point is expected to be at the start of the comment."
  (unless indent (setq indent comment-column))
664 665 666 667 668 669 670 671 672 673 674 675 676 677
  (let ((other nil)
        min max)
    (pcase indent
      (`(,lo . ,hi) (setq min lo) (setq max hi)
       (setq indent comment-column))
      (_ ;; Avoid moving comments past the fill-column.
       (setq max (+ (current-column)
                    (- (or comment-fill-column fill-column)
                       (save-excursion (end-of-line) (current-column)))))
       (setq min (save-excursion
                   (skip-chars-backward " \t")
                   ;; Leave at least `comment-inline-offset' space after
                   ;; other nonwhite text on the line.
                   (if (bolp) 0 (+ comment-inline-offset (current-column)))))))
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    ;; Fix up the range.
    (if (< max min) (setq max min))
    ;; Don't move past the fill column.
    (if (<= max indent) (setq indent max))
    ;; We can choose anywhere between min..max.
    ;; Let's try to align to a comment on the previous line.
    (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!
        other
      ;; Can't align to a previous comment: let's try to align to comments
      ;; on the following lines, then.  These have not been re-indented yet,
      ;; so we can't directly align ourselves with them.  All we do is to try
      ;; and choose an indentation point with which they will be able to
      ;; align themselves.
      (save-excursion
        (while (and (zerop (forward-line 1))
                    (setq other (comment-search-forward
                                 (line-end-position) t)))
          (goto-char other)
          (let ((omax (+ (current-column)
                         (- (or comment-fill-column fill-column)
                            (save-excursion (end-of-line) (current-column)))))
                (omin (save-excursion (skip-chars-backward " \t")
                                      (1+ (current-column)))))
            (if (and (>= omax min) (<= omin max))
                (progn (setq min (max omin min))
                       (setq max (min omax max)))
              ;; Can't align with this anyway, so exit the loop.
              (goto-char (point-max))))))
      ;; Return the closest point to indent within min..max.
      (max min (min max indent)))))

715
;;;###autoload
716
(defun comment-indent (&optional continue)
717
  "Indent this line's comment to `comment-column', or insert an empty comment.
718
If CONTINUE is non-nil, use the `comment-continue' markers if any."
Stefan Monnier's avatar
Stefan Monnier committed
719
  (interactive "*")
720
  (comment-normalize-vars)
Stefan Monnier's avatar
Stefan Monnier committed
721 722
  (let* ((empty (save-excursion (beginning-of-line)
				(looking-at "[ \t]*$")))
723
	 (starter (or (and continue comment-continue)
724
		      (and empty block-comment-start) comment-start))
725
	 (ender (or (and continue comment-continue "")
726
		    (and empty block-comment-end) comment-end)))
727 728 729 730 731
    (unless starter (error "No comment syntax defined"))
    (beginning-of-line)
    (let* ((eolpos (line-end-position))
	   (begpos (comment-search-forward eolpos t))
	   cpos indent)
732 733 734 735 736 737 738 739 740 741 742 743 744
      (if (and comment-insert-comment-function (not begpos))
	  ;; If no comment and c-i-c-f is set, let it do everything.
	  (funcall comment-insert-comment-function)
	;; 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)))
745 746
	  ;; If none, insert one.
	  (save-excursion
747 748 749
	    ;; Some `comment-indent-function's insist on not moving
	    ;; comments that are in column 0, so we first go to the
	    ;; likely target column.
750
	    (indent-to comment-column)
751 752
	    ;; Ensure there's a space before the comment for things
	    ;; like sh where it matters (as well as being neater).
753 754
	    (unless (memq (char-before) '(nil ?\n ?\t ?\s))
	      (insert ?\s))
755
	    (setq begpos (point))
Stefan Monnier's avatar
Stefan Monnier committed
756
	    (insert starter)
757
	    (setq cpos (point-marker))
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
	    (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: delegate to line-indent.
	    (indent-according-to-mode)
	  ;; If the comment is at the right of code, adjust the indentation.
	  (unless (save-excursion (skip-chars-backward " \t") (bolp))
	    (setq indent (comment-choose-indent indent)))
	  ;; If that's different from comment's current position, change it.
	  (unless (= (current-column) indent)
	    (delete-region (point) (progn (skip-chars-backward " \t") (point)))
	    (indent-to indent)))
	(goto-char cpos)
	(set-marker cpos nil)))))
Stefan Monnier's avatar
Stefan Monnier committed
778

779
;;;###autoload
780
(defun comment-set-column (arg)
Stefan Monnier's avatar
Stefan Monnier committed
781
  "Set the comment column based on point.
782
With no ARG, set the comment column to the current column.
Stefan Monnier's avatar
Stefan Monnier committed
783 784 785 786
With just minus as arg, kill any comment on this line.
With any other arg, set comment column to indentation of the previous comment
 and then align or create a comment on this line at that column."
  (interactive "P")
Stefan Monnier's avatar
Stefan Monnier committed
787
  (cond
788
   ((eq arg '-) (comment-kill nil))
Stefan Monnier's avatar
Stefan Monnier committed
789
   (arg
790
    (comment-normalize-vars)
Stefan Monnier's avatar
Stefan Monnier committed
791 792
    (save-excursion
      (beginning-of-line)
793
      (comment-search-backward)
Stefan Monnier's avatar
Stefan Monnier committed
794
      (beginning-of-line)
795
      (goto-char (comment-search-forward (line-end-position)))
Stefan Monnier's avatar
Stefan Monnier committed
796
      (setq comment-column (current-column))
Stefan Monnier's avatar
Stefan Monnier committed
797
      (message "Comment column set to %d" comment-column))
798
    (comment-indent))
Stefan Monnier's avatar
Stefan Monnier committed
799
   (t (setq comment-column (current-column))
Stefan Monnier's avatar
Stefan Monnier committed
800 801
      (message "Comment column set to %d" comment-column))))

802
;;;###autoload
803
(defun comment-kill (arg)
804
  "Kill the first comment on this line, if any.
805 806
With prefix ARG, kill comments on that many lines starting with this one."
  (interactive "P")
807
  (comment-normalize-vars)
808
  (dotimes (_i (prefix-numeric-value arg))
809 810 811 812 813 814 815 816 817 818 819
    (save-excursion
      (beginning-of-line)
      (let ((cs (comment-search-forward (line-end-position) t)))
	(when cs
	  (goto-char cs)
	  (skip-syntax-backward " ")
	  (setq cs (point))
	  (comment-forward)
	  (kill-region cs (if (bolp) (1- (point)) (point)))
	  (indent-according-to-mode))))
    (if arg (forward-line 1))))
820

821 822
(defun comment-padright (str &optional n)
  "Construct a string composed of STR plus `comment-padding'.
823
It also adds N copies of the last non-whitespace chars of STR.
824
If STR already contains padding, the corresponding amount is
825 826
ignored from `comment-padding'.
N defaults to 0.
827
If N is `re', a regexp is returned instead, that would match
828 829 830
the string for any N.

Ensure that `comment-normalize-vars' has been called before you use this."
831
  (setq n (or n 0))
832
  (when (and (stringp str) (string-match "\\S-" str))
833
    ;; Separate the actual string from any leading/trailing padding
834
    (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
835 836 837 838
    (let ((s (match-string 1 str))	;actual string
	  (lpad (substring str 0 (match-beginning 1))) ;left padding
	  (rpad (concat (substring str (match-end 1)) ;original right padding
			(substring comment-padding ;additional right padding
839
				   (min (- (match-end 0) (match-end 1))
840 841 842 843 844 845 846 847
					(length comment-padding)))))
	  ;; We can only duplicate C if the comment-end has multiple chars
	  ;; or if comments can be nested, else the comment-end `}' would
	  ;; be turned into `}}}' where only the first ends the comment
	  ;; and the rest becomes bogus junk.
	  (multi (not (and comment-quote-nested
			   ;; comment-end is a single char
			   (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
848
      (if (not (symbolp n))
849
	  (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
850 851 852 853
	;; construct a regexp that would match anything from just S
	;; to any possible output of this function for any N.
	(concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
			   lpad "")	;padding is not required
854 855
		(regexp-quote s)
		(when multi "+")	;the last char of S might be repeated
856 857
		(mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
			   rpad "")))))) ;padding is not required
858 859 860

(defun comment-padleft (str &optional n)
  "Construct a string composed of `comment-padding' plus STR.
861
It also adds N copies of the first non-whitespace chars of STR.
862
If STR already contains padding, the corresponding amount is
863 864
ignored from `comment-padding'.
N defaults to 0.
865 866 867 868
If N is `re', a regexp is returned instead, that would match the
string for any N.

Ensure that `comment-normalize-vars' has been called before you use this."
869 870
  (setq n (or n 0))
  (when (and (stringp str) (not (string= "" str)))
871
    ;; Only separate the left pad because we assume there is no right pad.
872 873 874 875 876 877
    (string-match "\\`\\s-*" str)
    (let ((s (substring str (match-end 0)))
	  (pad (concat (substring comment-padding
				  (min (- (match-end 0) (match-beginning 0))
				       (length comment-padding)))
		       (match-string 0 str)))
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
	  (c (aref str (match-end 0)))	;the first non-space char of STR
	  ;; We can only duplicate C if the comment-end has multiple chars
	  ;; or if comments can be nested, else the comment-end `}' would
	  ;; be turned into `}}}' where only the first ends the comment
	  ;; and the rest becomes bogus junk.
	  (multi (not (and comment-quote-nested
			   ;; comment-end is a single char
			   (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
      (if (not (symbolp n))
	  (concat pad (when multi (make-string n c)) s)
	;; Construct a regexp that would match anything from just S
	;; to any possible output of this function for any N.
	;; We match any number of leading spaces because this regexp will
	;; be used for uncommenting where we might want to remove
	;; uncomment markers with arbitrary leading space (because
	;; they were aligned).
	(concat "\\s-*"
		(if multi (concat (regexp-quote (string c)) "*"))
		(regexp-quote s))))))
Stefan Monnier's avatar
Stefan Monnier committed
897

898
;;;###autoload
899
(defun uncomment-region (beg end &optional arg)
900
  "Uncomment each line in the BEG .. END region.
901
The numeric prefix ARG can specify a number of chars to remove from the
902
comment delimiters."
Stefan Monnier's avatar
Stefan Monnier committed
903 904
  (interactive "*r\nP")
  (comment-normalize-vars)
905
  (when (> beg end) (setq beg (prog1 end (setq end beg))))
906 907
  ;; Bind `comment-use-global-state' to nil.  While uncommenting a region
  ;; (which works a line at a time), a comment can appear to be
908 909 910
  ;; included in a mult-line string, but it is actually not.
  (let ((comment-use-global-state nil))
    (save-excursion
911 912
      (funcall uncomment-region-function beg end arg))))

913
(defun uncomment-region-default-1 (beg end &optional arg)
914 915
  "Uncomment each line in the BEG .. END region.
The numeric prefix ARG can specify a number of chars to remove from the
916 917
comment delimiters.
This function is the default value of `uncomment-region-function'."
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  (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 non-terminated comments.
			       (eobp))
		     (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)
941

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
	  ;; Remove the comment-start.
	  (goto-char ipt)
	  (skip-syntax-backward " ")
	  ;; A box-comment starts with a looong comment-start marker.
	  (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))
	  ;; 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))
962 963
            (let ((opoint (point-marker)))
              (skip-syntax-backward " ")
964 965 966 967 968 969 970
              (delete-char (- numarg))
              (unless (and (not (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) opoint))))
971

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	  ;; 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.
1008 1009 1010 1011 1012 1013 1014 1015 1016
	  (goto-char (point-max)))
        ;; Remove any obtrusive spaces left preceding a tab at `spt'.
        (when (and (eq (char-after spt) ?\t) (eq (char-before spt) ? )
                   (> tab-width 0))
          (save-excursion
            (goto-char spt)
            (let* ((fcol (current-column))
                   (slim (- (point) (mod fcol tab-width))))
              (delete-char (- (skip-chars-backward " " slim)))))))))
1017
  (set-marker end nil))
Stefan Monnier's avatar
Stefan Monnier committed
1018

1019 1020 1021 1022 1023 1024 1025 1026 1027
(defun uncomment-region-default (beg end &optional arg)
  "Uncomment each line in the BEG .. END region.
The numeric prefix ARG can specify a number of chars to remove from the
comment markers."
  (if comment-combine-change-calls
      (combine-change-calls beg end (uncomment-region-default-1 beg end arg))
    (uncomment-region-default-1 beg end arg)))


1028 1029 1030 1031 1032 1033 1034 1035
(defun comment-make-bol-ws (len)
  "Make a white-space string of width LEN for use at BOL.
When `indent-tabs-mode' is non-nil, tab characters will be used."
  (if (and indent-tabs-mode (> tab-width 0))
      (concat (make-string (/ len tab-width) ?\t)
	      (make-string (% len tab-width) ? ))
    (make-string len ? )))

1036
(defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
1037 1038
  "Make the leading and trailing extra lines.
This is used for `extra-line' style (or `box' style if BLOCK is specified)."
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
  (let ((eindent 0))
    (if (not block)
	;; Try to match CS and CE's content so they align aesthetically.
	(progn
	  (setq ce (comment-string-strip ce t t))
	  (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
	    (setq eindent
		  (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
		       0))))
      ;; box comment
      (let* ((width (- max-indent min-indent))
	     (s (concat cs "a=m" cce))
	     (e (concat ccs "a=m" ce))
	     (c (if (string-match ".*\\S-\\S-" cs)
1053 1054 1055 1056 1057 1058
		    (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))
1059 1060
	     (fill
	      (make-string (+ width (- (match-end 0)
1061
				       (match-beginning 0) lcs 3)) c)))
1062
	(setq cs (replace-match fill t t s))
1063 1064 1065 1066 1067 1068 1069
	(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)
1070
	(setq ce (replace-match fill t t e))))
1071 1072
    (cons (concat cs "\n" (comment-make-bol-ws min-indent) ccs)
	  (concat cce "\n" (comment-make-bol-ws (+ min-indent eindent)) ce))))
1073 1074 1075 1076 1077

(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."
1078
  (declare (debug t) (indent 2))
Stefan Monnier's avatar
Stefan Monnier committed
1079
  (let ((bindent (make-symbol "bindent")))
1080
    `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
Stefan Monnier's avatar
Stefan Monnier committed
1081
       (save-restriction
1082
	 (narrow-to-region ,beg ,end)
Stefan Monnier's avatar
Stefan Monnier committed
1083 1084 1085 1086 1087 1088 1089 1090 1091
	 (goto-char (point-min))
	 (insert (make-string ,bindent ? ))
	 (prog1
	     (progn ,@body)
	   ;; remove the bindent
	   (save-excursion
	     (goto-char (point-min))
	     (when (looking-at " *")
	       (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
1092
		 (delete-char n)
Stefan Monnier's avatar
Stefan Monnier committed
1093 1094 1095 1096 1097 1098 1099 1100 1101
		 (setq ,bindent (- ,bindent n))))
	     (end-of-line)
	     (let ((e (point)))
	       (beginning-of-line)
	       (while (and (> ,bindent 0) (re-search-forward "   *" e t))
		 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
		   (goto-char (match-beginning 0))
		   (delete-char n)
		   (setq ,bindent (- ,bindent n)))))))))))
1102

1103
(defun comment-add (arg)
1104 1105
  "Compute the number of extra comment starter characters.
\(Extra semicolons in Lisp mode, extra stars in C mode, etc.)
1106 1107 1108
If ARG is non-nil, just follow ARG.
If the comment starter is multi-char, just follow ARG.
Otherwise obey `comment-add'."
Stefan Monnier's avatar
Stefan Monnier committed
1109
  (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
1110
      (* comment-add 1)
Stefan Monnier's avatar
Stefan Monnier committed
1111 1112
    (1- (prefix-numeric-value arg))))

1113
(defun comment-region-internal (beg end cs ce
1114
                                &optional ccs cce block lines indent)
1115
  "Comment region BEG .. END.
1116 1117 1118 1119 1120 1121 1122 1123 1124
CS and CE are the comment start string and comment end string,
respectively.  CCS and CCE are the comment continuation strings
for the start and end of lines, respectively (default to CS and CE).
BLOCK indicates that end of lines should be marked with either CCE,
CE or CS \(if CE is empty) and that those markers should be aligned.
LINES indicates that an extra lines will be used at the beginning
and end 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."
Stefan Monnier's avatar
Stefan Monnier committed
1125
  ;;(assert (< beg end))
1126
  (let ((no-empty (not (or (eq comment-empty-lines t)
1127 1128
			   (and comment-empty-lines (zerop (length ce))))))
	ce-sanitized)
1129
    ;; Sanitize CE and CCE.
Stefan Monnier's avatar
Stefan Monnier committed
1130
    (if (and (stringp ce) (string= "" ce)) (setq ce nil))
1131
    (setq ce-sanitized ce)
Stefan Monnier's avatar
Stefan Monnier committed
1132
    (if (and (stringp cce) (string= "" cce)) (setq cce nil))
1133 1134 1135
    ;; If CE is empty, multiline cannot be used.
    (unless ce (setq ccs nil cce nil))
    ;; Should we mark empty lines as well ?
Stefan Monnier's avatar
Stefan Monnier committed
1136
    (if (or ccs block lines) (setq no-empty nil))
1137
    ;; Make sure we have end-markers for BLOCK mode.
1138
    (when block (unless ce (setq ce (comment-string-reverse cs))))
1139 1140 1141 1142
    ;; If BLOCK is not requested, we don't need CCE.
    (unless block (setq cce nil))
    ;; Continuation defaults to the same as CS and CE.
    (unless ccs (setq ccs cs cce ce))
1143

Stefan Monnier's avatar
Stefan Monnier committed
1144
    (save-excursion
1145
      (goto-char end)
1146 1147
      ;; If the end is not at the end of a line and the comment-end
      ;; is implicit (i.e. a newline), explicitly insert a newline.
1148
      (unless (or ce-sanitized (eolp)) (insert "\n") (indent-according-to-mode))
1149
      (comment-with-narrowing beg end
1150
	(let ((min-indent (point-max))
1151
	      (max-indent 0))
Stefan Monnier's avatar
Stefan Monnier committed
1152
	  (goto-char (point-min))
1153 1154 1155 1156
	  ;; Quote any nested comment marker
	  (comment-quote-nested comment-start comment-end nil)

	  ;; Loop over all lines to find the needed indentations.
1157
	  (goto-char (point-min))
1158 1159 1160 1161 1162 1163 1164
	  (while
	      (progn
		(unless (looking-at "[ \t]*$")
		  (setq min-indent (min min-indent (current-indentation))))
		(end-of-line)
		(setq max-indent (max max-indent (current-column)))
		(not (or (eobp) (progn (forward-line) nil)))))
1165

Stefan Monnier's avatar
Stefan Monnier committed
1166
	  (setq max-indent
1167 1168 1169 1170