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