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