(lisp-mode-variables):
[bpt/emacs.git] / lisp / newcomment.el
CommitLineData
83b96b22
SM
1;;; newcomment.el --- (un)comment regions of buffers
2
771c9b97 3;; Copyright (C) 1999-2000 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
SM
7;; Keywords: comment uncomment
8;; Version: $Name: $
fae99944 9;; Revision: $Id: newcomment.el,v 1.21 2000/10/05 22:43:22 monnier Exp $
83b96b22 10
59a1ce8d
SM
11;; This file is part of GNU Emacs.
12
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
59a1ce8d
SM
15;; the Free Software Foundation; either version 2, or (at your option)
16;; any later version.
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
59a1ce8d
SM
24;; along with GNU Emacs; see the file COPYING. If not, write to the
25;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26;; Boston, MA 02111-1307, USA.
83b96b22
SM
27
28;;; Commentary:
29
771c9b97 30;; A replacement for simple.el's comment-related functions.
83b96b22
SM
31
32;;; Bugs:
33
2ab98065
SM
34;; - single-char nestable comment-start can only do the "\\s<+" stuff
35;; if the corresponding closing marker happens to be right.
771c9b97 36;; - comment-box in TeXinfo generate bogus comments @ccccc@
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
771c9b97
SM
47;; - try to align tail comments
48;; - check what c-comment-line-break-function has to say
3e569d22 49;; - spill auto-fill of comments onto the end of the next line
7a0a180a
SM
50;; - uncomment-region with a consp (for blocks) or somehow make the
51;; deletion of continuation markers less dangerous
2ab98065 52;; - drop block-comment-<foo> unless it's really used
f5215400 53;; - uncomment-region on a subpart of a comment
771c9b97 54;; - support gnu-style "multi-line with space in continue"
771c9b97
SM
55;; - somehow allow comment-dwim to use the region even if transient-mark-mode
56;; is not turned on.
83b96b22 57
bdbe3a89
SM
58;; - when auto-filling a comment, try to move the comment to the left
59;; rather than break it (if possible).
60;; - sometimes default the comment-column to the same
61;; one used on the preceding line(s).
62
83b96b22
SM
63;;; Code:
64
be83ecb2 65;;;###autoload
59a1ce8d 66(defalias 'indent-for-comment 'comment-indent)
be83ecb2 67;;;###autoload
59a1ce8d 68(defalias 'set-comment-column 'comment-set-column)
be83ecb2 69;;;###autoload
59a1ce8d 70(defalias 'kill-comment 'comment-kill)
be83ecb2 71;;;###autoload
59a1ce8d 72(defalias 'indent-new-comment-line 'comment-indent-new-line)
83b96b22 73
be83ecb2 74;;;###autoload
3e569d22
SM
75(defgroup comment nil
76 "Indenting and filling of comments."
77 :prefix "comment-"
ac87b3a9 78 :version "21.1"
3e569d22
SM
79 :group 'fill)
80
771c9b97
SM
81(defvar comment-use-syntax 'undecided
82 "Non-nil if syntax-tables can be used instead of regexps.
83Can also be `undecided' which means that a somewhat expensive test will
84be used to try to determine whether syntax-tables should be trusted
f5215400
SM
85to understand comments or not in the given buffer.
86Major modes should set this variable.")
2ab98065 87
be83ecb2 88;;;###autoload
83b96b22
SM
89(defcustom comment-column 32
90 "*Column to indent right-margin comments to.
91Setting this variable automatically makes it local to the current buffer.
92Each mode establishes a different default value for this variable; you
93can set the value for a particular mode using that mode's hook."
94 :type 'integer
3e569d22 95 :group 'comment)
83b96b22
SM
96(make-variable-buffer-local 'comment-column)
97
be83ecb2 98;;;###autoload
f5215400
SM
99(defvar comment-start nil
100 "*String to insert to start a new comment, or nil if no comment syntax.")
83b96b22 101
be83ecb2 102;;;###autoload
f5215400 103(defvar comment-start-skip nil
83b96b22
SM
104 "*Regexp to match the start of a comment plus everything up to its body.
105If there are any \\(...\\) pairs, the comment delimiter text is held to begin
f5215400 106at the place matched by the close of the first pair.")
771c9b97 107
be83ecb2 108;;;###autoload
3e569d22
SM
109(defvar comment-end-skip nil
110 "Regexp to match the end of a comment plus everything up to its body.")
83b96b22 111
be83ecb2 112;;;###autoload
f5215400 113(defvar comment-end ""
83b96b22 114 "*String to insert to end a new comment.
f5215400 115Should be an empty string if comments are terminated by end-of-line.")
83b96b22 116
be83ecb2 117;;;###autoload
87cf8421 118(defvar comment-indent-function 'comment-indent-default
83b96b22
SM
119 "Function to compute desired indentation for a comment.
120This function is called with no args with point at the beginning of
87cf8421
SM
121the comment's starting delimiter and should return either the desired
122column indentation or nil.
123If nil is returned, indentation is delegated to `indent-according-to-mode'.")
83b96b22 124
3e569d22
SM
125(defvar block-comment-start nil)
126(defvar block-comment-end nil)
83b96b22 127
771c9b97
SM
128(defvar comment-quote-nested t
129 "Non-nil if nested comments should be quoted.
130This should be locally set by each major mode if needed.")
131
132(defvar comment-continue nil
f5215400
SM
133 "Continuation string to insert for multiline comments.
134This string will be added at the beginning of each line except the very
135first one when commenting a region with a commenting style that allows
136comments to span several lines.
137It should generally have the same length as `comment-start' in order to
138preserve indentation.
139If it is nil a value will be automatically derived from `comment-start'
140by replacing its first character with a space.")
141
771c9b97 142(defvar comment-add 0
f5215400
SM
143 "How many more comment chars should be inserted by `comment-region'.
144This determines the default value of the numeric argument of `comment-region'.
145This should generally stay 0, except for a few modes like Lisp where
146it can be convenient to set it to 1 so that regions are commented with
147two semi-colons.")
2ab98065 148
2ab98065 149(defconst comment-styles
771c9b97
SM
150 '((plain . (nil nil nil nil))
151 (indent . (nil nil nil t))
152 (aligned . (nil t nil t))
153 (multi-line . (t nil nil t))
154 (extra-line . (t nil t t))
9b0d1d6e
SM
155 (box . (nil t t t))
156 (box-multi . (t t t t)))
f5215400
SM
157 "Possible comment styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
158STYLE should be a mnemonic symbol.
159MULTI specifies that comments are allowed to span multiple lines.
160ALIGN specifies that the `comment-end' markers should be aligned.
161EXTRA specifies that an extra line should be used before and after the
162 region to comment (to put the `comment-end' and `comment-start').
163INDENT specifies that the `comment-start' markers should not be put at the
164 left margin but at the current indentation of the region to comment.")
165
be83ecb2 166;;;###autoload
f5215400
SM
167(defcustom comment-style 'plain
168 "*Style to be used for `comment-region'.
169See `comment-styles' for a list of available styles."
170 :group 'comment
be83ecb2
SM
171 :type (if (boundp 'comment-styles)
172 `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles))
173 'symbol))
2ab98065 174
be83ecb2
SM
175;;;###autoload
176(defcustom comment-padding " "
f5215400
SM
177 "Padding string that `comment-region' puts between comment chars and text.
178Can also be an integer which will be automatically turned into a string
179of the corresponding number of spaces.
2ab98065
SM
180
181Extra spacing between the comment characters and the comment text
771c9b97 182makes the comment easier to read. Default is 1. nil means 0.")
2ab98065 183
be83ecb2 184;;;###autoload
3e569d22 185(defcustom comment-multi-line nil
ac87b3a9 186 "*Non-nil means \\[comment-indent-new-line] continues comments, with no new terminator or starter.
3e569d22
SM
187This is obsolete because you might as well use \\[newline-and-indent]."
188 :type 'boolean
189 :group 'comment)
190
2ab98065
SM
191;;;;
192;;;; Helpers
193;;;;
194
f5215400
SM
195(defun comment-string-strip (str beforep afterp)
196 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
197 (string-match (concat "\\`" (if beforep "\\s-*")
ad679e45 198 "\\(.*?\\)" (if afterp "\\s-*\n?")
2ab98065
SM
199 "\\'") str)
200 (match-string 1 str))
201
202(defun comment-string-reverse (s)
f5215400 203 "Return the mirror image of string S, without any trailing space."
771c9b97 204 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
2ab98065
SM
205
206(defun comment-normalize-vars (&optional noerror)
207 (if (not comment-start) (or noerror (error "No comment syntax is defined"))
208 ;; comment-use-syntax
771c9b97 209 (when (eq comment-use-syntax 'undecided)
2ab98065
SM
210 (set (make-local-variable 'comment-use-syntax)
211 (let ((st (syntax-table))
212 (cs comment-start)
213 (ce (if (string= "" comment-end) "\n" comment-end)))
771c9b97
SM
214 ;; Try to skip over a comment using forward-comment
215 ;; to see if the syntax tables properly recognize it.
2ab98065
SM
216 (with-temp-buffer
217 (set-syntax-table st)
218 (insert cs " hello " ce)
219 (goto-char (point-min))
220 (and (forward-comment 1) (eobp))))))
2ab98065
SM
221 ;; comment-padding
222 (when (integerp comment-padding)
223 (setq comment-padding (make-string comment-padding ? )))
224 ;; comment markers
225 ;;(setq comment-start (comment-string-strip comment-start t nil))
226 ;;(setq comment-end (comment-string-strip comment-end nil t))
227 ;; comment-continue
f5215400 228 (unless (or comment-continue (string= comment-end ""))
2ab98065 229 (set (make-local-variable 'comment-continue)
9b0d1d6e
SM
230 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
231 (substring comment-start 1))))
2ab98065
SM
232 ;; comment-skip regexps
233 (unless comment-start-skip
234 (set (make-local-variable 'comment-start-skip)
235 (concat "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
236 (regexp-quote (comment-string-strip comment-start t t))
237 "+\\)\\s-*")))
238 (unless comment-end-skip
239 (let ((ce (if (string= "" comment-end) "\n"
240 (comment-string-strip comment-end t t))))
241 (set (make-local-variable 'comment-end-skip)
771c9b97 242 (concat "\\s-*\\(\\s>" (if comment-quote-nested "" "+")
2ab98065 243 "\\|" (regexp-quote (substring ce 0 1))
771c9b97 244 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
2ab98065
SM
245 (regexp-quote (substring ce 1))
246 "\\)"))))))
247
f5215400
SM
248(defun comment-quote-re (str unp)
249 (concat (regexp-quote (substring str 0 1))
250 "\\\\" (if unp "+" "*")
251 (regexp-quote (substring str 1))))
252
253(defun comment-quote-nested (cs ce unp)
254 "Quote or unquote nested comments.
255If UNP is non-nil, unquote nested comment markers."
256 (setq cs (comment-string-strip cs t t))
257 (setq ce (comment-string-strip ce t t))
258 (when (and comment-quote-nested (> (length ce) 0))
259 (let ((re (concat (comment-quote-re ce unp)
260 "\\|" (comment-quote-re cs unp))))
261 (goto-char (point-min))
262 (while (re-search-forward re nil t)
263 (goto-char (match-beginning 0))
264 (forward-char 1)
265 (if unp (delete-char 1) (insert "\\"))
266 (when (= (length ce) 1)
267 ;; If the comment-end is a single char, adding a \ after that
268 ;; "first" char won't deactivate it, so we turn such a CE
269 ;; into !CS. I.e. for pascal, we turn } into !{
270 (if (not unp)
271 (when (string= (match-string 0) ce)
272 (replace-match (concat "!" cs) t t))
273 (when (and (< (point-min) (match-beginning 0))
274 (string= (buffer-substring (1- (match-beginning 0))
275 (1- (match-end 0)))
276 (concat "!" cs)))
277 (backward-char 2)
278 (delete-char (- (match-end 0) (match-beginning 0)))
279 (insert ce))))))))
2ab98065
SM
280
281;;;;
282;;;; Navigation
283;;;;
284
ad679e45 285(defun comment-search-forward (limit &optional noerror)
771c9b97
SM
286 "Find a comment start between point and LIMIT.
287Moves point to inside the comment and returns the position of the
288comment-starter. If no comment is found, moves point to LIMIT
e8fe7d39 289and raises an error or returns nil of NOERROR is non-nil."
2ab98065 290 (if (not comment-use-syntax)
9b0d1d6e
SM
291 (if (re-search-forward comment-start-skip limit noerror)
292 (or (match-end 1) (match-beginning 0))
293 (goto-char limit)
294 (unless noerror (error "No comment")))
ad679e45
SM
295 (let* ((pt (point))
296 ;; Assume (at first) that pt is outside of any string.
297 (s (parse-partial-sexp pt (or limit (point-max)) nil nil nil t)))
298 (when (and (nth 8 s) (nth 3 s))
299 ;; The search ended inside a string. Try to see if it
300 ;; works better when we assume that pt is inside a string.
301 (setq s (parse-partial-sexp
302 pt (or limit (point-max)) nil nil
303 (list nil nil nil (nth 3 s) nil nil nil nil)
304 t)))
305 (if (not (and (nth 8 s) (not (nth 3 s))))
306 (unless noerror (error "No comment"))
307 ;; We found the comment.
9b0d1d6e 308 (let ((pos (point))
ad679e45 309 (start (nth 8 s))
9b0d1d6e 310 (bol (line-beginning-position))
ad679e45
SM
311 (end nil))
312 (while (and (null end) (>= (point) bol))
313 (if (looking-at comment-start-skip)
314 (setq end (min (or limit (point-max)) (match-end 0)))
315 (backward-char)))
9b0d1d6e 316 (goto-char (or end pos))
ad679e45 317 start)))))
2ab98065
SM
318
319(defun comment-search-backward (&optional limit noerror)
320 "Find a comment start between LIMIT and point.
771c9b97
SM
321Moves point to inside the comment and returns the position of the
322comment-starter. If no comment is found, moves point to LIMIT
2ab98065 323and raises an error or returns nil of NOERROR is non-nil."
ad679e45
SM
324 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
325 ;; stop there. This can be rather bad in general, but since
326 ;; comment-search-backward is only used to find the comment-column (in
327 ;; comment-set-column) and to find the comment-start string (via
328 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
2ab98065
SM
329 (if (not (re-search-backward comment-start-skip limit t))
330 (unless noerror (error "No comment"))
331 (beginning-of-line)
332 (let* ((end (match-end 0))
333 (cs (comment-search-forward end t))
334 (pt (point)))
335 (if (not cs)
336 (progn (beginning-of-line)
337 (comment-search-backward limit noerror))
338 (while (progn (goto-char cs)
339 (comment-forward)
340 (and (< (point) end)
341 (setq cs (comment-search-forward end t))))
342 (setq pt (point)))
343 (goto-char pt)
344 cs))))
345
346(defun comment-beginning ()
771c9b97
SM
347 "Find the beginning of the enclosing comment.
348Returns nil if not inside a comment, else moves point and returns
2ab98065
SM
349the same as `comment-search-forward'."
350 (let ((pt (point))
351 (cs (comment-search-backward nil t)))
ad679e45 352 (when cs
392f1ef5
SM
353 (if (save-excursion
354 (goto-char cs)
355 (if (comment-forward 1) (> (point) pt) (eobp)))
ad679e45
SM
356 cs
357 (goto-char pt)
358 nil))))
2ab98065
SM
359
360(defun comment-forward (&optional n)
361 "Skip forward over N comments.
362Just like `forward-comment' but only for positive N
363and can use regexps instead of syntax."
364 (setq n (or n 1))
365 (if (< n 0) (error "No comment-backward")
366 (if comment-use-syntax (forward-comment n)
367 (while (> n 0)
368 (skip-syntax-forward " ")
59a1ce8d
SM
369 (setq n
370 (if (and (looking-at comment-start-skip)
371 (re-search-forward comment-end-skip nil 'move))
372 (1- n) -1)))
2ab98065
SM
373 (= n 0))))
374
375(defun comment-enter-backward ()
376 "Move from the end of a comment to the end of its content.
771c9b97 377Point is assumed to be just at the end of a comment."
2ab98065
SM
378 (if (bolp)
379 ;; comment-end = ""
380 (progn (backward-char) (skip-syntax-backward " "))
381 (let ((end (point)))
382 (beginning-of-line)
383 (save-restriction
384 (narrow-to-region (point) end)
ad679e45
SM
385 (if (re-search-forward (concat comment-end-skip "\\'") nil t)
386 (goto-char (match-beginning 0))
387 ;; comment-end-skip not found probably because it was not set right.
388 ;; Since \\s> should catch the single-char case, we'll blindly
389 ;; assume we're at the end of a two-char comment-end.
390 (goto-char (point-max))
391 (backward-char 2)
392 (skip-chars-backward (string (char-after)))
393 (skip-syntax-backward " "))))))
2ab98065
SM
394
395;;;;
396;;;; Commands
397;;;;
398
fae99944 399;;;###autoload
87cf8421
SM
400(defun comment-indent-default ()
401 "Default for `comment-indent-function'."
402 (if (looking-at "\\s<\\s<\\s<") 0
403 (when (or (/= (current-column) (current-indentation))
404 (and (> comment-add 0) (looking-at "\\s<\\S<")))
405 comment-column)))
406
be83ecb2 407;;;###autoload
3e569d22 408(defun comment-indent (&optional continue)
2ab98065
SM
409 "Indent this line's comment to comment column, or insert an empty comment.
410If CONTINUE is non-nil, use the `comment-continuation' markers if any."
83b96b22 411 (interactive "*")
ad679e45 412 (comment-normalize-vars)
83b96b22
SM
413 (let* ((empty (save-excursion (beginning-of-line)
414 (looking-at "[ \t]*$")))
f5215400 415 (starter (or (and continue comment-continue)
2ab98065 416 (and empty block-comment-start) comment-start))
f5215400 417 (ender (or (and continue comment-continue "")
2ab98065 418 (and empty block-comment-end) comment-end)))
83b96b22
SM
419 (cond
420 ((null starter)
421 (error "No comment syntax defined"))
ad679e45 422 (t (let* ((eolpos (line-end-position))
83b96b22
SM
423 cpos indent begpos)
424 (beginning-of-line)
9b0d1d6e
SM
425 (if (not (setq begpos (comment-search-forward eolpos t)))
426 (setq begpos (point))
e8fe7d39
SM
427 (setq cpos (point-marker))
428 (goto-char begpos))
87cf8421 429 ;; Compute desired indent.
bdbe3a89 430 (setq indent (funcall comment-indent-function))
87cf8421
SM
431 (if (not indent)
432 ;; comment-indent-function refuses delegates to indent.
433 (indent-according-to-mode)
434 ;; Avoid moving comments past the fill-column.
435 (setq indent
436 (min indent
437 (+ (current-column)
438 (- fill-column
439 (save-excursion (end-of-line) (current-column))))))
440 (if (= (current-column) indent)
441 (goto-char begpos)
442 ;; If that's different from current, change it.
443 (skip-chars-backward " \t")
444 (delete-region (point) begpos)
445 (indent-to (if (bolp) indent (max indent (1+ (current-column))))))
446 ;; An existing comment?
447 (if cpos
448 (progn (goto-char cpos) (set-marker cpos nil))
449 ;; No, insert one.
450 (insert starter)
451 (save-excursion
452 (insert ender)))))))))
83b96b22 453
be83ecb2 454;;;###autoload
3e569d22 455(defun comment-set-column (arg)
83b96b22 456 "Set the comment column based on point.
2ab98065 457With no ARG, set the comment column to the current column.
83b96b22
SM
458With just minus as arg, kill any comment on this line.
459With any other arg, set comment column to indentation of the previous comment
460 and then align or create a comment on this line at that column."
461 (interactive "P")
e8fe7d39 462 (cond
ad679e45 463 ((eq arg '-) (comment-kill nil))
e8fe7d39
SM
464 (arg
465 (save-excursion
466 (beginning-of-line)
2ab98065 467 (comment-search-backward)
e8fe7d39 468 (beginning-of-line)
ad679e45 469 (goto-char (comment-search-forward (line-end-position)))
83b96b22 470 (setq comment-column (current-column))
e8fe7d39 471 (message "Comment column set to %d" comment-column))
ad679e45 472 (comment-indent))
e8fe7d39 473 (t (setq comment-column (current-column))
83b96b22
SM
474 (message "Comment column set to %d" comment-column))))
475
be83ecb2 476;;;###autoload
3e569d22 477(defun comment-kill (arg)
7a0a180a
SM
478 "Kill the comment on this line, if any.
479With prefix ARG, kill comments on that many lines starting with this one."
480 (interactive "P")
ad679e45
SM
481 (dotimes (_ (prefix-numeric-value arg))
482 (save-excursion
483 (beginning-of-line)
484 (let ((cs (comment-search-forward (line-end-position) t)))
485 (when cs
486 (goto-char cs)
487 (skip-syntax-backward " ")
488 (setq cs (point))
489 (comment-forward)
490 (kill-region cs (if (bolp) (1- (point)) (point)))
491 (indent-according-to-mode))))
492 (if arg (forward-line 1))))
7a0a180a 493
2ab98065
SM
494(defun comment-padright (str &optional n)
495 "Construct a string composed of STR plus `comment-padding'.
f5215400 496It also adds N copies of the last non-whitespace chars of STR.
2ab98065 497If STR already contains padding, the corresponding amount is
f5215400
SM
498ignored from `comment-padding'.
499N defaults to 0.
771c9b97 500If N is `re', a regexp is returned instead, that would match
f5215400 501the string for any N."
2ab98065
SM
502 (setq n (or n 0))
503 (when (and (stringp str) (not (string= "" str)))
f5215400 504 ;; Separate the actual string from any leading/trailing padding
3e569d22 505 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
f5215400
SM
506 (let ((s (match-string 1 str)) ;actual string
507 (lpad (substring str 0 (match-beginning 1))) ;left padding
508 (rpad (concat (substring str (match-end 1)) ;original right padding
509 (substring comment-padding ;additional right padding
3e569d22 510 (min (- (match-end 0) (match-end 1))
9b0d1d6e
SM
511 (length comment-padding)))))
512 ;; We can only duplicate C if the comment-end has multiple chars
513 ;; or if comments can be nested, else the comment-end `}' would
514 ;; be turned into `}}}' where only the first ends the comment
515 ;; and the rest becomes bogus junk.
516 (multi (not (and comment-quote-nested
517 ;; comment-end is a single char
518 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
f5215400 519 (if (not (symbolp n))
9b0d1d6e 520 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
f5215400
SM
521 ;; construct a regexp that would match anything from just S
522 ;; to any possible output of this function for any N.
523 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
524 lpad "") ;padding is not required
9b0d1d6e
SM
525 (regexp-quote s)
526 (when multi "+") ;the last char of S might be repeated
f5215400
SM
527 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
528 rpad "")))))) ;padding is not required
2ab98065
SM
529
530(defun comment-padleft (str &optional n)
531 "Construct a string composed of `comment-padding' plus STR.
f5215400 532It also adds N copies of the first non-whitespace chars of STR.
2ab98065 533If STR already contains padding, the corresponding amount is
f5215400
SM
534ignored from `comment-padding'.
535N defaults to 0.
771c9b97 536If N is `re', a regexp is returned instead, that would match
2ab98065
SM
537 the string for any N."
538 (setq n (or n 0))
539 (when (and (stringp str) (not (string= "" str)))
f5215400 540 ;; Only separate the left pad because we assume there is no right pad.
2ab98065
SM
541 (string-match "\\`\\s-*" str)
542 (let ((s (substring str (match-end 0)))
543 (pad (concat (substring comment-padding
544 (min (- (match-end 0) (match-beginning 0))
545 (length comment-padding)))
546 (match-string 0 str)))
f5215400
SM
547 (c (aref str (match-end 0))) ;the first non-space char of STR
548 ;; We can only duplicate C if the comment-end has multiple chars
549 ;; or if comments can be nested, else the comment-end `}' would
550 ;; be turned into `}}}' where only the first ends the comment
551 ;; and the rest becomes bogus junk.
552 (multi (not (and comment-quote-nested
553 ;; comment-end is a single char
554 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
555 (if (not (symbolp n))
556 (concat pad (when multi (make-string n c)) s)
557 ;; Construct a regexp that would match anything from just S
558 ;; to any possible output of this function for any N.
559 ;; We match any number of leading spaces because this regexp will
560 ;; be used for uncommenting where we might want to remove
561 ;; uncomment markers with arbitrary leading space (because
562 ;; they were aligned).
563 (concat "\\s-*"
564 (if multi (concat (regexp-quote (string c)) "*"))
565 (regexp-quote s))))))
83b96b22 566
be83ecb2 567;;;###autoload
7a0a180a
SM
568(defun uncomment-region (beg end &optional arg)
569 "Uncomment each line in the BEG..END region.
f5215400
SM
570The numeric prefix ARG can specify a number of chars to remove from the
571comment markers."
83b96b22
SM
572 (interactive "*r\nP")
573 (comment-normalize-vars)
574 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
575 (save-excursion
7a0a180a 576 (goto-char beg)
f5215400 577 (setq end (copy-marker end))
7a0a180a 578 (let ((numarg (prefix-numeric-value arg))
2ab98065 579 spt)
7a0a180a 580 (while (and (< (point) end)
2ab98065
SM
581 (setq spt (comment-search-forward end t)))
582 (let* ((ipt (point))
f5215400 583 ;; Find the end of the comment.
e8fe7d39 584 (ept (progn
2ab98065
SM
585 (goto-char spt)
586 (unless (comment-forward)
e8fe7d39 587 (error "Can't find the comment end"))
f5215400
SM
588 (point)))
589 (box nil)
590 (ccs comment-continue)
2ab98065 591 (srei (comment-padright ccs 're))
3e569d22 592 (sre (and srei (concat "^\\s-*?\\(" srei "\\)"))))
e8fe7d39
SM
593 (save-restriction
594 (narrow-to-region spt ept)
f5215400 595 ;; Remove the comment-start.
2ab98065
SM
596 (goto-char ipt)
597 (skip-syntax-backward " ")
9b0d1d6e
SM
598 ;; Check for special `=' used sometimes in comment-box.
599 (when (and (= (- (point) (point-min)) 1) (looking-at "=\\{7\\}"))
600 (skip-chars-forward "="))
f5215400 601 ;; A box-comment starts with a looong comment-start marker.
2ab98065 602 (when (> (- (point) (point-min) (length comment-start)) 7)
f5215400 603 (setq box t))
2ab98065
SM
604 (when (looking-at (regexp-quote comment-padding))
605 (goto-char (match-end 0)))
606 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
607 (goto-char (match-end 0)))
3e569d22
SM
608 (if (null arg) (delete-region (point-min) (point))
609 (skip-syntax-backward " ")
610 (delete-char (- numarg)))
2ab98065 611
f5215400 612 ;; Remove the end-comment (and leading padding and such).
2ab98065 613 (goto-char (point-max)) (comment-enter-backward)
9b0d1d6e 614 ;; Check for special `=' used sometimes in comment-box.
6dcd3806
SM
615 (when (= (- (point-max) (point)) 1)
616 (let ((pos (point)))
617 ;; skip `=' but only if there are at least 7.
618 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
9b0d1d6e 619 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
2ab98065 620 (when (and (bolp) (not (bobp))) (backward-char))
f5215400 621 (if (null arg) (delete-region (point) (point-max))
3e569d22
SM
622 (skip-syntax-forward " ")
623 (delete-char numarg)))
e8fe7d39 624
f5215400
SM
625 ;; Unquote any nested end-comment.
626 (comment-quote-nested comment-start comment-end t)
627
628 ;; Eliminate continuation markers as well.
629 (when sre
630 (let* ((cce (comment-string-reverse (or comment-continue
631 comment-start)))
632 (erei (and box (comment-padleft cce 're)))
633 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
7a0a180a 634 (goto-char (point-min))
f5215400
SM
635 (while (progn
636 (if (and ere (re-search-forward
637 ere (line-end-position) t))
638 (replace-match "" t t nil (if (match-end 2) 2 1))
639 (setq ere nil))
640 (forward-line 1)
641 (re-search-forward sre (line-end-position) t))
2ab98065 642 (replace-match "" t t nil (if (match-end 2) 2 1)))))
f5215400
SM
643 ;; Go the the end for the next comment.
644 (goto-char (point-max)))))
645 (set-marker end nil))))
83b96b22 646
aac88001 647(defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
ad679e45
SM
648 "Make the leading and trailing extra lines.
649This is used for `extra-line' style (or `box' style if BLOCK is specified)."
9b0d1d6e
SM
650 (let ((eindent 0))
651 (if (not block)
652 ;; Try to match CS and CE's content so they align aesthetically.
653 (progn
654 (setq ce (comment-string-strip ce t t))
655 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
656 (setq eindent
657 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
658 0))))
659 ;; box comment
660 (let* ((width (- max-indent min-indent))
661 (s (concat cs "a=m" cce))
662 (e (concat ccs "a=m" ce))
663 (c (if (string-match ".*\\S-\\S-" cs)
664 (aref cs (1- (match-end 0))) ?=))
3fc5b4e2 665 (_ (string-match "\\s-*a=m\\s-*" s))
9b0d1d6e
SM
666 (fill
667 (make-string (+ width (- (match-end 0)
668 (match-beginning 0) (length cs) 3)) c)))
aac88001 669 (setq cs (replace-match fill t t s))
3fc5b4e2 670 (string-match "\\s-*a=m\\s-*" e)
9b0d1d6e
SM
671 (setq ce (replace-match fill t t e))))
672 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
673 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
aac88001
SM
674
675(def-edebug-spec comment-with-narrowing t)
676(put 'comment-with-narrowing 'lisp-indent-function 2)
677(defmacro comment-with-narrowing (beg end &rest body)
678 "Execute BODY with BEG..END narrowing.
679Space is added (and then removed) at the beginning for the text's
680indentation to be kept as it was before narrowing."
59a1ce8d
SM
681 (let ((bindent (make-symbol "bindent")))
682 `(let ((,bindent (save-excursion (goto-char beg) (current-column))))
683 (save-restriction
684 (narrow-to-region beg end)
685 (goto-char (point-min))
686 (insert (make-string ,bindent ? ))
687 (prog1
688 (progn ,@body)
689 ;; remove the bindent
690 (save-excursion
691 (goto-char (point-min))
692 (when (looking-at " *")
693 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
aac88001 694 (delete-char n)
59a1ce8d
SM
695 (setq ,bindent (- ,bindent n))))
696 (end-of-line)
697 (let ((e (point)))
698 (beginning-of-line)
699 (while (and (> ,bindent 0) (re-search-forward " *" e t))
700 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
701 (goto-char (match-beginning 0))
702 (delete-char n)
703 (setq ,bindent (- ,bindent n)))))))))))
aac88001 704
771c9b97
SM
705(defun comment-region-internal (beg end cs ce
706 &optional ccs cce block lines indent)
f5215400 707 "Comment region BEG..END.
4125ec7e
SM
708CS and CE are the comment start resp end string.
709CCS and CCE are the comment continuation strings for the start resp end
f5215400
SM
710of lines (default to CS and CE).
711BLOCK indicates that end of lines should be marked with either CCE, CE or CS
712\(if CE is empty) and that those markers should be aligned.
713LINES indicates that an extra lines will be used at the beginning and end
714of the region for CE and CS.
715INDENT indicates to put CS and CCS at the current indentation of the region
716rather than at left margin."
59a1ce8d 717 ;;(assert (< beg end))
83b96b22 718 (let ((no-empty t))
f5215400 719 ;; Sanitize CE and CCE.
83b96b22
SM
720 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
721 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
f5215400
SM
722 ;; If CE is empty, multiline cannot be used.
723 (unless ce (setq ccs nil cce nil))
724 ;; Should we mark empty lines as well ?
83b96b22 725 (if (or ccs block lines) (setq no-empty nil))
f5215400 726 ;; Make sure we have end-markers for BLOCK mode.
2ab98065 727 (when block (unless ce (setq ce (comment-string-reverse cs))))
f5215400
SM
728 ;; If BLOCK is not requested, we don't need CCE.
729 (unless block (setq cce nil))
730 ;; Continuation defaults to the same as CS and CE.
731 (unless ccs (setq ccs cs cce ce))
7a0a180a 732
83b96b22 733 (save-excursion
aac88001 734 (goto-char end)
f5215400
SM
735 ;; If the end is not at the end of a line and the comment-end
736 ;; is implicit (i.e. a newline), explicitly insert a newline.
aac88001
SM
737 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
738 (comment-with-narrowing beg end
f5215400 739 (let ((min-indent (point-max))
83b96b22
SM
740 (max-indent 0))
741 (goto-char (point-min))
f5215400
SM
742 ;; Quote any nested comment marker
743 (comment-quote-nested comment-start comment-end nil)
744
745 ;; Loop over all lines to find the needed indentations.
4125ec7e 746 (goto-char (point-min))
f5215400
SM
747 (while
748 (progn
749 (unless (looking-at "[ \t]*$")
750 (setq min-indent (min min-indent (current-indentation))))
751 (end-of-line)
752 (setq max-indent (max max-indent (current-column)))
753 (not (or (eobp) (progn (forward-line) nil)))))
754
755 ;; Inserting ccs can change max-indent by (1- tab-width).
59a1ce8d
SM
756 (setq max-indent
757 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
771c9b97 758 (unless indent (setq min-indent 0))
83b96b22 759
aac88001 760 ;; make the leading and trailing lines if requested
83b96b22 761 (when lines
771c9b97
SM
762 (let ((csce
763 (comment-make-extra-lines
764 cs ce ccs cce min-indent max-indent block)))
765 (setq cs (car csce))
766 (setq ce (cdr csce))))
83b96b22
SM
767
768 (goto-char (point-min))
769 ;; Loop over all lines from BEG to END.
f5215400
SM
770 (while
771 (progn
772 (unless (and no-empty (looking-at "[ \t]*$"))
773 (move-to-column min-indent t)
774 (insert cs) (setq cs ccs) ;switch to CCS after the first line
775 (end-of-line)
776 (if (eobp) (setq cce ce))
777 (when cce
778 (when block (move-to-column max-indent t))
779 (insert cce)))
780 (end-of-line)
781 (not (or (eobp) (progn (forward-line) nil))))))))))
83b96b22 782
be83ecb2 783;;;###autoload
83b96b22
SM
784(defun comment-region (beg end &optional arg)
785 "Comment or uncomment each line in the region.
786With just \\[universal-prefix] prefix arg, uncomment each line in region BEG..END.
787Numeric prefix arg ARG means use ARG comment characters.
788If ARG is negative, delete that many comment characters instead.
be83ecb2
SM
789By default, comments start at the left margin, are terminated on each line,
790even for syntax in which newline does not end the comment and blank lines
791do not get comments. This can be changed with `comment-style'.
83b96b22
SM
792
793The strings used as comment starts are built from
794`comment-start' without trailing spaces and `comment-padding'."
795 (interactive "*r\nP")
796 (comment-normalize-vars)
797 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
2ab98065 798 (let* ((numarg (prefix-numeric-value arg))
771c9b97 799 (add comment-add)
2ab98065
SM
800 (style (cdr (assoc comment-style comment-styles)))
801 (lines (nth 2 style))
802 (block (nth 1 style))
803 (multi (nth 0 style)))
83b96b22
SM
804 (save-excursion
805 ;; we use `chars' instead of `syntax' because `\n' might be
806 ;; of end-comment syntax rather than of whitespace syntax.
807 ;; sanitize BEG and END
808 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
809 (setq beg (max beg (point)))
810 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
811 (setq end (min end (point)))
812 (if (>= beg end) (error "Nothing to comment"))
813
83b96b22
SM
814 ;; sanitize LINES
815 (setq lines
816 (and
9b0d1d6e 817 lines ;; multi
83b96b22
SM
818 (progn (goto-char beg) (beginning-of-line)
819 (skip-syntax-forward " ")
820 (>= (point) beg))
821 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
822 (<= (point) end))
771c9b97 823 (or (not (string= "" comment-end)) block)
2ab98065 824 (progn (goto-char beg) (search-forward "\n" end t)))))
83b96b22 825
2ab98065
SM
826 ;; don't add end-markers just because the user asked for `block'
827 (unless (or lines (string= "" comment-end)) (setq block nil))
828
83b96b22
SM
829 (cond
830 ((consp arg) (uncomment-region beg end))
831 ((< numarg 0) (uncomment-region beg end (- numarg)))
832 (t
59a1ce8d
SM
833 (setq numarg (if (and (null arg) (= (length comment-start) 1))
834 add (1- numarg)))
83b96b22
SM
835 (comment-region-internal
836 beg end
3e569d22
SM
837 (let ((s (comment-padright comment-start numarg)))
838 (if (string-match comment-start-skip s) s
839 (comment-padright comment-start)))
840 (let ((s (comment-padleft comment-end numarg)))
841 (and s (if (string-match comment-end-skip s) s
842 (comment-padright comment-end))))
f5215400
SM
843 (if multi (comment-padright comment-continue numarg))
844 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
83b96b22 845 block
771c9b97
SM
846 lines
847 (nth 3 style))))))
848
849(defun comment-box (beg end &optional arg)
850 "Comment out the BEG..END region, putting it inside a box.
851The numeric prefix ARG specifies how many characters to add to begin- and
852end- comment markers additionally to what `comment-add' already specifies."
853 (interactive "*r\np")
9b0d1d6e
SM
854 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
855 'box-multi 'box)))
771c9b97 856 (comment-region beg end (+ comment-add arg))))
83b96b22 857
be83ecb2 858;;;###autoload
2ab98065 859(defun comment-dwim (arg)
ad679e45
SM
860 "Call the comment command you want (Do What I Mean).
861If the region is active and `transient-mark-mode' is on, call
862 `comment-region' (unless it only consists in comments, in which
863 case it calls `uncomment-region').
2ab98065 864Else, if the current line is empty, insert a comment and indent it.
ad679e45
SM
865Else if a prefix ARG is specified, call `comment-kill'.
866Else, call `comment-indent'."
2ab98065
SM
867 (interactive "*P")
868 (comment-normalize-vars)
771c9b97 869 (if (and mark-active transient-mark-mode)
2ab98065
SM
870 (let ((beg (min (point) (mark)))
871 (end (max (point) (mark))))
872 (if (save-excursion ;; check for already commented region
873 (goto-char beg)
874 (comment-forward (point-max))
875 (<= end (point)))
876 (uncomment-region beg end arg)
877 (comment-region beg end arg)))
878 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
ad679e45
SM
879 ;; FIXME: If there's no comment to kill on this line and ARG is
880 ;; specified, calling comment-kill is not very clever.
881 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
2ab98065 882 (let ((add (if arg (prefix-numeric-value arg)
771c9b97 883 (if (= (length comment-start) 1) comment-add 0))))
2ab98065
SM
884 (insert (comment-padright comment-start add))
885 (save-excursion
886 (unless (string= "" comment-end)
887 (insert (comment-padleft comment-end add)))
888 (indent-according-to-mode))))))
889
392f1ef5
SM
890(defcustom comment-auto-fill-only-comments nil
891 "Non-nil means to only auto-fill inside comments.
892This has no effect in modes that do not define a comment syntax."
893 :type 'boolean
894 :group 'comment)
895
be83ecb2 896;;;###autoload
ad679e45 897(defun comment-indent-new-line (&optional soft)
2ab98065
SM
898 "Break line at point and indent, continuing comment if within one.
899This indents the body of the continued comment
900under the previous comment line.
901
902This command is intended for styles where you write a comment per line,
903starting a new comment (and terminating it if necessary) on each line.
904If you want to continue one comment across several lines, use \\[newline-and-indent].
905
906If a fill column is specified, it overrides the use of the comment column
907or comment indentation.
908
909The inserted newline is marked hard if variable `use-hard-newlines' is true,
910unless optional argument SOFT is non-nil."
911 (interactive)
912 (comment-normalize-vars t)
59a1ce8d
SM
913 (let (compos comin)
914 ;; If we are not inside a comment and we only auto-fill comments,
915 ;; don't do anything (unless no comment syntax is defined).
392f1ef5
SM
916 (unless (and comment-start
917 comment-auto-fill-only-comments
918 (not (save-excursion
59a1ce8d 919 (prog1 (setq compos (comment-beginning))
392f1ef5 920 (setq comin (point))))))
59a1ce8d
SM
921
922 ;; Now we know we should auto-fill.
392f1ef5 923 (delete-region (progn (skip-chars-backward " \t") (point))
59a1ce8d 924 (progn (skip-chars-forward " \t") (point)))
392f1ef5
SM
925 (if soft (insert-and-inherit ?\n) (newline 1))
926 (if fill-prefix
927 (progn
928 (indent-to-left-margin)
929 (insert-and-inherit fill-prefix))
59a1ce8d
SM
930
931 ;; If necessary check whether we're inside a comment.
932 (unless (or comment-multi-line compos (null comment-start))
392f1ef5
SM
933 (save-excursion
934 (backward-char)
59a1ce8d
SM
935 (setq compos (comment-beginning))
936 (setq comin (point))))
937
938 ;; If we're not inside a comment, just try to indent.
939 (if (not compos) (indent-according-to-mode)
940 (let* ((comment-column
941 ;; The continuation indentation should be somewhere between
942 ;; the current line's indentation (plus 2 for good measure)
943 ;; and the current comment's indentation, with a preference
944 ;; for comment-column.
945 (save-excursion
946 (goto-char compos)
947 (min (current-column) (max comment-column
948 (+ 2 (current-indentation))))))
949 (comstart (buffer-substring compos comin))
950 (normalp
951 (string-match (regexp-quote (comment-string-strip
952 comment-start t t))
953 comstart))
954 (comment-end
955 (if normalp comment-end
956 ;; The comment starter is not the normal comment-start
957 ;; so we can't just use comment-end.
958 (save-excursion
959 (goto-char compos)
960 (if (not (comment-forward)) comment-end
961 (comment-string-strip
962 (buffer-substring
963 (save-excursion (comment-enter-backward) (point))
964 (point))
965 nil t)))))
966 (comment-start comstart)
967 ;; Force comment-continue to be recreated from comment-start.
968 (comment-continue nil))
969 (insert-and-inherit ?\n)
970 (forward-char -1)
971 (comment-indent (cadr (assoc comment-style comment-styles)))
972 (save-excursion
973 (let ((pt (point)))
974 (end-of-line)
975 (let ((comend (buffer-substring pt (point))))
976 ;; The 1+ is to make sure we delete the \n inserted above.
977 (delete-region pt (1+ (point)))
978 (beginning-of-line)
979 (backward-char)
980 (insert comend)
981 (forward-char))))))))))
2ab98065 982
83b96b22
SM
983(provide 'newcomment)
984
83b96b22 985;;; newcomment.el ends here