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