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