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