Revert previous change.
[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'.
c391a81f
RS
185The `plain' comment style doubles this value.
186
f5215400 187This should generally stay 0, except for a few modes like Lisp where
c391a81f 188it is 1 so that regions are commented with two or three semi-colons.")
2ab98065 189
2ab98065 190(defconst comment-styles
771c9b97
SM
191 '((plain . (nil nil nil nil))
192 (indent . (nil nil nil t))
c391a81f
RS
193 (indent-or-triple
194 . (nil nil nil multi-char))
771c9b97
SM
195 (aligned . (nil t nil t))
196 (multi-line . (t nil nil t))
197 (extra-line . (t nil t t))
9b0d1d6e
SM
198 (box . (nil t t t))
199 (box-multi . (t t t t)))
5266b06b 200 "Comment region styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
f5215400
SM
201STYLE should be a mnemonic symbol.
202MULTI specifies that comments are allowed to span multiple lines.
203ALIGN specifies that the `comment-end' markers should be aligned.
204EXTRA specifies that an extra line should be used before and after the
205 region to comment (to put the `comment-end' and `comment-start').
206INDENT specifies that the `comment-start' markers should not be put at the
c391a81f
RS
207 left margin but at the current indentation of the region to comment.
208If INDENT is `multi-char', that means indent multi-character
209 comment starters, but not one-character comment starters.")
f5215400 210
be83ecb2 211;;;###autoload
c391a81f 212(defcustom comment-style 'indent-or-triple
ae2c9c21 213 "Style to be used for `comment-region'.
f5215400 214See `comment-styles' for a list of available styles."
be83ecb2 215 :type (if (boundp 'comment-styles)
5266b06b
RS
216 `(choice ,@(mapcar (lambda (s) `(const ,(car s)))
217 comment-styles))
f5307782
JB
218 'symbol)
219 :group 'comment)
2ab98065 220
be83ecb2
SM
221;;;###autoload
222(defcustom comment-padding " "
f5215400
SM
223 "Padding string that `comment-region' puts between comment chars and text.
224Can also be an integer which will be automatically turned into a string
225of the corresponding number of spaces.
2ab98065
SM
226
227Extra spacing between the comment characters and the comment text
0603917d 228makes the comment easier to read. Default is 1. nil means 0."
f5307782
JB
229 :type '(choice string integer (const nil))
230 :group 'comment)
2ab98065 231
be83ecb2 232;;;###autoload
3e569d22 233(defcustom comment-multi-line nil
ae2c9c21 234 "Non-nil means `comment-indent-new-line' continues comments.
269a8f1c
LT
235That is, it inserts no new terminator or starter.
236This affects `auto-fill-mode', which is the main reason to
237customize this variable.
238
239It also affects \\[indent-new-comment-line]. However, if you want this
240behavior for explicit filling, you might as well use \\[newline-and-indent]."
f5307782
JB
241 :type 'boolean
242 :group 'comment)
3e569d22 243
6976bf99
SM
244(defcustom comment-empty-lines nil
245 "If nil, `comment-region' does not comment out empty lines.
246If t, it always comments out empty lines.
e29d96b6 247If `eol' it only comments out empty lines if comments are
6976bf99
SM
248terminated by the end of line (i.e. `comment-end' is empty)."
249 :type '(choice (const :tag "Never" nil)
250 (const :tag "Always" t)
f5307782
JB
251 (const :tag "EOl-terminated" 'eol))
252 :group 'comment)
6976bf99 253
2ab98065
SM
254;;;;
255;;;; Helpers
256;;;;
257
f5215400
SM
258(defun comment-string-strip (str beforep afterp)
259 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
260 (string-match (concat "\\`" (if beforep "\\s-*")
ad679e45 261 "\\(.*?\\)" (if afterp "\\s-*\n?")
2ab98065
SM
262 "\\'") str)
263 (match-string 1 str))
264
265(defun comment-string-reverse (s)
f5215400 266 "Return the mirror image of string S, without any trailing space."
771c9b97 267 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
2ab98065 268
7164ef13 269;;;###autoload
2ab98065 270(defun comment-normalize-vars (&optional noerror)
0f21c5a0
SM
271 "Check and setup the variables needed by other commenting functions.
272Functions autoloaded from newcomment.el, being entry points, should call
273this function before any other, so the rest of the code can assume that
274the variables are properly set."
0d6a08f6
SM
275 (unless (and (not comment-start) noerror)
276 (unless comment-start
31df2900
SM
277 (let ((cs (read-string "No comment syntax is defined. Use: ")))
278 (if (zerop (length cs))
279 (error "No comment syntax defined")
280 (set (make-local-variable 'comment-start) cs))))
2ab98065 281 ;; comment-use-syntax
771c9b97 282 (when (eq comment-use-syntax 'undecided)
2ab98065
SM
283 (set (make-local-variable 'comment-use-syntax)
284 (let ((st (syntax-table))
285 (cs comment-start)
286 (ce (if (string= "" comment-end) "\n" comment-end)))
771c9b97
SM
287 ;; Try to skip over a comment using forward-comment
288 ;; to see if the syntax tables properly recognize it.
2ab98065
SM
289 (with-temp-buffer
290 (set-syntax-table st)
291 (insert cs " hello " ce)
292 (goto-char (point-min))
293 (and (forward-comment 1) (eobp))))))
2ab98065 294 ;; comment-padding
9145f1c2 295 (unless comment-padding (setq comment-padding 0))
2ab98065
SM
296 (when (integerp comment-padding)
297 (setq comment-padding (make-string comment-padding ? )))
298 ;; comment markers
299 ;;(setq comment-start (comment-string-strip comment-start t nil))
300 ;;(setq comment-end (comment-string-strip comment-end nil t))
301 ;; comment-continue
f5215400 302 (unless (or comment-continue (string= comment-end ""))
2ab98065 303 (set (make-local-variable 'comment-continue)
9b0d1d6e 304 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
7164ef13
SM
305 (substring comment-start 1)))
306 ;; Hasn't been necessary yet.
307 ;; (unless (string-match comment-start-skip comment-continue)
016c63b6 308 ;; (kill-local-variable 'comment-continue))
7164ef13 309 )
2ab98065 310 ;; comment-skip regexps
f23a0f3a
SM
311 (unless (and comment-start-skip
312 ;; In case comment-start has changed since last time.
313 (string-match comment-start-skip comment-start))
2ab98065 314 (set (make-local-variable 'comment-start-skip)
f0a478be 315 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
2ab98065 316 (regexp-quote (comment-string-strip comment-start t t))
75ed43a6
SM
317 ;; Let's not allow any \s- but only [ \t] since \n
318 ;; might be both a comment-end marker and \s-.
319 "+\\)[ \t]*")))
f23a0f3a
SM
320 (unless (and comment-end-skip
321 ;; In case comment-end has changed since last time.
322 (string-match comment-end-skip comment-end))
2ab98065
SM
323 (let ((ce (if (string= "" comment-end) "\n"
324 (comment-string-strip comment-end t t))))
325 (set (make-local-variable 'comment-end-skip)
37dbd369
SM
326 ;; We use [ \t] rather than \s- because we don't want to
327 ;; remove ^L in C mode when uncommenting.
328 (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
2ab98065 329 "\\|" (regexp-quote (substring ce 0 1))
771c9b97 330 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
2ab98065
SM
331 (regexp-quote (substring ce 1))
332 "\\)"))))))
f1180544 333
f5215400
SM
334(defun comment-quote-re (str unp)
335 (concat (regexp-quote (substring str 0 1))
336 "\\\\" (if unp "+" "*")
337 (regexp-quote (substring str 1))))
338
339(defun comment-quote-nested (cs ce unp)
340 "Quote or unquote nested comments.
341If UNP is non-nil, unquote nested comment markers."
342 (setq cs (comment-string-strip cs t t))
343 (setq ce (comment-string-strip ce t t))
344 (when (and comment-quote-nested (> (length ce) 0))
345 (let ((re (concat (comment-quote-re ce unp)
346 "\\|" (comment-quote-re cs unp))))
347 (goto-char (point-min))
348 (while (re-search-forward re nil t)
349 (goto-char (match-beginning 0))
350 (forward-char 1)
351 (if unp (delete-char 1) (insert "\\"))
352 (when (= (length ce) 1)
353 ;; If the comment-end is a single char, adding a \ after that
354 ;; "first" char won't deactivate it, so we turn such a CE
355 ;; into !CS. I.e. for pascal, we turn } into !{
356 (if (not unp)
357 (when (string= (match-string 0) ce)
358 (replace-match (concat "!" cs) t t))
359 (when (and (< (point-min) (match-beginning 0))
360 (string= (buffer-substring (1- (match-beginning 0))
361 (1- (match-end 0)))
362 (concat "!" cs)))
363 (backward-char 2)
364 (delete-char (- (match-end 0) (match-beginning 0)))
365 (insert ce))))))))
2ab98065
SM
366
367;;;;
368;;;; Navigation
369;;;;
370
f5f95edf
SM
371(defvar comment-use-global-state nil
372 "Non-nil means that the global syntactic context is used.
373More specifically, it means that `syntax-ppss' is used to find out whether
374point is within a string or not. Major modes whose syntax is faithfully
375described by the syntax-tables can set this to non-nil so comment markers
376in strings will not confuse Emacs.")
377
ad679e45 378(defun comment-search-forward (limit &optional noerror)
771c9b97
SM
379 "Find a comment start between point and LIMIT.
380Moves point to inside the comment and returns the position of the
381comment-starter. If no comment is found, moves point to LIMIT
11a26e05 382and raises an error or returns nil if NOERROR is non-nil."
2ab98065 383 (if (not comment-use-syntax)
9b0d1d6e
SM
384 (if (re-search-forward comment-start-skip limit noerror)
385 (or (match-end 1) (match-beginning 0))
386 (goto-char limit)
387 (unless noerror (error "No comment")))
ad679e45
SM
388 (let* ((pt (point))
389 ;; Assume (at first) that pt is outside of any string.
f5f95edf
SM
390 (s (parse-partial-sexp pt (or limit (point-max)) nil nil
391 (if comment-use-global-state (syntax-ppss pt))
392 t)))
393 (when (and (nth 8 s) (nth 3 s) (not comment-use-global-state))
b70dd952
SM
394 ;; The search ended at eol inside a string. Try to see if it
395 ;; works better when we assume that pt is inside a string.
396 (setq s (parse-partial-sexp
397 pt (or limit (point-max)) nil nil
398 (list nil nil nil (nth 3 s) nil nil nil nil)
399 t)))
5605893d
SM
400 (if (or (not (and (nth 8 s) (not (nth 3 s))))
401 ;; Make sure the comment starts after PT.
402 (< (nth 8 s) pt))
ad679e45
SM
403 (unless noerror (error "No comment"))
404 ;; We found the comment.
9b0d1d6e 405 (let ((pos (point))
ad679e45 406 (start (nth 8 s))
9b0d1d6e 407 (bol (line-beginning-position))
ad679e45
SM
408 (end nil))
409 (while (and (null end) (>= (point) bol))
410 (if (looking-at comment-start-skip)
411 (setq end (min (or limit (point-max)) (match-end 0)))
412 (backward-char)))
9b0d1d6e 413 (goto-char (or end pos))
ad679e45 414 start)))))
2ab98065
SM
415
416(defun comment-search-backward (&optional limit noerror)
417 "Find a comment start between LIMIT and point.
771c9b97
SM
418Moves point to inside the comment and returns the position of the
419comment-starter. If no comment is found, moves point to LIMIT
11a26e05 420and raises an error or returns nil if NOERROR is non-nil."
ad679e45
SM
421 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
422 ;; stop there. This can be rather bad in general, but since
423 ;; comment-search-backward is only used to find the comment-column (in
424 ;; comment-set-column) and to find the comment-start string (via
425 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
2ab98065
SM
426 (if (not (re-search-backward comment-start-skip limit t))
427 (unless noerror (error "No comment"))
428 (beginning-of-line)
429 (let* ((end (match-end 0))
430 (cs (comment-search-forward end t))
431 (pt (point)))
432 (if (not cs)
433 (progn (beginning-of-line)
434 (comment-search-backward limit noerror))
435 (while (progn (goto-char cs)
436 (comment-forward)
437 (and (< (point) end)
438 (setq cs (comment-search-forward end t))))
439 (setq pt (point)))
440 (goto-char pt)
441 cs))))
442
443(defun comment-beginning ()
771c9b97
SM
444 "Find the beginning of the enclosing comment.
445Returns nil if not inside a comment, else moves point and returns
2308f447 446the same as `comment-search-backward'."
75ed43a6
SM
447 ;; HACK ATTACK!
448 ;; We should really test `in-string-p' but that can be expensive.
449 (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
450 (let ((pt (point))
451 (cs (comment-search-backward nil t)))
452 (when cs
453 (if (save-excursion
454 (goto-char cs)
dde6824c
SM
455 (and
456 ;; For modes where comment-start and comment-end are the same,
457 ;; the search above may have found a `ce' rather than a `cs'.
2308f447 458 (or (if comment-end-skip (not (looking-at comment-end-skip)))
dde6824c
SM
459 ;; Maybe font-lock knows that it's a `cs'?
460 (eq (get-text-property (match-end 0) 'face)
461 'font-lock-comment-face)
462 (unless (eq (get-text-property (point) 'face)
463 'font-lock-comment-face)
464 ;; Let's assume it's a `cs' if we're on the same line.
465 (>= (line-end-position) pt)))
466 ;; Make sure that PT is not past the end of the comment.
467 (if (comment-forward 1) (> (point) pt) (eobp))))
75ed43a6
SM
468 cs
469 (goto-char pt)
470 nil)))))
2ab98065
SM
471
472(defun comment-forward (&optional n)
473 "Skip forward over N comments.
474Just like `forward-comment' but only for positive N
475and can use regexps instead of syntax."
476 (setq n (or n 1))
477 (if (< n 0) (error "No comment-backward")
478 (if comment-use-syntax (forward-comment n)
479 (while (> n 0)
59a1ce8d 480 (setq n
0f38a885
SM
481 (if (or (forward-comment 1)
482 (and (looking-at comment-start-skip)
483 (goto-char (match-end 0))
484 (re-search-forward comment-end-skip nil 'move)))
59a1ce8d 485 (1- n) -1)))
2ab98065
SM
486 (= n 0))))
487
488(defun comment-enter-backward ()
489 "Move from the end of a comment to the end of its content.
771c9b97 490Point is assumed to be just at the end of a comment."
2ab98065
SM
491 (if (bolp)
492 ;; comment-end = ""
493 (progn (backward-char) (skip-syntax-backward " "))
3cc4b076
SM
494 (cond
495 ((save-restriction
1cb40089
SM
496 (narrow-to-region (line-beginning-position) (point))
497 (goto-char (point-min))
3cc4b076
SM
498 (re-search-forward (concat comment-end-skip "\\'") nil t))
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)
602 ;; An existing comment?
7a06b250
SM
603 (if begpos
604 (progn
605 (if (and (not (looking-at "[\t\n ]"))
606 (looking-at comment-end-skip))
607 ;; The comment is empty and we have skipped all its space
608 ;; and landed right before the comment-ender:
609 ;; Go back to the middle of the space.
610 (forward-char (/ (skip-chars-backward " \t") -2)))
611 (setq cpos (point-marker)))
2e1fbba4 612 ;; If none, insert one.
a71b3805
EZ
613 (if comment-insert-comment-function
614 (funcall comment-insert-comment-function)
2e1fbba4 615 (save-excursion
a71b3805
EZ
616 ;; Some `comment-indent-function's insist on not moving
617 ;; comments that are in column 0, so we first go to the
618 ;; likely target column.
567e961e 619 (indent-to comment-column)
e6bba95e
DL
620 ;; Ensure there's a space before the comment for things
621 ;; like sh where it matters (as well as being neater).
7c0bbe7f
JB
622 (unless (memq (char-before) '(nil ?\n ?\t ?\s))
623 (insert ?\s))
07f10bab 624 (setq begpos (point))
bb304a7a 625 (insert starter)
2e1fbba4 626 (setq cpos (point-marker))
a71b3805 627 (insert ender))))
2e1fbba4
SM
628 (goto-char begpos)
629 ;; Compute desired indent.
053b8d35 630 (setq indent (save-excursion (funcall comment-indent-function)))
8cc313a3
SM
631 ;; If `indent' is nil and there's code before the comment, we can't
632 ;; use `indent-according-to-mode', so we default to comment-column.
633 (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
634 (setq indent comment-column))
2e1fbba4 635 (if (not indent)
bfe6e13f 636 ;; comment-indent-function refuses: delegate to line-indent.
2e1fbba4 637 (indent-according-to-mode)
2ed8e1f7 638 ;; If the comment is at the right of code, adjust the indentation.
a764440a 639 (unless (save-excursion (skip-chars-backward " \t") (bolp))
2ed8e1f7 640 (setq indent (comment-choose-indent indent)))
b605a60a
RS
641 ;; Update INDENT to leave at least one space
642 ;; after other nonwhite text on the line.
643 (save-excursion
016c63b6 644 (skip-chars-backward " \t")
b605a60a
RS
645 (unless (bolp)
646 (setq indent (max indent (1+ (current-column))))))
647 ;; If that's different from comment's current position, change it.
7164ef13 648 (unless (= (current-column) indent)
7164ef13 649 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
b605a60a 650 (indent-to indent)))
2e1fbba4
SM
651 (goto-char cpos)
652 (set-marker cpos nil))))
83b96b22 653
be83ecb2 654;;;###autoload
3e569d22 655(defun comment-set-column (arg)
83b96b22 656 "Set the comment column based on point.
2ab98065 657With no ARG, set the comment column to the current column.
83b96b22
SM
658With just minus as arg, kill any comment on this line.
659With any other arg, set comment column to indentation of the previous comment
660 and then align or create a comment on this line at that column."
661 (interactive "P")
e8fe7d39 662 (cond
ad679e45 663 ((eq arg '-) (comment-kill nil))
e8fe7d39 664 (arg
2abd0306 665 (comment-normalize-vars)
e8fe7d39
SM
666 (save-excursion
667 (beginning-of-line)
2ab98065 668 (comment-search-backward)
e8fe7d39 669 (beginning-of-line)
ad679e45 670 (goto-char (comment-search-forward (line-end-position)))
83b96b22 671 (setq comment-column (current-column))
e8fe7d39 672 (message "Comment column set to %d" comment-column))
ad679e45 673 (comment-indent))
e8fe7d39 674 (t (setq comment-column (current-column))
83b96b22
SM
675 (message "Comment column set to %d" comment-column))))
676
be83ecb2 677;;;###autoload
3e569d22 678(defun comment-kill (arg)
7a0a180a
SM
679 "Kill the comment on this line, if any.
680With prefix ARG, kill comments on that many lines starting with this one."
681 (interactive "P")
2abd0306 682 (comment-normalize-vars)
ad679e45
SM
683 (dotimes (_ (prefix-numeric-value arg))
684 (save-excursion
685 (beginning-of-line)
686 (let ((cs (comment-search-forward (line-end-position) t)))
687 (when cs
688 (goto-char cs)
689 (skip-syntax-backward " ")
690 (setq cs (point))
691 (comment-forward)
692 (kill-region cs (if (bolp) (1- (point)) (point)))
693 (indent-according-to-mode))))
694 (if arg (forward-line 1))))
7a0a180a 695
2ab98065
SM
696(defun comment-padright (str &optional n)
697 "Construct a string composed of STR plus `comment-padding'.
f5215400 698It also adds N copies of the last non-whitespace chars of STR.
2ab98065 699If STR already contains padding, the corresponding amount is
f5215400
SM
700ignored from `comment-padding'.
701N defaults to 0.
771c9b97 702If N is `re', a regexp is returned instead, that would match
f5215400 703the string for any N."
2ab98065
SM
704 (setq n (or n 0))
705 (when (and (stringp str) (not (string= "" str)))
f5215400 706 ;; Separate the actual string from any leading/trailing padding
3e569d22 707 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
f5215400
SM
708 (let ((s (match-string 1 str)) ;actual string
709 (lpad (substring str 0 (match-beginning 1))) ;left padding
710 (rpad (concat (substring str (match-end 1)) ;original right padding
711 (substring comment-padding ;additional right padding
3e569d22 712 (min (- (match-end 0) (match-end 1))
9b0d1d6e
SM
713 (length comment-padding)))))
714 ;; We can only duplicate C if the comment-end has multiple chars
715 ;; or if comments can be nested, else the comment-end `}' would
716 ;; be turned into `}}}' where only the first ends the comment
717 ;; and the rest becomes bogus junk.
718 (multi (not (and comment-quote-nested
719 ;; comment-end is a single char
720 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
f5215400 721 (if (not (symbolp n))
9b0d1d6e 722 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
f5215400
SM
723 ;; construct a regexp that would match anything from just S
724 ;; to any possible output of this function for any N.
725 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
726 lpad "") ;padding is not required
9b0d1d6e
SM
727 (regexp-quote s)
728 (when multi "+") ;the last char of S might be repeated
f5215400
SM
729 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
730 rpad "")))))) ;padding is not required
2ab98065
SM
731
732(defun comment-padleft (str &optional n)
733 "Construct a string composed of `comment-padding' plus STR.
f5215400 734It also adds N copies of the first non-whitespace chars of STR.
2ab98065 735If STR already contains padding, the corresponding amount is
f5215400
SM
736ignored from `comment-padding'.
737N defaults to 0.
771c9b97 738If N is `re', a regexp is returned instead, that would match
2ab98065
SM
739 the string for any N."
740 (setq n (or n 0))
741 (when (and (stringp str) (not (string= "" str)))
f5215400 742 ;; Only separate the left pad because we assume there is no right pad.
2ab98065
SM
743 (string-match "\\`\\s-*" str)
744 (let ((s (substring str (match-end 0)))
745 (pad (concat (substring comment-padding
746 (min (- (match-end 0) (match-beginning 0))
747 (length comment-padding)))
748 (match-string 0 str)))
f5215400
SM
749 (c (aref str (match-end 0))) ;the first non-space char of STR
750 ;; We can only duplicate C if the comment-end has multiple chars
751 ;; or if comments can be nested, else the comment-end `}' would
752 ;; be turned into `}}}' where only the first ends the comment
753 ;; and the rest becomes bogus junk.
754 (multi (not (and comment-quote-nested
755 ;; comment-end is a single char
756 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
757 (if (not (symbolp n))
758 (concat pad (when multi (make-string n c)) s)
759 ;; Construct a regexp that would match anything from just S
760 ;; to any possible output of this function for any N.
761 ;; We match any number of leading spaces because this regexp will
762 ;; be used for uncommenting where we might want to remove
763 ;; uncomment markers with arbitrary leading space (because
764 ;; they were aligned).
765 (concat "\\s-*"
766 (if multi (concat (regexp-quote (string c)) "*"))
767 (regexp-quote s))))))
83b96b22 768
be83ecb2 769;;;###autoload
7a0a180a 770(defun uncomment-region (beg end &optional arg)
eb0b51f8 771 "Uncomment each line in the BEG .. END region.
f5215400
SM
772The numeric prefix ARG can specify a number of chars to remove from the
773comment markers."
83b96b22
SM
774 (interactive "*r\nP")
775 (comment-normalize-vars)
065b7364 776 (when (> beg end) (setq beg (prog1 end (setq end beg))))
b70dd952
SM
777 ;; Bind `comment-use-global-state' to nil. While uncommenting a region
778 ;; (which works a line at a time), a comment can appear to be
cbdad6e2
EZ
779 ;; included in a mult-line string, but it is actually not.
780 (let ((comment-use-global-state nil))
781 (save-excursion
b70dd952
SM
782 (funcall uncomment-region-function beg end arg))))
783
784(defun uncomment-region-default (beg end &optional arg)
785 "Uncomment each line in the BEG .. END region.
786The numeric prefix ARG can specify a number of chars to remove from the
787comment markers."
788 (goto-char beg)
789 (setq end (copy-marker end))
790 (let* ((numarg (prefix-numeric-value arg))
791 (ccs comment-continue)
792 (srei (comment-padright ccs 're))
793 (csre (comment-padright comment-start 're))
794 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
795 spt)
796 (while (and (< (point) end)
797 (setq spt (comment-search-forward end t)))
798 (let ((ipt (point))
799 ;; Find the end of the comment.
800 (ept (progn
801 (goto-char spt)
802 (unless (or (comment-forward)
803 ;; Allow non-terminated comments.
804 (eobp))
805 (error "Can't find the comment end"))
806 (point)))
807 (box nil)
808 (box-equal nil)) ;Whether we might be using `=' for boxes.
809 (save-restriction
810 (narrow-to-region spt ept)
016c63b6 811
b70dd952
SM
812 ;; Remove the comment-start.
813 (goto-char ipt)
814 (skip-syntax-backward " ")
815 ;; A box-comment starts with a looong comment-start marker.
816 (when (and (or (and (= (- (point) (point-min)) 1)
817 (setq box-equal t)
818 (looking-at "=\\{7\\}")
819 (not (eq (char-before (point-max)) ?\n))
820 (skip-chars-forward "="))
821 (> (- (point) (point-min) (length comment-start)) 7))
822 (> (count-lines (point-min) (point-max)) 2))
823 (setq box t))
824 ;; Skip the padding. Padding can come from comment-padding and/or
825 ;; from comment-start, so we first check comment-start.
826 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
827 (looking-at (regexp-quote comment-padding)))
828 (goto-char (match-end 0)))
829 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
830 (goto-char (match-end 0)))
831 (if (null arg) (delete-region (point-min) (point))
832 (skip-syntax-backward " ")
833 (delete-char (- numarg))
834 (unless (or (bobp)
835 (save-excursion (goto-char (point-min))
836 (looking-at comment-start-skip)))
837 ;; If there's something left but it doesn't look like
838 ;; a comment-start any more, just remove it.
839 (delete-region (point-min) (point))))
016c63b6 840
b70dd952
SM
841 ;; Remove the end-comment (and leading padding and such).
842 (goto-char (point-max)) (comment-enter-backward)
843 ;; Check for special `=' used sometimes in comment-box.
844 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
845 (let ((pos (point)))
846 ;; skip `=' but only if there are at least 7.
847 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
848 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
849 (when (and (bolp) (not (bobp))) (backward-char))
850 (if (null arg) (delete-region (point) (point-max))
851 (skip-syntax-forward " ")
852 (delete-char numarg)
853 (unless (or (eobp) (looking-at comment-end-skip))
854 ;; If there's something left but it doesn't look like
855 ;; a comment-end any more, just remove it.
856 (delete-region (point) (point-max)))))
857
858 ;; Unquote any nested end-comment.
859 (comment-quote-nested comment-start comment-end t)
860
861 ;; Eliminate continuation markers as well.
862 (when sre
863 (let* ((cce (comment-string-reverse (or comment-continue
864 comment-start)))
865 (erei (and box (comment-padleft cce 're)))
866 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
867 (goto-char (point-min))
868 (while (progn
869 (if (and ere (re-search-forward
870 ere (line-end-position) t))
871 (replace-match "" t t nil (if (match-end 2) 2 1))
872 (setq ere nil))
873 (forward-line 1)
874 (re-search-forward sre (line-end-position) t))
875 (replace-match "" t t nil (if (match-end 2) 2 1)))))
876 ;; Go to the end for the next comment.
877 (goto-char (point-max))))))
878 (set-marker end nil))
83b96b22 879
aac88001 880(defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
ad679e45
SM
881 "Make the leading and trailing extra lines.
882This is used for `extra-line' style (or `box' style if BLOCK is specified)."
9b0d1d6e
SM
883 (let ((eindent 0))
884 (if (not block)
885 ;; Try to match CS and CE's content so they align aesthetically.
886 (progn
887 (setq ce (comment-string-strip ce t t))
888 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
889 (setq eindent
890 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
891 0))))
892 ;; box comment
893 (let* ((width (- max-indent min-indent))
894 (s (concat cs "a=m" cce))
895 (e (concat ccs "a=m" ce))
896 (c (if (string-match ".*\\S-\\S-" cs)
3674a4a9
SM
897 (aref cs (1- (match-end 0)))
898 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
899 (aref cs (1- (match-end 0))) ?=)))
900 (re "\\s-*a=m\\s-*")
901 (_ (string-match re s))
902 (lcs (length cs))
9b0d1d6e
SM
903 (fill
904 (make-string (+ width (- (match-end 0)
3674a4a9 905 (match-beginning 0) lcs 3)) c)))
aac88001 906 (setq cs (replace-match fill t t s))
3674a4a9
SM
907 (when (and (not (string-match comment-start-skip cs))
908 (string-match "a=m" s))
909 ;; The whitespace around CS cannot be ignored: put it back.
910 (setq re "a=m")
911 (setq fill (make-string (- width lcs) c))
912 (setq cs (replace-match fill t t s)))
913 (string-match re e)
9b0d1d6e
SM
914 (setq ce (replace-match fill t t e))))
915 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
916 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
aac88001 917
aac88001
SM
918(defmacro comment-with-narrowing (beg end &rest body)
919 "Execute BODY with BEG..END narrowing.
920Space is added (and then removed) at the beginning for the text's
921indentation to be kept as it was before narrowing."
4745e738 922 (declare (debug t) (indent 2))
59a1ce8d 923 (let ((bindent (make-symbol "bindent")))
bfe6e13f 924 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
59a1ce8d 925 (save-restriction
bfe6e13f 926 (narrow-to-region ,beg ,end)
59a1ce8d
SM
927 (goto-char (point-min))
928 (insert (make-string ,bindent ? ))
929 (prog1
930 (progn ,@body)
931 ;; remove the bindent
932 (save-excursion
933 (goto-char (point-min))
934 (when (looking-at " *")
935 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
aac88001 936 (delete-char n)
59a1ce8d
SM
937 (setq ,bindent (- ,bindent n))))
938 (end-of-line)
939 (let ((e (point)))
940 (beginning-of-line)
941 (while (and (> ,bindent 0) (re-search-forward " *" e t))
942 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
943 (goto-char (match-beginning 0))
944 (delete-char n)
945 (setq ,bindent (- ,bindent n)))))))))))
aac88001 946
c391a81f
RS
947;; Compute the number of extra comment starter characters
948;; (extra semicolons in Lisp mode, extra stars in C mode, etc.)
5266b06b 949;; If ARG is non-nil, just follow ARG.
7f821b79
RS
950;; If the comment-starter is multi-char, just follow ARG.
951;; Otherwise obey comment-add, and double it if EXTRA is non-nil.
c391a81f 952(defun comment-add (arg)
b433a560 953 (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
c391a81f 954 (* comment-add 1)
b433a560
SM
955 (1- (prefix-numeric-value arg))))
956
771c9b97 957(defun comment-region-internal (beg end cs ce
aa417798 958 &optional ccs cce block lines indent)
3674a4a9 959 "Comment region BEG .. END.
aa417798
JB
960CS and CE are the comment start string and comment end string,
961respectively. CCS and CCE are the comment continuation strings
962for the start and end of lines, respectively (default to CS and CE).
963BLOCK indicates that end of lines should be marked with either CCE,
964CE or CS \(if CE is empty) and that those markers should be aligned.
965LINES indicates that an extra lines will be used at the beginning
966and end of the region for CE and CS.
967INDENT indicates to put CS and CCS at the current indentation of
968the region rather than at left margin."
59a1ce8d 969 ;;(assert (< beg end))
6976bf99
SM
970 (let ((no-empty (not (or (eq comment-empty-lines t)
971 (and comment-empty-lines (zerop (length ce)))))))
f5215400 972 ;; Sanitize CE and CCE.
83b96b22
SM
973 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
974 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
f5215400
SM
975 ;; If CE is empty, multiline cannot be used.
976 (unless ce (setq ccs nil cce nil))
977 ;; Should we mark empty lines as well ?
83b96b22 978 (if (or ccs block lines) (setq no-empty nil))
f5215400 979 ;; Make sure we have end-markers for BLOCK mode.
2ab98065 980 (when block (unless ce (setq ce (comment-string-reverse cs))))
f5215400
SM
981 ;; If BLOCK is not requested, we don't need CCE.
982 (unless block (setq cce nil))
983 ;; Continuation defaults to the same as CS and CE.
984 (unless ccs (setq ccs cs cce ce))
f1180544 985
83b96b22 986 (save-excursion
aac88001 987 (goto-char end)
f5215400
SM
988 ;; If the end is not at the end of a line and the comment-end
989 ;; is implicit (i.e. a newline), explicitly insert a newline.
aac88001
SM
990 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
991 (comment-with-narrowing beg end
f5215400 992 (let ((min-indent (point-max))
9d5240d2 993 (max-indent 0))
83b96b22 994 (goto-char (point-min))
f5215400
SM
995 ;; Quote any nested comment marker
996 (comment-quote-nested comment-start comment-end nil)
997
998 ;; Loop over all lines to find the needed indentations.
4125ec7e 999 (goto-char (point-min))
f5215400
SM
1000 (while
1001 (progn
1002 (unless (looking-at "[ \t]*$")
1003 (setq min-indent (min min-indent (current-indentation))))
1004 (end-of-line)
1005 (setq max-indent (max max-indent (current-column)))
1006 (not (or (eobp) (progn (forward-line) nil)))))
f1180544 1007
59a1ce8d 1008 (setq max-indent
45f6a663
SM
1009 (+ max-indent (max (length cs) (length ccs))
1010 ;; Inserting ccs can change max-indent by (1- tab-width)
1011 ;; but only if there are TABs in the boxed text, of course.
1012 (if (save-excursion (goto-char beg)
1013 (search-forward "\t" end t))
1014 (1- tab-width) 0)))
771c9b97 1015 (unless indent (setq min-indent 0))
83b96b22 1016
aac88001 1017 ;; make the leading and trailing lines if requested
83b96b22 1018 (when lines
771c9b97
SM
1019 (let ((csce
1020 (comment-make-extra-lines
1021 cs ce ccs cce min-indent max-indent block)))
1022 (setq cs (car csce))
1023 (setq ce (cdr csce))))
f1180544 1024
83b96b22
SM
1025 (goto-char (point-min))
1026 ;; Loop over all lines from BEG to END.
f5215400
SM
1027 (while
1028 (progn
1029 (unless (and no-empty (looking-at "[ \t]*$"))
1030 (move-to-column min-indent t)
1031 (insert cs) (setq cs ccs) ;switch to CCS after the first line
1032 (end-of-line)
1033 (if (eobp) (setq cce ce))
1034 (when cce
1035 (when block (move-to-column max-indent t))
1036 (insert cce)))
1037 (end-of-line)
1038 (not (or (eobp) (progn (forward-line) nil))))))))))
83b96b22 1039
be83ecb2 1040;;;###autoload
83b96b22
SM
1041(defun comment-region (beg end &optional arg)
1042 "Comment or uncomment each line in the region.
3674a4a9 1043With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
11a26e05 1044Numeric prefix ARG means use ARG comment characters.
83b96b22 1045If ARG is negative, delete that many comment characters instead.
be83ecb2
SM
1046By default, comments start at the left margin, are terminated on each line,
1047even for syntax in which newline does not end the comment and blank lines
1048do not get comments. This can be changed with `comment-style'.
83b96b22
SM
1049
1050The strings used as comment starts are built from
1051`comment-start' without trailing spaces and `comment-padding'."
1052 (interactive "*r\nP")
1053 (comment-normalize-vars)
1054 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
b70dd952
SM
1055 (save-excursion
1056 ;; FIXME: maybe we should call uncomment depending on ARG.
1057 (funcall comment-region-function beg end arg)))
1058
1059(defun comment-region-default (beg end &optional arg)
2ab98065 1060 (let* ((numarg (prefix-numeric-value arg))
2ab98065
SM
1061 (style (cdr (assoc comment-style comment-styles)))
1062 (lines (nth 2 style))
1063 (block (nth 1 style))
1064 (multi (nth 0 style)))
5266b06b
RS
1065
1066 ;; We use `chars' instead of `syntax' because `\n' might be
b70dd952
SM
1067 ;; of end-comment syntax rather than of whitespace syntax.
1068 ;; sanitize BEG and END
1069 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
1070 (setq beg (max beg (point)))
1071 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
1072 (setq end (min end (point)))
1073 (if (>= beg end) (error "Nothing to comment"))
1074
1075 ;; sanitize LINES
1076 (setq lines
1077 (and
1078 lines ;; multi
1079 (progn (goto-char beg) (beginning-of-line)
1080 (skip-syntax-forward " ")
1081 (>= (point) beg))
1082 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
1083 (<= (point) end))
1084 (or block (not (string= "" comment-end)))
1085 (or block (progn (goto-char beg) (search-forward "\n" end t)))))
1086
1087 ;; don't add end-markers just because the user asked for `block'
1088 (unless (or lines (string= "" comment-end)) (setq block nil))
1089
1090 (cond
1091 ((consp arg) (uncomment-region beg end))
1092 ((< numarg 0) (uncomment-region beg end (- numarg)))
1093 (t
c391a81f
RS
1094 (let ((multi-char (/= (string-match "[ \t]*\\'" comment-start) 1))
1095 indent)
1096 (if (eq (nth 3 style) 'multi-char)
1097 (setq indent multi-char)
1098 (setq indent (nth 3 style)))
1099
1100 ;; In Lisp and similar modes with one-character comment starters,
1101 ;; double it by default if `comment-add' says so.
1102 ;; If it isn't indented, triple it.
1103 (if (and (null arg) (not multi-char))
1104 (setq numarg (* comment-add (if indent 1 2)))
1105 (setq numarg (1- (prefix-numeric-value arg))))
1106
1107 (comment-region-internal
1108 beg end
1109 (let ((s (comment-padright comment-start numarg)))
1110 (if (string-match comment-start-skip s) s
1111 (comment-padright comment-start)))
1112 (let ((s (comment-padleft comment-end numarg)))
1113 (and s (if (string-match comment-end-skip s) s
1114 (comment-padright comment-end))))
1115 (if multi (comment-padright comment-continue numarg))
1116 (if multi
1117 (comment-padleft (comment-string-reverse comment-continue) numarg))
1118 block
1119 lines
1120 indent))))))
771c9b97 1121
016c63b6 1122;;;###autoload
771c9b97 1123(defun comment-box (beg end &optional arg)
3674a4a9 1124 "Comment out the BEG .. END region, putting it inside a box.
771c9b97
SM
1125The numeric prefix ARG specifies how many characters to add to begin- and
1126end- comment markers additionally to what `comment-add' already specifies."
1127 (interactive "*r\np")
016c63b6 1128 (comment-normalize-vars)
9b0d1d6e
SM
1129 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
1130 'box-multi 'box)))
771c9b97 1131 (comment-region beg end (+ comment-add arg))))
83b96b22 1132
88fe06af
SM
1133
1134;;;###autoload
1135(defun comment-or-uncomment-region (beg end &optional arg)
1136 "Call `comment-region', unless the region only consists of comments,
1137in which case call `uncomment-region'. If a prefix arg is given, it
1138is passed on to the respective function."
1139 (interactive "*r\nP")
2abd0306 1140 (comment-normalize-vars)
88fe06af
SM
1141 (funcall (if (save-excursion ;; check for already commented region
1142 (goto-char beg)
1143 (comment-forward (point-max))
1144 (<= end (point)))
1145 'uncomment-region 'comment-region)
1146 beg end arg))
1147
be83ecb2 1148;;;###autoload
2ab98065 1149(defun comment-dwim (arg)
ad679e45
SM
1150 "Call the comment command you want (Do What I Mean).
1151If the region is active and `transient-mark-mode' is on, call
39cb51e7 1152 `comment-region' (unless it only consists of comments, in which
ad679e45 1153 case it calls `uncomment-region').
2ab98065 1154Else, if the current line is empty, insert a comment and indent it.
ad679e45 1155Else if a prefix ARG is specified, call `comment-kill'.
ae2c9c21
SM
1156Else, call `comment-indent'.
1157You can configure `comment-style' to change the way regions are commented."
2ab98065
SM
1158 (interactive "*P")
1159 (comment-normalize-vars)
771c9b97 1160 (if (and mark-active transient-mark-mode)
88fe06af 1161 (comment-or-uncomment-region (region-beginning) (region-end) arg)
2ab98065 1162 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
ad679e45
SM
1163 ;; FIXME: If there's no comment to kill on this line and ARG is
1164 ;; specified, calling comment-kill is not very clever.
1165 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
b433a560
SM
1166 (let ((add (comment-add arg)))
1167 ;; Some modes insist on keeping column 0 comment in column 0
2e1fbba4
SM
1168 ;; so we need to move away from it before inserting the comment.
1169 (indent-according-to-mode)
2ab98065
SM
1170 (insert (comment-padright comment-start add))
1171 (save-excursion
1172 (unless (string= "" comment-end)
1173 (insert (comment-padleft comment-end add)))
1174 (indent-according-to-mode))))))
1175
1fc075d8 1176;;;###autoload
392f1ef5
SM
1177(defcustom comment-auto-fill-only-comments nil
1178 "Non-nil means to only auto-fill inside comments.
1179This has no effect in modes that do not define a comment syntax."
f5307782
JB
1180 :type 'boolean
1181 :group 'comment)
392f1ef5 1182
bfe6e13f 1183(defun comment-valid-prefix-p (prefix compos)
e29d96b6
SM
1184 "Check that the adaptive-fill-prefix is consistent with the context.
1185PREFIX is the prefix (presumably guessed by `adaptive-fill-mode').
1186COMPOS is the position of the beginning of the comment we're in, or nil
1187if we're not inside a comment."
1188 ;; This consistency checking is mostly needed to workaround the limitation
1189 ;; of auto-fill-mode whose paragraph-determination doesn't pay attention
1190 ;; to comment boundaries.
1191 (if (null compos)
1192 ;; We're not inside a comment: the prefix shouldn't match
1193 ;; a comment-starter.
1194 (not (and comment-start comment-start-skip
1195 (string-match comment-start-skip prefix)))
1196 (or
1197 ;; Accept any prefix if the current comment is not EOL-terminated.
1198 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1199 ;; Accept any prefix that starts with the same comment-start marker
1200 ;; as the current one.
1201 (when (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1202 prefix)
1203 (let ((prefix-com (comment-string-strip (match-string 0 prefix) nil t)))
1204 (string-match "\\`[ \t]*" prefix-com)
1205 (let* ((prefix-space (match-string 0 prefix-com))
1206 (prefix-indent (string-width prefix-space))
1207 (prefix-comstart (substring prefix-com (match-end 0))))
1208 (save-excursion
1209 (goto-char compos)
1210 ;; The comstart marker is the same.
1211 (and (looking-at (regexp-quote prefix-comstart))
1212 ;; The indentation as well.
1213 (or (= prefix-indent
1214 (- (current-column) (current-left-margin)))
1215 ;; Check the indentation in two different ways, just
1216 ;; to try and avoid most of the potential funny cases.
1217 (equal prefix-space
1218 (buffer-substring (point)
1219 (progn (move-to-left-margin)
1220 (point)))))))))))))
1221
7164ef13 1222
be83ecb2 1223;;;###autoload
ad679e45 1224(defun comment-indent-new-line (&optional soft)
2ab98065
SM
1225 "Break line at point and indent, continuing comment if within one.
1226This indents the body of the continued comment
1227under the previous comment line.
1228
1229This command is intended for styles where you write a comment per line,
1230starting a new comment (and terminating it if necessary) on each line.
1231If you want to continue one comment across several lines, use \\[newline-and-indent].
1232
1233If a fill column is specified, it overrides the use of the comment column
1234or comment indentation.
1235
1236The inserted newline is marked hard if variable `use-hard-newlines' is true,
1237unless optional argument SOFT is non-nil."
1238 (interactive)
1239 (comment-normalize-vars t)
59a1ce8d
SM
1240 (let (compos comin)
1241 ;; If we are not inside a comment and we only auto-fill comments,
1242 ;; don't do anything (unless no comment syntax is defined).
392f1ef5
SM
1243 (unless (and comment-start
1244 comment-auto-fill-only-comments
0603917d 1245 (not (interactive-p))
392f1ef5 1246 (not (save-excursion
59a1ce8d 1247 (prog1 (setq compos (comment-beginning))
392f1ef5 1248 (setq comin (point))))))
59a1ce8d
SM
1249
1250 ;; Now we know we should auto-fill.
88fe06af
SM
1251 ;; Insert the newline before removing empty space so that markers
1252 ;; get preserved better.
392f1ef5 1253 (if soft (insert-and-inherit ?\n) (newline 1))
88fe06af
SM
1254 (save-excursion (forward-char -1) (delete-horizontal-space))
1255 (delete-horizontal-space)
1256
7164ef13
SM
1257 (if (and fill-prefix (not adaptive-fill-mode))
1258 ;; Blindly trust a non-adaptive fill-prefix.
392f1ef5
SM
1259 (progn
1260 (indent-to-left-margin)
88fe06af 1261 (insert-before-markers-and-inherit fill-prefix))
59a1ce8d
SM
1262
1263 ;; If necessary check whether we're inside a comment.
a764440a 1264 (unless (or compos (null comment-start))
392f1ef5
SM
1265 (save-excursion
1266 (backward-char)
59a1ce8d
SM
1267 (setq compos (comment-beginning))
1268 (setq comin (point))))
1269
7164ef13
SM
1270 (cond
1271 ;; If there's an adaptive prefix, use it unless we're inside
1272 ;; a comment and the prefix is not a comment starter.
1273 ((and fill-prefix
e29d96b6 1274 (comment-valid-prefix-p fill-prefix compos))
7164ef13
SM
1275 (indent-to-left-margin)
1276 (insert-and-inherit fill-prefix))
1277 ;; If we're not inside a comment, just try to indent.
1278 ((not compos) (indent-according-to-mode))
1279 (t
59a1ce8d
SM
1280 (let* ((comment-column
1281 ;; The continuation indentation should be somewhere between
1282 ;; the current line's indentation (plus 2 for good measure)
1283 ;; and the current comment's indentation, with a preference
1284 ;; for comment-column.
1285 (save-excursion
a764440a 1286 ;; FIXME: use prev line's info rather than first line's.
59a1ce8d
SM
1287 (goto-char compos)
1288 (min (current-column) (max comment-column
1289 (+ 2 (current-indentation))))))
1290 (comstart (buffer-substring compos comin))
1291 (normalp
1292 (string-match (regexp-quote (comment-string-strip
1293 comment-start t t))
1294 comstart))
1295 (comment-end
1296 (if normalp comment-end
1297 ;; The comment starter is not the normal comment-start
1298 ;; so we can't just use comment-end.
1299 (save-excursion
1300 (goto-char compos)
1301 (if (not (comment-forward)) comment-end
1302 (comment-string-strip
1303 (buffer-substring
1304 (save-excursion (comment-enter-backward) (point))
1305 (point))
1306 nil t)))))
1307 (comment-start comstart)
a764440a
SM
1308 (continuep (or comment-multi-line
1309 (cadr (assoc comment-style comment-styles))))
59a1ce8d 1310 ;; Force comment-continue to be recreated from comment-start.
dde6824c 1311 ;; FIXME: wrong if comment-continue was set explicitly!
a764440a 1312 ;; FIXME: use prev line's continuation if available.
59a1ce8d 1313 (comment-continue nil))
a764440a
SM
1314 (if (and comment-multi-line (> (length comment-end) 0))
1315 (indent-according-to-mode)
1316 (insert-and-inherit ?\n)
1317 (forward-char -1)
1318 (comment-indent continuep)
1319 (save-excursion
1320 (let ((pt (point)))
1321 (end-of-line)
1322 (let ((comend (buffer-substring pt (point))))
1323 ;; The 1+ is to make sure we delete the \n inserted above.
1324 (delete-region pt (1+ (point)))
1325 (end-of-line 0)
1326 (insert comend))))))))))))
2ab98065 1327
83b96b22
SM
1328(provide 'newcomment)
1329
b70dd952 1330;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
83b96b22 1331;;; newcomment.el ends here