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