(Equality Predicates): Null strings are uniquified.
[bpt/emacs.git] / lisp / newcomment.el
CommitLineData
83b96b22
SM
1;;; newcomment.el --- (un)comment regions of buffers
2
c90f2757 3;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
d7a0267c 4;; 2005, 2006, 2007 Free Software Foundation, Inc.
83b96b22 5
59a1ce8d 6;; Author: code extracted from Emacs-20's simple.el
e8bf8343 7;; Maintainer: Stefan Monnier <monnier@iro.umontreal.ca>
83b96b22 8;; Keywords: comment uncomment
83b96b22 9
59a1ce8d
SM
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
83b96b22 13;; it under the terms of the GNU General Public License as published by
b4aa6026 14;; the Free Software Foundation; either version 3, or (at your option)
59a1ce8d
SM
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
83b96b22
SM
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
59a1ce8d 21
83b96b22 22;; You should have received a copy of the GNU General Public License
59a1ce8d 23;; along with GNU Emacs; see the file COPYING. If not, write to the
086add15
LK
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
83b96b22
SM
26
27;;; Commentary:
28
771c9b97 29;; A replacement for simple.el's comment-related functions.
83b96b22
SM
30
31;;; Bugs:
32
3674a4a9
SM
33;; - boxed comments in Perl are not properly uncommented because they are
34;; uncommented one-line at a time.
75e95a97 35;; - nested comments in sgml-mode are not properly quoted.
2ab98065
SM
36;; - single-char nestable comment-start can only do the "\\s<+" stuff
37;; if the corresponding closing marker happens to be right.
3e569d22
SM
38;; - uncomment-region with a numeric argument can render multichar
39;; comment markers invalid.
3fc5b4e2
SM
40;; - comment-indent or comment-region when called inside a comment
41;; will happily break the surrounding comment.
42;; - comment-quote-nested will not (un)quote properly all nested comment
43;; markers if there are more than just comment-start and comment-end.
44;; For example, in Pascal where {...*) and (*...} are possible.
83b96b22
SM
45
46;;; Todo:
47
3674a4a9
SM
48;; - rebox.el-style refill.
49;; - quantized steps in comment-alignment.
50;; - try to align tail comments.
51;; - check what c-comment-line-break-function has to say.
52;; - spill auto-fill of comments onto the end of the next line.
7a0a180a 53;; - uncomment-region with a consp (for blocks) or somehow make the
3674a4a9
SM
54;; deletion of continuation markers less dangerous.
55;; - drop block-comment-<foo> unless it's really used.
56;; - uncomment-region on a subpart of a comment.
57;; - support gnu-style "multi-line with space in continue".
771c9b97
SM
58;; - somehow allow comment-dwim to use the region even if transient-mark-mode
59;; is not turned on.
83b96b22 60
bdbe3a89
SM
61;; - when auto-filling a comment, try to move the comment to the left
62;; rather than break it (if possible).
63;; - sometimes default the comment-column to the same
64;; one used on the preceding line(s).
65
83b96b22
SM
66;;; Code:
67
be83ecb2 68;;;###autoload
59a1ce8d 69(defalias 'indent-for-comment 'comment-indent)
be83ecb2 70;;;###autoload
59a1ce8d 71(defalias 'set-comment-column 'comment-set-column)
be83ecb2 72;;;###autoload
59a1ce8d 73(defalias 'kill-comment 'comment-kill)
be83ecb2 74;;;###autoload
59a1ce8d 75(defalias 'indent-new-comment-line 'comment-indent-new-line)
83b96b22 76
3e569d22
SM
77(defgroup comment nil
78 "Indenting and filling of comments."
79 :prefix "comment-"
ac87b3a9 80 :version "21.1"
3e569d22
SM
81 :group 'fill)
82
75975685
RS
83;; Autoload this to avoid warnings, since some major modes define it.
84;;;###autoload
771c9b97
SM
85(defvar comment-use-syntax 'undecided
86 "Non-nil if syntax-tables can be used instead of regexps.
87Can also be `undecided' which means that a somewhat expensive test will
88be used to try to determine whether syntax-tables should be trusted
f5215400
SM
89to understand comments or not in the given buffer.
90Major modes should set this variable.")
2ab98065 91
88fe06af
SM
92(defcustom comment-fill-column nil
93 "Column to use for `comment-indent'. If nil, use `fill-column' instead."
f5307782
JB
94 :type '(choice (const nil) integer)
95 :group 'comment)
88fe06af 96
be83ecb2 97;;;###autoload
83b96b22 98(defcustom comment-column 32
ae2c9c21 99 "Column to indent right-margin comments to.
2ed8e1f7 100Each mode may establish a different default value for this variable; you
a704fec0 101can set the value for a particular mode using that mode's hook.
2ed8e1f7
SM
102Comments might be indented to a different value in order not to go beyond
103`comment-fill-column' or in order to align them with surrounding comments."
f5307782
JB
104 :type 'integer
105 :group 'comment)
83b96b22 106(make-variable-buffer-local 'comment-column)
631c8020 107;;;###autoload(put 'comment-column 'safe-local-variable 'integerp)
83b96b22 108
be83ecb2 109;;;###autoload
f5215400
SM
110(defvar comment-start nil
111 "*String to insert to start a new comment, or nil if no comment syntax.")
be2c62b3 112;;;###autoload(put 'comment-start 'safe-local-variable 'string-or-null-p)
83b96b22 113
be83ecb2 114;;;###autoload
f5215400 115(defvar comment-start-skip nil
83b96b22
SM
116 "*Regexp to match the start of a comment plus everything up to its body.
117If there are any \\(...\\) pairs, the comment delimiter text is held to begin
f5215400 118at the place matched by the close of the first pair.")
be2c62b3 119;;;###autoload(put 'comment-start-skip 'safe-local-variable 'string-or-null-p)
771c9b97 120
be83ecb2 121;;;###autoload
3e569d22
SM
122(defvar comment-end-skip nil
123 "Regexp to match the end of a comment plus everything up to its body.")
be2c62b3 124;;;###autoload(put 'comment-end-skip 'safe-local-variable 'string-or-null-p)
83b96b22 125
be83ecb2 126;;;###autoload
f5215400 127(defvar comment-end ""
83b96b22 128 "*String to insert to end a new comment.
f5215400 129Should be an empty string if comments are terminated by end-of-line.")
be2c62b3 130;;;###autoload(put 'comment-end 'safe-local-variable 'string-or-null-p)
83b96b22 131
be83ecb2 132;;;###autoload
87cf8421 133(defvar comment-indent-function 'comment-indent-default
83b96b22
SM
134 "Function to compute desired indentation for a comment.
135This function is called with no args with point at the beginning of
87cf8421
SM
136the comment's starting delimiter and should return either the desired
137column indentation or nil.
138If nil is returned, indentation is delegated to `indent-according-to-mode'.")
83b96b22 139
a71b3805
EZ
140;;;###autoload
141(defvar comment-insert-comment-function nil
142 "Function to insert a comment when a line doesn't contain one.
143The function has no args.
144
145Applicable at least in modes for languages like fixed-format Fortran where
146comments always start in column zero.")
147
b70dd952 148(defvar comment-region-function 'comment-region-default
a71b3805
EZ
149 "Function to comment a region.
150Its args are the same as those of `comment-region', but BEG and END are
151guaranteed to be correctly ordered. It is called within `save-excursion'.
152
153Applicable at least in modes for languages like fixed-format Fortran where
154comments always start in column zero.")
155
b70dd952 156(defvar uncomment-region-function 'uncomment-region-default
a71b3805
EZ
157 "Function to uncomment a region.
158Its args are the same as those of `uncomment-region', but BEG and END are
159guaranteed to be correctly ordered. It is called within `save-excursion'.
160
161Applicable at least in modes for languages like fixed-format Fortran where
162comments always start in column zero.")
163
164;; ?? never set
3e569d22
SM
165(defvar block-comment-start nil)
166(defvar block-comment-end nil)
83b96b22 167
771c9b97
SM
168(defvar comment-quote-nested t
169 "Non-nil if nested comments should be quoted.
170This should be locally set by each major mode if needed.")
171
172(defvar comment-continue nil
f5215400
SM
173 "Continuation string to insert for multiline comments.
174This string will be added at the beginning of each line except the very
175first one when commenting a region with a commenting style that allows
176comments to span several lines.
177It should generally have the same length as `comment-start' in order to
178preserve indentation.
179If it is nil a value will be automatically derived from `comment-start'
180by replacing its first character with a space.")
181
771c9b97 182(defvar comment-add 0
f5215400
SM
183 "How many more comment chars should be inserted by `comment-region'.
184This determines the default value of the numeric argument of `comment-region'.
185This should generally stay 0, except for a few modes like Lisp where
186it can be convenient to set it to 1 so that regions are commented with
187two semi-colons.")
2ab98065 188
2ab98065 189(defconst comment-styles
771c9b97
SM
190 '((plain . (nil nil nil nil))
191 (indent . (nil nil nil t))
192 (aligned . (nil t nil t))
193 (multi-line . (t nil nil t))
194 (extra-line . (t nil t t))
9b0d1d6e
SM
195 (box . (nil t t t))
196 (box-multi . (t t t t)))
5266b06b 197 "Comment region styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
f5215400
SM
198STYLE should be a mnemonic symbol.
199MULTI specifies that comments are allowed to span multiple lines.
200ALIGN specifies that the `comment-end' markers should be aligned.
201EXTRA specifies that an extra line should be used before and after the
202 region to comment (to put the `comment-end' and `comment-start').
203INDENT specifies that the `comment-start' markers should not be put at the
204 left margin but at the current indentation of the region to comment.")
205
be83ecb2 206;;;###autoload
f5215400 207(defcustom comment-style 'plain
ae2c9c21 208 "Style to be used for `comment-region'.
f5215400 209See `comment-styles' for a list of available styles."
be83ecb2 210 :type (if (boundp 'comment-styles)
5266b06b
RS
211 `(choice ,@(mapcar (lambda (s) `(const ,(car s)))
212 comment-styles))
f5307782
JB
213 'symbol)
214 :group 'comment)
2ab98065 215
be83ecb2
SM
216;;;###autoload
217(defcustom comment-padding " "
f5215400
SM
218 "Padding string that `comment-region' puts between comment chars and text.
219Can also be an integer which will be automatically turned into a string
220of the corresponding number of spaces.
2ab98065
SM
221
222Extra spacing between the comment characters and the comment text
0603917d 223makes the comment easier to read. Default is 1. nil means 0."
f5307782
JB
224 :type '(choice string integer (const nil))
225 :group 'comment)
2ab98065 226
be83ecb2 227;;;###autoload
3e569d22 228(defcustom comment-multi-line nil
ae2c9c21 229 "Non-nil means `comment-indent-new-line' continues comments.
269a8f1c
LT
230That is, it inserts no new terminator or starter.
231This affects `auto-fill-mode', which is the main reason to
232customize this variable.
233
234It also affects \\[indent-new-comment-line]. However, if you want this
235behavior for explicit filling, you might as well use \\[newline-and-indent]."
f5307782
JB
236 :type 'boolean
237 :group 'comment)
3e569d22 238
6976bf99
SM
239(defcustom comment-empty-lines nil
240 "If nil, `comment-region' does not comment out empty lines.
241If t, it always comments out empty lines.
e29d96b6 242If `eol' it only comments out empty lines if comments are
6976bf99
SM
243terminated by the end of line (i.e. `comment-end' is empty)."
244 :type '(choice (const :tag "Never" nil)
245 (const :tag "Always" t)
f5307782
JB
246 (const :tag "EOl-terminated" 'eol))
247 :group 'comment)
6976bf99 248
2ab98065
SM
249;;;;
250;;;; Helpers
251;;;;
252
f5215400
SM
253(defun comment-string-strip (str beforep afterp)
254 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
255 (string-match (concat "\\`" (if beforep "\\s-*")
ad679e45 256 "\\(.*?\\)" (if afterp "\\s-*\n?")
2ab98065
SM
257 "\\'") str)
258 (match-string 1 str))
259
260(defun comment-string-reverse (s)
f5215400 261 "Return the mirror image of string S, without any trailing space."
771c9b97 262 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
2ab98065 263
7164ef13 264;;;###autoload
2ab98065 265(defun comment-normalize-vars (&optional noerror)
0f21c5a0
SM
266 "Check and setup the variables needed by other commenting functions.
267Functions autoloaded from newcomment.el, being entry points, should call
268this function before any other, so the rest of the code can assume that
269the variables are properly set."
0d6a08f6
SM
270 (unless (and (not comment-start) noerror)
271 (unless comment-start
31df2900
SM
272 (let ((cs (read-string "No comment syntax is defined. Use: ")))
273 (if (zerop (length cs))
274 (error "No comment syntax defined")
275 (set (make-local-variable 'comment-start) cs))))
2ab98065 276 ;; comment-use-syntax
771c9b97 277 (when (eq comment-use-syntax 'undecided)
2ab98065
SM
278 (set (make-local-variable 'comment-use-syntax)
279 (let ((st (syntax-table))
280 (cs comment-start)
281 (ce (if (string= "" comment-end) "\n" comment-end)))
771c9b97
SM
282 ;; Try to skip over a comment using forward-comment
283 ;; to see if the syntax tables properly recognize it.
2ab98065
SM
284 (with-temp-buffer
285 (set-syntax-table st)
286 (insert cs " hello " ce)
287 (goto-char (point-min))
288 (and (forward-comment 1) (eobp))))))
2ab98065 289 ;; comment-padding
9145f1c2 290 (unless comment-padding (setq comment-padding 0))
2ab98065
SM
291 (when (integerp comment-padding)
292 (setq comment-padding (make-string comment-padding ? )))
293 ;; comment markers
294 ;;(setq comment-start (comment-string-strip comment-start t nil))
295 ;;(setq comment-end (comment-string-strip comment-end nil t))
296 ;; comment-continue
f5215400 297 (unless (or comment-continue (string= comment-end ""))
2ab98065 298 (set (make-local-variable 'comment-continue)
9b0d1d6e 299 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
7164ef13
SM
300 (substring comment-start 1)))
301 ;; Hasn't been necessary yet.
302 ;; (unless (string-match comment-start-skip comment-continue)
016c63b6 303 ;; (kill-local-variable 'comment-continue))
7164ef13 304 )
2ab98065 305 ;; comment-skip regexps
f23a0f3a
SM
306 (unless (and comment-start-skip
307 ;; In case comment-start has changed since last time.
308 (string-match comment-start-skip comment-start))
2ab98065 309 (set (make-local-variable 'comment-start-skip)
f0a478be 310 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
2ab98065 311 (regexp-quote (comment-string-strip comment-start t t))
75ed43a6
SM
312 ;; Let's not allow any \s- but only [ \t] since \n
313 ;; might be both a comment-end marker and \s-.
314 "+\\)[ \t]*")))
f23a0f3a
SM
315 (unless (and comment-end-skip
316 ;; In case comment-end has changed since last time.
317 (string-match comment-end-skip comment-end))
2ab98065
SM
318 (let ((ce (if (string= "" comment-end) "\n"
319 (comment-string-strip comment-end t t))))
320 (set (make-local-variable 'comment-end-skip)
37dbd369
SM
321 ;; We use [ \t] rather than \s- because we don't want to
322 ;; remove ^L in C mode when uncommenting.
323 (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
2ab98065 324 "\\|" (regexp-quote (substring ce 0 1))
771c9b97 325 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
2ab98065
SM
326 (regexp-quote (substring ce 1))
327 "\\)"))))))
f1180544 328
f5215400
SM
329(defun comment-quote-re (str unp)
330 (concat (regexp-quote (substring str 0 1))
331 "\\\\" (if unp "+" "*")
332 (regexp-quote (substring str 1))))
333
334(defun comment-quote-nested (cs ce unp)
335 "Quote or unquote nested comments.
336If UNP is non-nil, unquote nested comment markers."
337 (setq cs (comment-string-strip cs t t))
338 (setq ce (comment-string-strip ce t t))
339 (when (and comment-quote-nested (> (length ce) 0))
340 (let ((re (concat (comment-quote-re ce unp)
341 "\\|" (comment-quote-re cs unp))))
342 (goto-char (point-min))
343 (while (re-search-forward re nil t)
344 (goto-char (match-beginning 0))
345 (forward-char 1)
346 (if unp (delete-char 1) (insert "\\"))
347 (when (= (length ce) 1)
348 ;; If the comment-end is a single char, adding a \ after that
349 ;; "first" char won't deactivate it, so we turn such a CE
350 ;; into !CS. I.e. for pascal, we turn } into !{
351 (if (not unp)
352 (when (string= (match-string 0) ce)
353 (replace-match (concat "!" cs) t t))
354 (when (and (< (point-min) (match-beginning 0))
355 (string= (buffer-substring (1- (match-beginning 0))
356 (1- (match-end 0)))
357 (concat "!" cs)))
358 (backward-char 2)
359 (delete-char (- (match-end 0) (match-beginning 0)))
360 (insert ce))))))))
2ab98065
SM
361
362;;;;
363;;;; Navigation
364;;;;
365
f5f95edf
SM
366(defvar comment-use-global-state nil
367 "Non-nil means that the global syntactic context is used.
368More specifically, it means that `syntax-ppss' is used to find out whether
369point is within a string or not. Major modes whose syntax is faithfully
370described by the syntax-tables can set this to non-nil so comment markers
371in strings will not confuse Emacs.")
372
ad679e45 373(defun comment-search-forward (limit &optional noerror)
771c9b97
SM
374 "Find a comment start between point and LIMIT.
375Moves point to inside the comment and returns the position of the
376comment-starter. If no comment is found, moves point to LIMIT
11a26e05 377and raises an error or returns nil if NOERROR is non-nil."
2ab98065 378 (if (not comment-use-syntax)
9b0d1d6e
SM
379 (if (re-search-forward comment-start-skip limit noerror)
380 (or (match-end 1) (match-beginning 0))
381 (goto-char limit)
382 (unless noerror (error "No comment")))
ad679e45
SM
383 (let* ((pt (point))
384 ;; Assume (at first) that pt is outside of any string.
f5f95edf
SM
385 (s (parse-partial-sexp pt (or limit (point-max)) nil nil
386 (if comment-use-global-state (syntax-ppss pt))
387 t)))
388 (when (and (nth 8 s) (nth 3 s) (not comment-use-global-state))
b70dd952
SM
389 ;; The search ended at eol inside a string. Try to see if it
390 ;; works better when we assume that pt is inside a string.
391 (setq s (parse-partial-sexp
392 pt (or limit (point-max)) nil nil
393 (list nil nil nil (nth 3 s) nil nil nil nil)
394 t)))
5605893d
SM
395 (if (or (not (and (nth 8 s) (not (nth 3 s))))
396 ;; Make sure the comment starts after PT.
397 (< (nth 8 s) pt))
ad679e45
SM
398 (unless noerror (error "No comment"))
399 ;; We found the comment.
9b0d1d6e 400 (let ((pos (point))
ad679e45 401 (start (nth 8 s))
9b0d1d6e 402 (bol (line-beginning-position))
ad679e45
SM
403 (end nil))
404 (while (and (null end) (>= (point) bol))
405 (if (looking-at comment-start-skip)
406 (setq end (min (or limit (point-max)) (match-end 0)))
407 (backward-char)))
9b0d1d6e 408 (goto-char (or end pos))
ad679e45 409 start)))))
2ab98065
SM
410
411(defun comment-search-backward (&optional limit noerror)
412 "Find a comment start between LIMIT and point.
771c9b97
SM
413Moves point to inside the comment and returns the position of the
414comment-starter. If no comment is found, moves point to LIMIT
11a26e05 415and raises an error or returns nil if NOERROR is non-nil."
ad679e45
SM
416 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
417 ;; stop there. This can be rather bad in general, but since
418 ;; comment-search-backward is only used to find the comment-column (in
419 ;; comment-set-column) and to find the comment-start string (via
420 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
2ab98065
SM
421 (if (not (re-search-backward comment-start-skip limit t))
422 (unless noerror (error "No comment"))
423 (beginning-of-line)
424 (let* ((end (match-end 0))
425 (cs (comment-search-forward end t))
426 (pt (point)))
427 (if (not cs)
428 (progn (beginning-of-line)
429 (comment-search-backward limit noerror))
430 (while (progn (goto-char cs)
431 (comment-forward)
432 (and (< (point) end)
433 (setq cs (comment-search-forward end t))))
434 (setq pt (point)))
435 (goto-char pt)
436 cs))))
437
438(defun comment-beginning ()
771c9b97
SM
439 "Find the beginning of the enclosing comment.
440Returns nil if not inside a comment, else moves point and returns
2308f447 441the same as `comment-search-backward'."
75ed43a6
SM
442 ;; HACK ATTACK!
443 ;; We should really test `in-string-p' but that can be expensive.
444 (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
445 (let ((pt (point))
446 (cs (comment-search-backward nil t)))
447 (when cs
448 (if (save-excursion
449 (goto-char cs)
dde6824c
SM
450 (and
451 ;; For modes where comment-start and comment-end are the same,
452 ;; the search above may have found a `ce' rather than a `cs'.
2308f447 453 (or (if comment-end-skip (not (looking-at comment-end-skip)))
dde6824c
SM
454 ;; Maybe font-lock knows that it's a `cs'?
455 (eq (get-text-property (match-end 0) 'face)
456 'font-lock-comment-face)
457 (unless (eq (get-text-property (point) 'face)
458 'font-lock-comment-face)
459 ;; Let's assume it's a `cs' if we're on the same line.
460 (>= (line-end-position) pt)))
461 ;; Make sure that PT is not past the end of the comment.
462 (if (comment-forward 1) (> (point) pt) (eobp))))
75ed43a6
SM
463 cs
464 (goto-char pt)
465 nil)))))
2ab98065
SM
466
467(defun comment-forward (&optional n)
468 "Skip forward over N comments.
469Just like `forward-comment' but only for positive N
470and can use regexps instead of syntax."
471 (setq n (or n 1))
472 (if (< n 0) (error "No comment-backward")
473 (if comment-use-syntax (forward-comment n)
474 (while (> n 0)
59a1ce8d 475 (setq n
0f38a885
SM
476 (if (or (forward-comment 1)
477 (and (looking-at comment-start-skip)
478 (goto-char (match-end 0))
479 (re-search-forward comment-end-skip nil 'move)))
59a1ce8d 480 (1- n) -1)))
2ab98065
SM
481 (= n 0))))
482
483(defun comment-enter-backward ()
484 "Move from the end of a comment to the end of its content.
771c9b97 485Point is assumed to be just at the end of a comment."
2ab98065
SM
486 (if (bolp)
487 ;; comment-end = ""
488 (progn (backward-char) (skip-syntax-backward " "))
3cc4b076
SM
489 (cond
490 ((save-restriction
1cb40089
SM
491 (narrow-to-region (line-beginning-position) (point))
492 (goto-char (point-min))
3cc4b076
SM
493 (re-search-forward (concat comment-end-skip "\\'") nil t))
494 (goto-char (match-beginning 0)))
2ed8e1f7
SM
495 ;; comment-end-skip not found probably because it was not set
496 ;; right. Since \\s> should catch the single-char case, let's
497 ;; check that we're looking at a two-char comment ender.
498 ((not (or (<= (- (point-max) (line-beginning-position)) 1)
499 (zerop (logand (car (syntax-after (- (point) 1)))
500 ;; Here we take advantage of the fact that
501 ;; the syntax class " " is encoded to 0,
502 ;; so " 4" gives us just the 4 bit.
503 (car (string-to-syntax " 4"))))
504 (zerop (logand (car (syntax-after (- (point) 2)))
505 (car (string-to-syntax " 3"))))))
3cc4b076
SM
506 (backward-char 2)
507 (skip-chars-backward (string (char-after)))
2ed8e1f7
SM
508 (skip-syntax-backward " "))
509 ;; No clue what's going on: maybe we're really not right after the
510 ;; end of a comment. Maybe we're at the "end" because of EOB rather
511 ;; than because of a marker.
512 (t (skip-syntax-backward " ")))))
2ab98065
SM
513
514;;;;
515;;;; Commands
516;;;;
517
fae99944 518;;;###autoload
87cf8421
SM
519(defun comment-indent-default ()
520 "Default for `comment-indent-function'."
d3fcda22
SM
521 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
522 (or (match-end 1) (/= (current-column) (current-indentation))))
523 0
87cf8421 524 (when (or (/= (current-column) (current-indentation))
8c39e595 525 (and (> comment-add 0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
87cf8421
SM
526 comment-column)))
527
2ed8e1f7
SM
528(defun comment-choose-indent (&optional indent)
529 "Choose the indentation to use for a right-hand-side comment.
530The criteria are (in this order):
531- try to keep the comment's text within `comment-fill-column'.
532- try to align with surrounding comments.
533- prefer INDENT (or `comment-column' if nil).
534Point is expected to be at the start of the comment."
535 (unless indent (setq indent comment-column))
536 ;; Avoid moving comments past the fill-column.
537 (let ((max (+ (current-column)
538 (- (or comment-fill-column fill-column)
539 (save-excursion (end-of-line) (current-column)))))
540 (other nil)
541 (min (save-excursion (skip-chars-backward " \t")
542 (1+ (current-column)))))
543 ;; Fix up the range.
544 (if (< max min) (setq max min))
545 ;; Don't move past the fill column.
546 (if (<= max indent) (setq indent max))
547 ;; We can choose anywhere between min..max.
548 ;; Let's try to align to a comment on the previous line.
549 (save-excursion
550 (when (and (zerop (forward-line -1))
551 (setq other (comment-search-forward
552 (line-end-position) t)))
553 (goto-char other) (setq other (current-column))))
554 (if (and other (<= other max) (>= other min))
555 ;; There is a comment and it's in the range: bingo!
556 other
557 ;; Can't align to a previous comment: let's try to align to comments
558 ;; on the following lines, then. These have not been re-indented yet,
559 ;; so we can't directly align ourselves with them. All we do is to try
560 ;; and choose an indentation point with which they will be able to
561 ;; align themselves.
562 (save-excursion
563 (while (and (zerop (forward-line 1))
564 (setq other (comment-search-forward
565 (line-end-position) t)))
566 (goto-char other)
567 (let ((omax (+ (current-column)
568 (- (or comment-fill-column fill-column)
569 (save-excursion (end-of-line) (current-column)))))
570 (omin (save-excursion (skip-chars-backward " \t")
571 (1+ (current-column)))))
572 (if (and (>= omax min) (<= omin max))
573 (progn (setq min (max omin min))
574 (setq max (min omax max)))
575 ;; Can't align with this anyway, so exit the loop.
576 (goto-char (point-max))))))
577 ;; Return the closest point to indent within min..max.
578 (max min (min max indent)))))
579
be83ecb2 580;;;###autoload
3e569d22 581(defun comment-indent (&optional continue)
a71b3805 582 "Indent this line's comment to `comment-column', or insert an empty comment.
dde6824c 583If CONTINUE is non-nil, use the `comment-continue' markers if any."
83b96b22 584 (interactive "*")
ad679e45 585 (comment-normalize-vars)
83b96b22
SM
586 (let* ((empty (save-excursion (beginning-of-line)
587 (looking-at "[ \t]*$")))
f5215400 588 (starter (or (and continue comment-continue)
2ab98065 589 (and empty block-comment-start) comment-start))
f5215400 590 (ender (or (and continue comment-continue "")
2ab98065 591 (and empty block-comment-end) comment-end)))
2e1fbba4
SM
592 (unless starter (error "No comment syntax defined"))
593 (beginning-of-line)
594 (let* ((eolpos (line-end-position))
595 (begpos (comment-search-forward eolpos t))
596 cpos indent)
597 ;; An existing comment?
7a06b250
SM
598 (if begpos
599 (progn
600 (if (and (not (looking-at "[\t\n ]"))
601 (looking-at comment-end-skip))
602 ;; The comment is empty and we have skipped all its space
603 ;; and landed right before the comment-ender:
604 ;; Go back to the middle of the space.
605 (forward-char (/ (skip-chars-backward " \t") -2)))
606 (setq cpos (point-marker)))
2e1fbba4 607 ;; If none, insert one.
a71b3805
EZ
608 (if comment-insert-comment-function
609 (funcall comment-insert-comment-function)
2e1fbba4 610 (save-excursion
a71b3805
EZ
611 ;; Some `comment-indent-function's insist on not moving
612 ;; comments that are in column 0, so we first go to the
613 ;; likely target column.
567e961e 614 (indent-to comment-column)
e6bba95e
DL
615 ;; Ensure there's a space before the comment for things
616 ;; like sh where it matters (as well as being neater).
7c0bbe7f
JB
617 (unless (memq (char-before) '(nil ?\n ?\t ?\s))
618 (insert ?\s))
07f10bab 619 (setq begpos (point))
bb304a7a 620 (insert starter)
2e1fbba4 621 (setq cpos (point-marker))
a71b3805 622 (insert ender))))
2e1fbba4
SM
623 (goto-char begpos)
624 ;; Compute desired indent.
053b8d35 625 (setq indent (save-excursion (funcall comment-indent-function)))
8cc313a3
SM
626 ;; If `indent' is nil and there's code before the comment, we can't
627 ;; use `indent-according-to-mode', so we default to comment-column.
628 (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
629 (setq indent comment-column))
2e1fbba4 630 (if (not indent)
bfe6e13f 631 ;; comment-indent-function refuses: delegate to line-indent.
2e1fbba4 632 (indent-according-to-mode)
2ed8e1f7 633 ;; If the comment is at the right of code, adjust the indentation.
a764440a 634 (unless (save-excursion (skip-chars-backward " \t") (bolp))
2ed8e1f7 635 (setq indent (comment-choose-indent indent)))
b605a60a
RS
636 ;; Update INDENT to leave at least one space
637 ;; after other nonwhite text on the line.
638 (save-excursion
016c63b6 639 (skip-chars-backward " \t")
b605a60a
RS
640 (unless (bolp)
641 (setq indent (max indent (1+ (current-column))))))
642 ;; If that's different from comment's current position, change it.
7164ef13 643 (unless (= (current-column) indent)
7164ef13 644 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
b605a60a 645 (indent-to indent)))
2e1fbba4
SM
646 (goto-char cpos)
647 (set-marker cpos nil))))
83b96b22 648
be83ecb2 649;;;###autoload
3e569d22 650(defun comment-set-column (arg)
83b96b22 651 "Set the comment column based on point.
2ab98065 652With no ARG, set the comment column to the current column.
83b96b22
SM
653With just minus as arg, kill any comment on this line.
654With any other arg, set comment column to indentation of the previous comment
655 and then align or create a comment on this line at that column."
656 (interactive "P")
e8fe7d39 657 (cond
ad679e45 658 ((eq arg '-) (comment-kill nil))
e8fe7d39 659 (arg
2abd0306 660 (comment-normalize-vars)
e8fe7d39
SM
661 (save-excursion
662 (beginning-of-line)
2ab98065 663 (comment-search-backward)
e8fe7d39 664 (beginning-of-line)
ad679e45 665 (goto-char (comment-search-forward (line-end-position)))
83b96b22 666 (setq comment-column (current-column))
e8fe7d39 667 (message "Comment column set to %d" comment-column))
ad679e45 668 (comment-indent))
e8fe7d39 669 (t (setq comment-column (current-column))
83b96b22
SM
670 (message "Comment column set to %d" comment-column))))
671
be83ecb2 672;;;###autoload
3e569d22 673(defun comment-kill (arg)
7a0a180a
SM
674 "Kill the comment on this line, if any.
675With prefix ARG, kill comments on that many lines starting with this one."
676 (interactive "P")
2abd0306 677 (comment-normalize-vars)
ad679e45
SM
678 (dotimes (_ (prefix-numeric-value arg))
679 (save-excursion
680 (beginning-of-line)
681 (let ((cs (comment-search-forward (line-end-position) t)))
682 (when cs
683 (goto-char cs)
684 (skip-syntax-backward " ")
685 (setq cs (point))
686 (comment-forward)
687 (kill-region cs (if (bolp) (1- (point)) (point)))
688 (indent-according-to-mode))))
689 (if arg (forward-line 1))))
7a0a180a 690
2ab98065
SM
691(defun comment-padright (str &optional n)
692 "Construct a string composed of STR plus `comment-padding'.
f5215400 693It also adds N copies of the last non-whitespace chars of STR.
2ab98065 694If STR already contains padding, the corresponding amount is
f5215400
SM
695ignored from `comment-padding'.
696N defaults to 0.
771c9b97 697If N is `re', a regexp is returned instead, that would match
f5215400 698the string for any N."
2ab98065
SM
699 (setq n (or n 0))
700 (when (and (stringp str) (not (string= "" str)))
f5215400 701 ;; Separate the actual string from any leading/trailing padding
3e569d22 702 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
f5215400
SM
703 (let ((s (match-string 1 str)) ;actual string
704 (lpad (substring str 0 (match-beginning 1))) ;left padding
705 (rpad (concat (substring str (match-end 1)) ;original right padding
706 (substring comment-padding ;additional right padding
3e569d22 707 (min (- (match-end 0) (match-end 1))
9b0d1d6e
SM
708 (length comment-padding)))))
709 ;; We can only duplicate C if the comment-end has multiple chars
710 ;; or if comments can be nested, else the comment-end `}' would
711 ;; be turned into `}}}' where only the first ends the comment
712 ;; and the rest becomes bogus junk.
713 (multi (not (and comment-quote-nested
714 ;; comment-end is a single char
715 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
f5215400 716 (if (not (symbolp n))
9b0d1d6e 717 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
f5215400
SM
718 ;; construct a regexp that would match anything from just S
719 ;; to any possible output of this function for any N.
720 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
721 lpad "") ;padding is not required
9b0d1d6e
SM
722 (regexp-quote s)
723 (when multi "+") ;the last char of S might be repeated
f5215400
SM
724 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
725 rpad "")))))) ;padding is not required
2ab98065
SM
726
727(defun comment-padleft (str &optional n)
728 "Construct a string composed of `comment-padding' plus STR.
f5215400 729It also adds N copies of the first non-whitespace chars of STR.
2ab98065 730If STR already contains padding, the corresponding amount is
f5215400
SM
731ignored from `comment-padding'.
732N defaults to 0.
771c9b97 733If N is `re', a regexp is returned instead, that would match
2ab98065
SM
734 the string for any N."
735 (setq n (or n 0))
736 (when (and (stringp str) (not (string= "" str)))
f5215400 737 ;; Only separate the left pad because we assume there is no right pad.
2ab98065
SM
738 (string-match "\\`\\s-*" str)
739 (let ((s (substring str (match-end 0)))
740 (pad (concat (substring comment-padding
741 (min (- (match-end 0) (match-beginning 0))
742 (length comment-padding)))
743 (match-string 0 str)))
f5215400
SM
744 (c (aref str (match-end 0))) ;the first non-space char of STR
745 ;; We can only duplicate C if the comment-end has multiple chars
746 ;; or if comments can be nested, else the comment-end `}' would
747 ;; be turned into `}}}' where only the first ends the comment
748 ;; and the rest becomes bogus junk.
749 (multi (not (and comment-quote-nested
750 ;; comment-end is a single char
751 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
752 (if (not (symbolp n))
753 (concat pad (when multi (make-string n c)) s)
754 ;; Construct a regexp that would match anything from just S
755 ;; to any possible output of this function for any N.
756 ;; We match any number of leading spaces because this regexp will
757 ;; be used for uncommenting where we might want to remove
758 ;; uncomment markers with arbitrary leading space (because
759 ;; they were aligned).
760 (concat "\\s-*"
761 (if multi (concat (regexp-quote (string c)) "*"))
762 (regexp-quote s))))))
83b96b22 763
be83ecb2 764;;;###autoload
7a0a180a 765(defun uncomment-region (beg end &optional arg)
eb0b51f8 766 "Uncomment each line in the BEG .. END region.
f5215400
SM
767The numeric prefix ARG can specify a number of chars to remove from the
768comment markers."
83b96b22
SM
769 (interactive "*r\nP")
770 (comment-normalize-vars)
065b7364 771 (when (> beg end) (setq beg (prog1 end (setq end beg))))
b70dd952
SM
772 ;; Bind `comment-use-global-state' to nil. While uncommenting a region
773 ;; (which works a line at a time), a comment can appear to be
cbdad6e2
EZ
774 ;; included in a mult-line string, but it is actually not.
775 (let ((comment-use-global-state nil))
776 (save-excursion
b70dd952
SM
777 (funcall uncomment-region-function beg end arg))))
778
779(defun uncomment-region-default (beg end &optional arg)
780 "Uncomment each line in the BEG .. END region.
781The numeric prefix ARG can specify a number of chars to remove from the
782comment markers."
783 (goto-char beg)
784 (setq end (copy-marker end))
785 (let* ((numarg (prefix-numeric-value arg))
786 (ccs comment-continue)
787 (srei (comment-padright ccs 're))
788 (csre (comment-padright comment-start 're))
789 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
790 spt)
791 (while (and (< (point) end)
792 (setq spt (comment-search-forward end t)))
793 (let ((ipt (point))
794 ;; Find the end of the comment.
795 (ept (progn
796 (goto-char spt)
797 (unless (or (comment-forward)
798 ;; Allow non-terminated comments.
799 (eobp))
800 (error "Can't find the comment end"))
801 (point)))
802 (box nil)
803 (box-equal nil)) ;Whether we might be using `=' for boxes.
804 (save-restriction
805 (narrow-to-region spt ept)
016c63b6 806
b70dd952
SM
807 ;; Remove the comment-start.
808 (goto-char ipt)
809 (skip-syntax-backward " ")
810 ;; A box-comment starts with a looong comment-start marker.
811 (when (and (or (and (= (- (point) (point-min)) 1)
812 (setq box-equal t)
813 (looking-at "=\\{7\\}")
814 (not (eq (char-before (point-max)) ?\n))
815 (skip-chars-forward "="))
816 (> (- (point) (point-min) (length comment-start)) 7))
817 (> (count-lines (point-min) (point-max)) 2))
818 (setq box t))
819 ;; Skip the padding. Padding can come from comment-padding and/or
820 ;; from comment-start, so we first check comment-start.
821 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
822 (looking-at (regexp-quote comment-padding)))
823 (goto-char (match-end 0)))
824 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
825 (goto-char (match-end 0)))
826 (if (null arg) (delete-region (point-min) (point))
827 (skip-syntax-backward " ")
828 (delete-char (- numarg))
829 (unless (or (bobp)
830 (save-excursion (goto-char (point-min))
831 (looking-at comment-start-skip)))
832 ;; If there's something left but it doesn't look like
833 ;; a comment-start any more, just remove it.
834 (delete-region (point-min) (point))))
016c63b6 835
b70dd952
SM
836 ;; Remove the end-comment (and leading padding and such).
837 (goto-char (point-max)) (comment-enter-backward)
838 ;; Check for special `=' used sometimes in comment-box.
839 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
840 (let ((pos (point)))
841 ;; skip `=' but only if there are at least 7.
842 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
843 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
844 (when (and (bolp) (not (bobp))) (backward-char))
845 (if (null arg) (delete-region (point) (point-max))
846 (skip-syntax-forward " ")
847 (delete-char numarg)
848 (unless (or (eobp) (looking-at comment-end-skip))
849 ;; If there's something left but it doesn't look like
850 ;; a comment-end any more, just remove it.
851 (delete-region (point) (point-max)))))
852
853 ;; Unquote any nested end-comment.
854 (comment-quote-nested comment-start comment-end t)
855
856 ;; Eliminate continuation markers as well.
857 (when sre
858 (let* ((cce (comment-string-reverse (or comment-continue
859 comment-start)))
860 (erei (and box (comment-padleft cce 're)))
861 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
862 (goto-char (point-min))
863 (while (progn
864 (if (and ere (re-search-forward
865 ere (line-end-position) t))
866 (replace-match "" t t nil (if (match-end 2) 2 1))
867 (setq ere nil))
868 (forward-line 1)
869 (re-search-forward sre (line-end-position) t))
870 (replace-match "" t t nil (if (match-end 2) 2 1)))))
871 ;; Go to the end for the next comment.
872 (goto-char (point-max))))))
873 (set-marker end nil))
83b96b22 874
aac88001 875(defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
ad679e45
SM
876 "Make the leading and trailing extra lines.
877This is used for `extra-line' style (or `box' style if BLOCK is specified)."
9b0d1d6e
SM
878 (let ((eindent 0))
879 (if (not block)
880 ;; Try to match CS and CE's content so they align aesthetically.
881 (progn
882 (setq ce (comment-string-strip ce t t))
883 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
884 (setq eindent
885 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
886 0))))
887 ;; box comment
888 (let* ((width (- max-indent min-indent))
889 (s (concat cs "a=m" cce))
890 (e (concat ccs "a=m" ce))
891 (c (if (string-match ".*\\S-\\S-" cs)
3674a4a9
SM
892 (aref cs (1- (match-end 0)))
893 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
894 (aref cs (1- (match-end 0))) ?=)))
895 (re "\\s-*a=m\\s-*")
896 (_ (string-match re s))
897 (lcs (length cs))
9b0d1d6e
SM
898 (fill
899 (make-string (+ width (- (match-end 0)
3674a4a9 900 (match-beginning 0) lcs 3)) c)))
aac88001 901 (setq cs (replace-match fill t t s))
3674a4a9
SM
902 (when (and (not (string-match comment-start-skip cs))
903 (string-match "a=m" s))
904 ;; The whitespace around CS cannot be ignored: put it back.
905 (setq re "a=m")
906 (setq fill (make-string (- width lcs) c))
907 (setq cs (replace-match fill t t s)))
908 (string-match re e)
9b0d1d6e
SM
909 (setq ce (replace-match fill t t e))))
910 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
911 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
aac88001 912
aac88001
SM
913(defmacro comment-with-narrowing (beg end &rest body)
914 "Execute BODY with BEG..END narrowing.
915Space is added (and then removed) at the beginning for the text's
916indentation to be kept as it was before narrowing."
4745e738 917 (declare (debug t) (indent 2))
59a1ce8d 918 (let ((bindent (make-symbol "bindent")))
bfe6e13f 919 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
59a1ce8d 920 (save-restriction
bfe6e13f 921 (narrow-to-region ,beg ,end)
59a1ce8d
SM
922 (goto-char (point-min))
923 (insert (make-string ,bindent ? ))
924 (prog1
925 (progn ,@body)
926 ;; remove the bindent
927 (save-excursion
928 (goto-char (point-min))
929 (when (looking-at " *")
930 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
aac88001 931 (delete-char n)
59a1ce8d
SM
932 (setq ,bindent (- ,bindent n))))
933 (end-of-line)
934 (let ((e (point)))
935 (beginning-of-line)
936 (while (and (> ,bindent 0) (re-search-forward " *" e t))
937 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
938 (goto-char (match-beginning 0))
939 (delete-char n)
940 (setq ,bindent (- ,bindent n)))))))))))
aac88001 941
5266b06b
RS
942;; Compute the number of extra semicolons to add to the comment starter
943;; in Lisp mode, extra stars in C mode, etc.
944;; If ARG is non-nil, just follow ARG.
7f821b79
RS
945;; If the comment-starter is multi-char, just follow ARG.
946;; Otherwise obey comment-add, and double it if EXTRA is non-nil.
5266b06b 947(defun comment-add (arg &optional extra)
b433a560 948 (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
7f821b79 949 (* comment-add (if extra 2 1))
b433a560
SM
950 (1- (prefix-numeric-value arg))))
951
771c9b97 952(defun comment-region-internal (beg end cs ce
aa417798 953 &optional ccs cce block lines indent)
3674a4a9 954 "Comment region BEG .. END.
aa417798
JB
955CS and CE are the comment start string and comment end string,
956respectively. CCS and CCE are the comment continuation strings
957for the start and end of lines, respectively (default to CS and CE).
958BLOCK indicates that end of lines should be marked with either CCE,
959CE or CS \(if CE is empty) and that those markers should be aligned.
960LINES indicates that an extra lines will be used at the beginning
961and end of the region for CE and CS.
962INDENT indicates to put CS and CCS at the current indentation of
963the region rather than at left margin."
59a1ce8d 964 ;;(assert (< beg end))
6976bf99
SM
965 (let ((no-empty (not (or (eq comment-empty-lines t)
966 (and comment-empty-lines (zerop (length ce)))))))
f5215400 967 ;; Sanitize CE and CCE.
83b96b22
SM
968 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
969 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
f5215400
SM
970 ;; If CE is empty, multiline cannot be used.
971 (unless ce (setq ccs nil cce nil))
972 ;; Should we mark empty lines as well ?
83b96b22 973 (if (or ccs block lines) (setq no-empty nil))
f5215400 974 ;; Make sure we have end-markers for BLOCK mode.
2ab98065 975 (when block (unless ce (setq ce (comment-string-reverse cs))))
f5215400
SM
976 ;; If BLOCK is not requested, we don't need CCE.
977 (unless block (setq cce nil))
978 ;; Continuation defaults to the same as CS and CE.
979 (unless ccs (setq ccs cs cce ce))
f1180544 980
83b96b22 981 (save-excursion
aac88001 982 (goto-char end)
f5215400
SM
983 ;; If the end is not at the end of a line and the comment-end
984 ;; is implicit (i.e. a newline), explicitly insert a newline.
aac88001
SM
985 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
986 (comment-with-narrowing beg end
f5215400 987 (let ((min-indent (point-max))
9d5240d2 988 (max-indent 0))
83b96b22 989 (goto-char (point-min))
f5215400
SM
990 ;; Quote any nested comment marker
991 (comment-quote-nested comment-start comment-end nil)
992
993 ;; Loop over all lines to find the needed indentations.
4125ec7e 994 (goto-char (point-min))
f5215400
SM
995 (while
996 (progn
997 (unless (looking-at "[ \t]*$")
998 (setq min-indent (min min-indent (current-indentation))))
999 (end-of-line)
1000 (setq max-indent (max max-indent (current-column)))
1001 (not (or (eobp) (progn (forward-line) nil)))))
f1180544 1002
59a1ce8d 1003 (setq max-indent
45f6a663
SM
1004 (+ max-indent (max (length cs) (length ccs))
1005 ;; Inserting ccs can change max-indent by (1- tab-width)
1006 ;; but only if there are TABs in the boxed text, of course.
1007 (if (save-excursion (goto-char beg)
1008 (search-forward "\t" end t))
1009 (1- tab-width) 0)))
771c9b97 1010 (unless indent (setq min-indent 0))
83b96b22 1011
aac88001 1012 ;; make the leading and trailing lines if requested
83b96b22 1013 (when lines
771c9b97
SM
1014 (let ((csce
1015 (comment-make-extra-lines
1016 cs ce ccs cce min-indent max-indent block)))
1017 (setq cs (car csce))
1018 (setq ce (cdr csce))))
f1180544 1019
83b96b22
SM
1020 (goto-char (point-min))
1021 ;; Loop over all lines from BEG to END.
f5215400
SM
1022 (while
1023 (progn
1024 (unless (and no-empty (looking-at "[ \t]*$"))
1025 (move-to-column min-indent t)
1026 (insert cs) (setq cs ccs) ;switch to CCS after the first line
1027 (end-of-line)
1028 (if (eobp) (setq cce ce))
1029 (when cce
1030 (when block (move-to-column max-indent t))
1031 (insert cce)))
1032 (end-of-line)
1033 (not (or (eobp) (progn (forward-line) nil))))))))))
83b96b22 1034
be83ecb2 1035;;;###autoload
83b96b22
SM
1036(defun comment-region (beg end &optional arg)
1037 "Comment or uncomment each line in the region.
3674a4a9 1038With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
11a26e05 1039Numeric prefix ARG means use ARG comment characters.
83b96b22 1040If ARG is negative, delete that many comment characters instead.
be83ecb2
SM
1041By default, comments start at the left margin, are terminated on each line,
1042even for syntax in which newline does not end the comment and blank lines
1043do not get comments. This can be changed with `comment-style'.
83b96b22
SM
1044
1045The strings used as comment starts are built from
1046`comment-start' without trailing spaces and `comment-padding'."
1047 (interactive "*r\nP")
1048 (comment-normalize-vars)
1049 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
b70dd952
SM
1050 (save-excursion
1051 ;; FIXME: maybe we should call uncomment depending on ARG.
1052 (funcall comment-region-function beg end arg)))
1053
1054(defun comment-region-default (beg end &optional arg)
2ab98065 1055 (let* ((numarg (prefix-numeric-value arg))
2ab98065
SM
1056 (style (cdr (assoc comment-style comment-styles)))
1057 (lines (nth 2 style))
1058 (block (nth 1 style))
1059 (multi (nth 0 style)))
5266b06b
RS
1060
1061 ;; We use `chars' instead of `syntax' because `\n' might be
b70dd952
SM
1062 ;; of end-comment syntax rather than of whitespace syntax.
1063 ;; sanitize BEG and END
1064 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
1065 (setq beg (max beg (point)))
1066 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
1067 (setq end (min end (point)))
1068 (if (>= beg end) (error "Nothing to comment"))
1069
1070 ;; sanitize LINES
1071 (setq lines
1072 (and
1073 lines ;; multi
1074 (progn (goto-char beg) (beginning-of-line)
1075 (skip-syntax-forward " ")
1076 (>= (point) beg))
1077 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
1078 (<= (point) end))
1079 (or block (not (string= "" comment-end)))
1080 (or block (progn (goto-char beg) (search-forward "\n" end t)))))
1081
1082 ;; don't add end-markers just because the user asked for `block'
1083 (unless (or lines (string= "" comment-end)) (setq block nil))
1084
1085 (cond
1086 ((consp arg) (uncomment-region beg end))
1087 ((< numarg 0) (uncomment-region beg end (- numarg)))
1088 (t
5266b06b
RS
1089 ;; Add an extra semicolon in Lisp and similar modes.
1090 ;; If STYLE doesn't specify indenting the comments,
7f821b79 1091 ;; then double the value of `comment-add'.
5266b06b 1092 (setq numarg (comment-add arg (null (nth 3 style))))
b70dd952
SM
1093 (comment-region-internal
1094 beg end
1095 (let ((s (comment-padright comment-start numarg)))
1096 (if (string-match comment-start-skip s) s
1097 (comment-padright comment-start)))
1098 (let ((s (comment-padleft comment-end numarg)))
1099 (and s (if (string-match comment-end-skip s) s
1100 (comment-padright comment-end))))
1101 (if multi (comment-padright comment-continue numarg))
1102 (if multi
1103 (comment-padleft (comment-string-reverse comment-continue) numarg))
1104 block
1105 lines
1106 (nth 3 style))))))
771c9b97 1107
016c63b6 1108;;;###autoload
771c9b97 1109(defun comment-box (beg end &optional arg)
3674a4a9 1110 "Comment out the BEG .. END region, putting it inside a box.
771c9b97
SM
1111The numeric prefix ARG specifies how many characters to add to begin- and
1112end- comment markers additionally to what `comment-add' already specifies."
1113 (interactive "*r\np")
016c63b6 1114 (comment-normalize-vars)
9b0d1d6e
SM
1115 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
1116 'box-multi 'box)))
771c9b97 1117 (comment-region beg end (+ comment-add arg))))
83b96b22 1118
88fe06af
SM
1119
1120;;;###autoload
1121(defun comment-or-uncomment-region (beg end &optional arg)
1122 "Call `comment-region', unless the region only consists of comments,
1123in which case call `uncomment-region'. If a prefix arg is given, it
1124is passed on to the respective function."
1125 (interactive "*r\nP")
2abd0306 1126 (comment-normalize-vars)
88fe06af
SM
1127 (funcall (if (save-excursion ;; check for already commented region
1128 (goto-char beg)
1129 (comment-forward (point-max))
1130 (<= end (point)))
1131 'uncomment-region 'comment-region)
1132 beg end arg))
1133
be83ecb2 1134;;;###autoload
2ab98065 1135(defun comment-dwim (arg)
ad679e45
SM
1136 "Call the comment command you want (Do What I Mean).
1137If the region is active and `transient-mark-mode' is on, call
39cb51e7 1138 `comment-region' (unless it only consists of comments, in which
ad679e45 1139 case it calls `uncomment-region').
2ab98065 1140Else, if the current line is empty, insert a comment and indent it.
ad679e45 1141Else if a prefix ARG is specified, call `comment-kill'.
ae2c9c21
SM
1142Else, call `comment-indent'.
1143You can configure `comment-style' to change the way regions are commented."
2ab98065
SM
1144 (interactive "*P")
1145 (comment-normalize-vars)
771c9b97 1146 (if (and mark-active transient-mark-mode)
88fe06af 1147 (comment-or-uncomment-region (region-beginning) (region-end) arg)
2ab98065 1148 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
ad679e45
SM
1149 ;; FIXME: If there's no comment to kill on this line and ARG is
1150 ;; specified, calling comment-kill is not very clever.
1151 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
b433a560
SM
1152 (let ((add (comment-add arg)))
1153 ;; Some modes insist on keeping column 0 comment in column 0
2e1fbba4
SM
1154 ;; so we need to move away from it before inserting the comment.
1155 (indent-according-to-mode)
2ab98065
SM
1156 (insert (comment-padright comment-start add))
1157 (save-excursion
1158 (unless (string= "" comment-end)
1159 (insert (comment-padleft comment-end add)))
1160 (indent-according-to-mode))))))
1161
1fc075d8 1162;;;###autoload
392f1ef5
SM
1163(defcustom comment-auto-fill-only-comments nil
1164 "Non-nil means to only auto-fill inside comments.
1165This has no effect in modes that do not define a comment syntax."
f5307782
JB
1166 :type 'boolean
1167 :group 'comment)
392f1ef5 1168
bfe6e13f 1169(defun comment-valid-prefix-p (prefix compos)
e29d96b6
SM
1170 "Check that the adaptive-fill-prefix is consistent with the context.
1171PREFIX is the prefix (presumably guessed by `adaptive-fill-mode').
1172COMPOS is the position of the beginning of the comment we're in, or nil
1173if we're not inside a comment."
1174 ;; This consistency checking is mostly needed to workaround the limitation
1175 ;; of auto-fill-mode whose paragraph-determination doesn't pay attention
1176 ;; to comment boundaries.
1177 (if (null compos)
1178 ;; We're not inside a comment: the prefix shouldn't match
1179 ;; a comment-starter.
1180 (not (and comment-start comment-start-skip
1181 (string-match comment-start-skip prefix)))
1182 (or
1183 ;; Accept any prefix if the current comment is not EOL-terminated.
1184 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1185 ;; Accept any prefix that starts with the same comment-start marker
1186 ;; as the current one.
1187 (when (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1188 prefix)
1189 (let ((prefix-com (comment-string-strip (match-string 0 prefix) nil t)))
1190 (string-match "\\`[ \t]*" prefix-com)
1191 (let* ((prefix-space (match-string 0 prefix-com))
1192 (prefix-indent (string-width prefix-space))
1193 (prefix-comstart (substring prefix-com (match-end 0))))
1194 (save-excursion
1195 (goto-char compos)
1196 ;; The comstart marker is the same.
1197 (and (looking-at (regexp-quote prefix-comstart))
1198 ;; The indentation as well.
1199 (or (= prefix-indent
1200 (- (current-column) (current-left-margin)))
1201 ;; Check the indentation in two different ways, just
1202 ;; to try and avoid most of the potential funny cases.
1203 (equal prefix-space
1204 (buffer-substring (point)
1205 (progn (move-to-left-margin)
1206 (point)))))))))))))
1207
7164ef13 1208
be83ecb2 1209;;;###autoload
ad679e45 1210(defun comment-indent-new-line (&optional soft)
2ab98065
SM
1211 "Break line at point and indent, continuing comment if within one.
1212This indents the body of the continued comment
1213under the previous comment line.
1214
1215This command is intended for styles where you write a comment per line,
1216starting a new comment (and terminating it if necessary) on each line.
1217If you want to continue one comment across several lines, use \\[newline-and-indent].
1218
1219If a fill column is specified, it overrides the use of the comment column
1220or comment indentation.
1221
1222The inserted newline is marked hard if variable `use-hard-newlines' is true,
1223unless optional argument SOFT is non-nil."
1224 (interactive)
1225 (comment-normalize-vars t)
59a1ce8d
SM
1226 (let (compos comin)
1227 ;; If we are not inside a comment and we only auto-fill comments,
1228 ;; don't do anything (unless no comment syntax is defined).
392f1ef5
SM
1229 (unless (and comment-start
1230 comment-auto-fill-only-comments
0603917d 1231 (not (interactive-p))
392f1ef5 1232 (not (save-excursion
59a1ce8d 1233 (prog1 (setq compos (comment-beginning))
392f1ef5 1234 (setq comin (point))))))
59a1ce8d
SM
1235
1236 ;; Now we know we should auto-fill.
88fe06af
SM
1237 ;; Insert the newline before removing empty space so that markers
1238 ;; get preserved better.
392f1ef5 1239 (if soft (insert-and-inherit ?\n) (newline 1))
88fe06af
SM
1240 (save-excursion (forward-char -1) (delete-horizontal-space))
1241 (delete-horizontal-space)
1242
7164ef13
SM
1243 (if (and fill-prefix (not adaptive-fill-mode))
1244 ;; Blindly trust a non-adaptive fill-prefix.
392f1ef5
SM
1245 (progn
1246 (indent-to-left-margin)
88fe06af 1247 (insert-before-markers-and-inherit fill-prefix))
59a1ce8d
SM
1248
1249 ;; If necessary check whether we're inside a comment.
a764440a 1250 (unless (or compos (null comment-start))
392f1ef5
SM
1251 (save-excursion
1252 (backward-char)
59a1ce8d
SM
1253 (setq compos (comment-beginning))
1254 (setq comin (point))))
1255
7164ef13
SM
1256 (cond
1257 ;; If there's an adaptive prefix, use it unless we're inside
1258 ;; a comment and the prefix is not a comment starter.
1259 ((and fill-prefix
e29d96b6 1260 (comment-valid-prefix-p fill-prefix compos))
7164ef13
SM
1261 (indent-to-left-margin)
1262 (insert-and-inherit fill-prefix))
1263 ;; If we're not inside a comment, just try to indent.
1264 ((not compos) (indent-according-to-mode))
1265 (t
59a1ce8d
SM
1266 (let* ((comment-column
1267 ;; The continuation indentation should be somewhere between
1268 ;; the current line's indentation (plus 2 for good measure)
1269 ;; and the current comment's indentation, with a preference
1270 ;; for comment-column.
1271 (save-excursion
a764440a 1272 ;; FIXME: use prev line's info rather than first line's.
59a1ce8d
SM
1273 (goto-char compos)
1274 (min (current-column) (max comment-column
1275 (+ 2 (current-indentation))))))
1276 (comstart (buffer-substring compos comin))
1277 (normalp
1278 (string-match (regexp-quote (comment-string-strip
1279 comment-start t t))
1280 comstart))
1281 (comment-end
1282 (if normalp comment-end
1283 ;; The comment starter is not the normal comment-start
1284 ;; so we can't just use comment-end.
1285 (save-excursion
1286 (goto-char compos)
1287 (if (not (comment-forward)) comment-end
1288 (comment-string-strip
1289 (buffer-substring
1290 (save-excursion (comment-enter-backward) (point))
1291 (point))
1292 nil t)))))
1293 (comment-start comstart)
a764440a
SM
1294 (continuep (or comment-multi-line
1295 (cadr (assoc comment-style comment-styles))))
59a1ce8d 1296 ;; Force comment-continue to be recreated from comment-start.
dde6824c 1297 ;; FIXME: wrong if comment-continue was set explicitly!
a764440a 1298 ;; FIXME: use prev line's continuation if available.
59a1ce8d 1299 (comment-continue nil))
a764440a
SM
1300 (if (and comment-multi-line (> (length comment-end) 0))
1301 (indent-according-to-mode)
1302 (insert-and-inherit ?\n)
1303 (forward-char -1)
1304 (comment-indent continuep)
1305 (save-excursion
1306 (let ((pt (point)))
1307 (end-of-line)
1308 (let ((comend (buffer-substring pt (point))))
1309 ;; The 1+ is to make sure we delete the \n inserted above.
1310 (delete-region pt (1+ (point)))
1311 (end-of-line 0)
1312 (insert comend))))))))))))
2ab98065 1313
83b96b22
SM
1314(provide 'newcomment)
1315
b70dd952 1316;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
83b96b22 1317;;; newcomment.el ends here