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