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
9 ;; Revision: $Id: newcomment.el,v 1.14 2000/05/23 20:06:10 monnier Exp $
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
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.
23 ;; You should have received a copy of the GNU General Public License
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.
30 ;; A replacement for simple.el's comment-related functions.
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.
47 ;; - try to align tail comments
48 ;; - check what c-comment-line-break-function has to say
49 ;; - spill auto-fill of comments onto the end of the next line
50 ;; - uncomment-region with a consp (for blocks) or somehow make the
51 ;; deletion of continuation markers less dangerous
52 ;; - drop block-comment-<foo> unless it's really used
53 ;; - uncomment-region on a subpart of a comment
54 ;; - support gnu-style "multi-line with space in continue"
55 ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
61 (defalias 'indent-for-comment 'comment-indent)
63 (defalias 'set-comment-column 'comment-set-column)
65 (defalias 'kill-comment 'comment-kill)
67 (defalias 'indent-new-comment-line 'comment-indent-new-line)
71 "Indenting and filling of comments."
75 (defvar comment-use-syntax 'undecided
76 "Non-nil if syntax-tables can be used instead of regexps.
77 Can also be `undecided' which means that a somewhat expensive test will
78 be used to try to determine whether syntax-tables should be trusted
79 to understand comments or not in the given buffer.
80 Major modes should set this variable.")
83 (defcustom comment-column 32
84 "*Column to indent right-margin comments to.
85 Setting this variable automatically makes it local to the current buffer.
86 Each mode establishes a different default value for this variable; you
87 can set the value for a particular mode using that mode's hook."
90 (make-variable-buffer-local 'comment-column)
93 (defvar comment-start nil
94 "*String to insert to start a new comment, or nil if no comment syntax.")
97 (defvar comment-start-skip nil
98 "*Regexp to match the start of a comment plus everything up to its body.
99 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
100 at the place matched by the close of the first pair.")
103 (defvar comment-end-skip nil
104 "Regexp to match the end of a comment plus everything up to its body.")
107 (defvar comment-end ""
108 "*String to insert to end a new comment.
109 Should be an empty string if comments are terminated by end-of-line.")
112 (defvar comment-indent-function
113 (lambda () comment-column)
114 "Function to compute desired indentation for a comment.
115 This function is called with no args with point at the beginning of
116 the comment's starting delimiter.")
118 (defvar block-comment-start nil)
119 (defvar block-comment-end nil)
121 (defvar comment-quote-nested t
122 "Non-nil if nested comments should be quoted.
123 This should be locally set by each major mode if needed.")
125 (defvar comment-continue nil
126 "Continuation string to insert for multiline comments.
127 This string will be added at the beginning of each line except the very
128 first one when commenting a region with a commenting style that allows
129 comments to span several lines.
130 It should generally have the same length as `comment-start' in order to
131 preserve indentation.
132 If it is nil a value will be automatically derived from `comment-start'
133 by replacing its first character with a space.")
135 (defvar comment-add 0
136 "How many more comment chars should be inserted by `comment-region'.
137 This determines the default value of the numeric argument of `comment-region'.
138 This should generally stay 0, except for a few modes like Lisp where
139 it can be convenient to set it to 1 so that regions are commented with
142 (defconst comment-styles
143 '((plain . (nil nil nil nil))
144 (indent . (nil nil nil t))
145 (aligned . (nil t nil t))
146 (multi-line . (t nil nil t))
147 (extra-line . (t nil t t))
149 (box-multi . (t t t t)))
150 "Possible comment styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
151 STYLE should be a mnemonic symbol.
152 MULTI specifies that comments are allowed to span multiple lines.
153 ALIGN specifies that the `comment-end' markers should be aligned.
154 EXTRA specifies that an extra line should be used before and after the
155 region to comment (to put the `comment-end' and `comment-start').
156 INDENT specifies that the `comment-start' markers should not be put at the
157 left margin but at the current indentation of the region to comment.")
160 (defcustom comment-style 'plain
161 "*Style to be used for `comment-region'.
162 See `comment-styles' for a list of available styles."
164 :type (if (boundp 'comment-styles)
165 `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles))
169 (defcustom comment-padding " "
170 "Padding string that `comment-region' puts between comment chars and text.
171 Can also be an integer which will be automatically turned into a string
172 of the corresponding number of spaces.
174 Extra spacing between the comment characters and the comment text
175 makes the comment easier to read. Default is 1. nil means 0.")
178 (defcustom comment-multi-line nil
179 "*Non-nil means \\[indent-new-comment-line] should continue same comment
180 on new line, with no new terminator or starter.
181 This is obsolete because you might as well use \\[newline-and-indent]."
189 (defun comment-string-strip (str beforep afterp)
190 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
191 (string-match (concat "\\`" (if beforep "\\s-*")
192 "\\(.*?\\)" (if afterp "\\s-*\n?")
194 (match-string 1 str))
196 (defun comment-string-reverse (s)
197 "Return the mirror image of string S, without any trailing space."
198 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
200 (defun comment-normalize-vars (&optional noerror)
201 (if (not comment-start) (or noerror (error "No comment syntax is defined"))
202 ;; comment-use-syntax
203 (when (eq comment-use-syntax 'undecided)
204 (set (make-local-variable 'comment-use-syntax)
205 (let ((st (syntax-table))
207 (ce (if (string= "" comment-end) "\n" comment-end)))
208 ;; Try to skip over a comment using forward-comment
209 ;; to see if the syntax tables properly recognize it.
211 (set-syntax-table st)
212 (insert cs " hello " ce)
213 (goto-char (point-min))
214 (and (forward-comment 1) (eobp))))))
216 (when (integerp comment-padding)
217 (setq comment-padding (make-string comment-padding ? )))
219 ;;(setq comment-start (comment-string-strip comment-start t nil))
220 ;;(setq comment-end (comment-string-strip comment-end nil t))
222 (unless (or comment-continue (string= comment-end ""))
223 (set (make-local-variable 'comment-continue)
224 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
225 (substring comment-start 1))))
226 ;; comment-skip regexps
227 (unless comment-start-skip
228 (set (make-local-variable 'comment-start-skip)
229 (concat "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
230 (regexp-quote (comment-string-strip comment-start t t))
232 (unless comment-end-skip
233 (let ((ce (if (string= "" comment-end) "\n"
234 (comment-string-strip comment-end t t))))
235 (set (make-local-variable 'comment-end-skip)
236 (concat "\\s-*\\(\\s>" (if comment-quote-nested "" "+")
237 "\\|" (regexp-quote (substring ce 0 1))
238 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
239 (regexp-quote (substring ce 1))
242 (defun comment-quote-re (str unp)
243 (concat (regexp-quote (substring str 0 1))
244 "\\\\" (if unp "+" "*")
245 (regexp-quote (substring str 1))))
247 (defun comment-quote-nested (cs ce unp)
248 "Quote or unquote nested comments.
249 If UNP is non-nil, unquote nested comment markers."
250 (setq cs (comment-string-strip cs t t))
251 (setq ce (comment-string-strip ce t t))
252 (when (and comment-quote-nested (> (length ce) 0))
253 (let ((re (concat (comment-quote-re ce unp)
254 "\\|" (comment-quote-re cs unp))))
255 (goto-char (point-min))
256 (while (re-search-forward re nil t)
257 (goto-char (match-beginning 0))
259 (if unp (delete-char 1) (insert "\\"))
260 (when (= (length ce) 1)
261 ;; If the comment-end is a single char, adding a \ after that
262 ;; "first" char won't deactivate it, so we turn such a CE
263 ;; into !CS. I.e. for pascal, we turn } into !{
265 (when (string= (match-string 0) ce)
266 (replace-match (concat "!" cs) t t))
267 (when (and (< (point-min) (match-beginning 0))
268 (string= (buffer-substring (1- (match-beginning 0))
272 (delete-char (- (match-end 0) (match-beginning 0)))
279 (defun comment-search-forward (limit &optional noerror)
280 "Find a comment start between point and LIMIT.
281 Moves point to inside the comment and returns the position of the
282 comment-starter. If no comment is found, moves point to LIMIT
283 and raises an error or returns nil of NOERROR is non-nil."
284 (if (not comment-use-syntax)
285 (if (re-search-forward comment-start-skip limit noerror)
286 (or (match-end 1) (match-beginning 0))
288 (unless noerror (error "No comment")))
290 ;; Assume (at first) that pt is outside of any string.
291 (s (parse-partial-sexp pt (or limit (point-max)) nil nil nil t)))
292 (when (and (nth 8 s) (nth 3 s))
293 ;; The search ended inside a string. Try to see if it
294 ;; works better when we assume that pt is inside a string.
295 (setq s (parse-partial-sexp
296 pt (or limit (point-max)) nil nil
297 (list nil nil nil (nth 3 s) nil nil nil nil)
299 (if (not (and (nth 8 s) (not (nth 3 s))))
300 (unless noerror (error "No comment"))
301 ;; We found the comment.
304 (bol (line-beginning-position))
306 (while (and (null end) (>= (point) bol))
307 (if (looking-at comment-start-skip)
308 (setq end (min (or limit (point-max)) (match-end 0)))
310 (goto-char (or end pos))
313 (defun comment-search-backward (&optional limit noerror)
314 "Find a comment start between LIMIT and point.
315 Moves point to inside the comment and returns the position of the
316 comment-starter. If no comment is found, moves point to LIMIT
317 and raises an error or returns nil of NOERROR is non-nil."
318 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
319 ;; stop there. This can be rather bad in general, but since
320 ;; comment-search-backward is only used to find the comment-column (in
321 ;; comment-set-column) and to find the comment-start string (via
322 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
323 (if (not (re-search-backward comment-start-skip limit t))
324 (unless noerror (error "No comment"))
326 (let* ((end (match-end 0))
327 (cs (comment-search-forward end t))
330 (progn (beginning-of-line)
331 (comment-search-backward limit noerror))
332 (while (progn (goto-char cs)
335 (setq cs (comment-search-forward end t))))
340 (defun comment-beginning ()
341 "Find the beginning of the enclosing comment.
342 Returns nil if not inside a comment, else moves point and returns
343 the same as `comment-search-forward'."
345 (cs (comment-search-backward nil t)))
349 (if (comment-forward 1) (> (point) pt) (eobp)))
354 (defun comment-forward (&optional n)
355 "Skip forward over N comments.
356 Just like `forward-comment' but only for positive N
357 and can use regexps instead of syntax."
359 (if (< n 0) (error "No comment-backward")
360 (if comment-use-syntax (forward-comment n)
362 (skip-syntax-forward " ")
364 (if (and (looking-at comment-start-skip)
365 (re-search-forward comment-end-skip nil 'move))
369 (defun comment-enter-backward ()
370 "Move from the end of a comment to the end of its content.
371 Point is assumed to be just at the end of a comment."
374 (progn (backward-char) (skip-syntax-backward " "))
378 (narrow-to-region (point) end)
379 (if (re-search-forward (concat comment-end-skip "\\'") nil t)
380 (goto-char (match-beginning 0))
381 ;; comment-end-skip not found probably because it was not set right.
382 ;; Since \\s> should catch the single-char case, we'll blindly
383 ;; assume we're at the end of a two-char comment-end.
384 (goto-char (point-max))
386 (skip-chars-backward (string (char-after)))
387 (skip-syntax-backward " "))))))
394 (defun comment-indent (&optional continue)
395 "Indent this line's comment to comment column, or insert an empty comment.
396 If CONTINUE is non-nil, use the `comment-continuation' markers if any."
398 (comment-normalize-vars)
399 (let* ((empty (save-excursion (beginning-of-line)
400 (looking-at "[ \t]*$")))
401 (starter (or (and continue comment-continue)
402 (and empty block-comment-start) comment-start))
403 (ender (or (and continue comment-continue "")
404 (and empty block-comment-end) comment-end)))
407 (error "No comment syntax defined"))
408 (t (let* ((eolpos (line-end-position))
411 (if (not (setq begpos (comment-search-forward eolpos t)))
412 (setq begpos (point))
413 (setq cpos (point-marker))
415 ;; Compute desired indent.
416 (if (= (current-column)
417 (setq indent (funcall (or (and (boundp 'comment-indent-hook)
419 comment-indent-function))))
421 ;; If that's different from current, change it.
422 (skip-chars-backward " \t")
423 (delete-region (point) begpos)
425 ;; An existing comment?
427 (progn (goto-char cpos) (set-marker cpos nil))
431 (insert ender))))))))
434 (defun comment-set-column (arg)
435 "Set the comment column based on point.
436 With no ARG, set the comment column to the current column.
437 With just minus as arg, kill any comment on this line.
438 With any other arg, set comment column to indentation of the previous comment
439 and then align or create a comment on this line at that column."
442 ((eq arg '-) (comment-kill nil))
446 (comment-search-backward)
448 (goto-char (comment-search-forward (line-end-position)))
449 (setq comment-column (current-column))
450 (message "Comment column set to %d" comment-column))
452 (t (setq comment-column (current-column))
453 (message "Comment column set to %d" comment-column))))
456 (defun comment-kill (arg)
457 "Kill the comment on this line, if any.
458 With prefix ARG, kill comments on that many lines starting with this one."
460 (dotimes (_ (prefix-numeric-value arg))
463 (let ((cs (comment-search-forward (line-end-position) t)))
466 (skip-syntax-backward " ")
469 (kill-region cs (if (bolp) (1- (point)) (point)))
470 (indent-according-to-mode))))
471 (if arg (forward-line 1))))
473 (defun comment-padright (str &optional n)
474 "Construct a string composed of STR plus `comment-padding'.
475 It also adds N copies of the last non-whitespace chars of STR.
476 If STR already contains padding, the corresponding amount is
477 ignored from `comment-padding'.
479 If N is `re', a regexp is returned instead, that would match
480 the string for any N."
482 (when (and (stringp str) (not (string= "" str)))
483 ;; Separate the actual string from any leading/trailing padding
484 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
485 (let ((s (match-string 1 str)) ;actual string
486 (lpad (substring str 0 (match-beginning 1))) ;left padding
487 (rpad (concat (substring str (match-end 1)) ;original right padding
488 (substring comment-padding ;additional right padding
489 (min (- (match-end 0) (match-end 1))
490 (length comment-padding)))))
491 ;; We can only duplicate C if the comment-end has multiple chars
492 ;; or if comments can be nested, else the comment-end `}' would
493 ;; be turned into `}}}' where only the first ends the comment
494 ;; and the rest becomes bogus junk.
495 (multi (not (and comment-quote-nested
496 ;; comment-end is a single char
497 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
498 (if (not (symbolp n))
499 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
500 ;; construct a regexp that would match anything from just S
501 ;; to any possible output of this function for any N.
502 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
503 lpad "") ;padding is not required
505 (when multi "+") ;the last char of S might be repeated
506 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
507 rpad "")))))) ;padding is not required
509 (defun comment-padleft (str &optional n)
510 "Construct a string composed of `comment-padding' plus STR.
511 It also adds N copies of the first non-whitespace chars of STR.
512 If STR already contains padding, the corresponding amount is
513 ignored from `comment-padding'.
515 If N is `re', a regexp is returned instead, that would match
516 the string for any N."
518 (when (and (stringp str) (not (string= "" str)))
519 ;; Only separate the left pad because we assume there is no right pad.
520 (string-match "\\`\\s-*" str)
521 (let ((s (substring str (match-end 0)))
522 (pad (concat (substring comment-padding
523 (min (- (match-end 0) (match-beginning 0))
524 (length comment-padding)))
525 (match-string 0 str)))
526 (c (aref str (match-end 0))) ;the first non-space char of STR
527 ;; We can only duplicate C if the comment-end has multiple chars
528 ;; or if comments can be nested, else the comment-end `}' would
529 ;; be turned into `}}}' where only the first ends the comment
530 ;; and the rest becomes bogus junk.
531 (multi (not (and comment-quote-nested
532 ;; comment-end is a single char
533 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
534 (if (not (symbolp n))
535 (concat pad (when multi (make-string n c)) s)
536 ;; Construct a regexp that would match anything from just S
537 ;; to any possible output of this function for any N.
538 ;; We match any number of leading spaces because this regexp will
539 ;; be used for uncommenting where we might want to remove
540 ;; uncomment markers with arbitrary leading space (because
541 ;; they were aligned).
543 (if multi (concat (regexp-quote (string c)) "*"))
544 (regexp-quote s))))))
547 (defun uncomment-region (beg end &optional arg)
548 "Uncomment each line in the BEG..END region.
549 The numeric prefix ARG can specify a number of chars to remove from the
551 (interactive "*r\nP")
552 (comment-normalize-vars)
553 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
556 (setq end (copy-marker end))
557 (let ((numarg (prefix-numeric-value arg))
559 (while (and (< (point) end)
560 (setq spt (comment-search-forward end t)))
562 ;; Find the end of the comment.
565 (unless (comment-forward)
566 (error "Can't find the comment end"))
569 (ccs comment-continue)
570 (srei (comment-padright ccs 're))
571 (sre (and srei (concat "^\\s-*?\\(" srei "\\)"))))
573 (narrow-to-region spt ept)
574 ;; Remove the comment-start.
576 (skip-syntax-backward " ")
577 ;; Check for special `=' used sometimes in comment-box.
578 (when (and (= (- (point) (point-min)) 1) (looking-at "=\\{7\\}"))
579 (skip-chars-forward "="))
580 ;; A box-comment starts with a looong comment-start marker.
581 (when (> (- (point) (point-min) (length comment-start)) 7)
583 (when (looking-at (regexp-quote comment-padding))
584 (goto-char (match-end 0)))
585 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
586 (goto-char (match-end 0)))
587 (if (null arg) (delete-region (point-min) (point))
588 (skip-syntax-backward " ")
589 (delete-char (- numarg)))
591 ;; Remove the end-comment (and leading padding and such).
592 (goto-char (point-max)) (comment-enter-backward)
593 ;; Check for special `=' used sometimes in comment-box.
594 (when (and (= (- (point-max) (point)) 1) (> (point) 7)
595 (save-excursion (backward-char 7)
596 (looking-at "=\\{7\\}")))
597 (skip-chars-backward "="))
598 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
599 (when (and (bolp) (not (bobp))) (backward-char))
600 (if (null arg) (delete-region (point) (point-max))
601 (skip-syntax-forward " ")
602 (delete-char numarg)))
604 ;; Unquote any nested end-comment.
605 (comment-quote-nested comment-start comment-end t)
607 ;; Eliminate continuation markers as well.
609 (let* ((cce (comment-string-reverse (or comment-continue
611 (erei (and box (comment-padleft cce 're)))
612 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
613 (goto-char (point-min))
615 (if (and ere (re-search-forward
616 ere (line-end-position) t))
617 (replace-match "" t t nil (if (match-end 2) 2 1))
620 (re-search-forward sre (line-end-position) t))
621 (replace-match "" t t nil (if (match-end 2) 2 1)))))
622 ;; Go the the end for the next comment.
623 (goto-char (point-max)))))
624 (set-marker end nil))))
626 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
627 "Make the leading and trailing extra lines.
628 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
631 ;; Try to match CS and CE's content so they align aesthetically.
633 (setq ce (comment-string-strip ce t t))
634 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
636 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
639 (let* ((width (- max-indent min-indent))
640 (s (concat cs "a=m" cce))
641 (e (concat ccs "a=m" ce))
642 (c (if (string-match ".*\\S-\\S-" cs)
643 (aref cs (1- (match-end 0))) ?=))
644 (_ (string-match "\\s-*a=m\\s-*" s))
646 (make-string (+ width (- (match-end 0)
647 (match-beginning 0) (length cs) 3)) c)))
648 (setq cs (replace-match fill t t s))
649 (string-match "\\s-*a=m\\s-*" e)
650 (setq ce (replace-match fill t t e))))
651 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
652 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
654 (def-edebug-spec comment-with-narrowing t)
655 (put 'comment-with-narrowing 'lisp-indent-function 2)
656 (defmacro comment-with-narrowing (beg end &rest body)
657 "Execute BODY with BEG..END narrowing.
658 Space is added (and then removed) at the beginning for the text's
659 indentation to be kept as it was before narrowing."
660 (let ((bindent (make-symbol "bindent")))
661 `(let ((,bindent (save-excursion (goto-char beg) (current-column))))
663 (narrow-to-region beg end)
664 (goto-char (point-min))
665 (insert (make-string ,bindent ? ))
668 ;; remove the bindent
670 (goto-char (point-min))
671 (when (looking-at " *")
672 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
674 (setq ,bindent (- ,bindent n))))
678 (while (and (> ,bindent 0) (re-search-forward " *" e t))
679 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
680 (goto-char (match-beginning 0))
682 (setq ,bindent (- ,bindent n)))))))))))
684 (defun comment-region-internal (beg end cs ce
685 &optional ccs cce block lines indent)
686 "Comment region BEG..END.
687 CS and CE are the comment start resp end string.
688 CCS and CCE are the comment continuation strings for the start resp end
689 of lines (default to CS and CE).
690 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
691 \(if CE is empty) and that those markers should be aligned.
692 LINES indicates that an extra lines will be used at the beginning and end
693 of the region for CE and CS.
694 INDENT indicates to put CS and CCS at the current indentation of the region
695 rather than at left margin."
696 ;;(assert (< beg end))
698 ;; Sanitize CE and CCE.
699 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
700 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
701 ;; If CE is empty, multiline cannot be used.
702 (unless ce (setq ccs nil cce nil))
703 ;; Should we mark empty lines as well ?
704 (if (or ccs block lines) (setq no-empty nil))
705 ;; Make sure we have end-markers for BLOCK mode.
706 (when block (unless ce (setq ce (comment-string-reverse cs))))
707 ;; If BLOCK is not requested, we don't need CCE.
708 (unless block (setq cce nil))
709 ;; Continuation defaults to the same as CS and CE.
710 (unless ccs (setq ccs cs cce ce))
714 ;; If the end is not at the end of a line and the comment-end
715 ;; is implicit (i.e. a newline), explicitly insert a newline.
716 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
717 (comment-with-narrowing beg end
718 (let ((min-indent (point-max))
720 (goto-char (point-min))
721 ;; Quote any nested comment marker
722 (comment-quote-nested comment-start comment-end nil)
724 ;; Loop over all lines to find the needed indentations.
725 (goto-char (point-min))
728 (unless (looking-at "[ \t]*$")
729 (setq min-indent (min min-indent (current-indentation))))
731 (setq max-indent (max max-indent (current-column)))
732 (not (or (eobp) (progn (forward-line) nil)))))
734 ;; Inserting ccs can change max-indent by (1- tab-width).
736 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
737 (unless indent (setq min-indent 0))
739 ;; make the leading and trailing lines if requested
742 (comment-make-extra-lines
743 cs ce ccs cce min-indent max-indent block)))
745 (setq ce (cdr csce))))
747 (goto-char (point-min))
748 ;; Loop over all lines from BEG to END.
751 (unless (and no-empty (looking-at "[ \t]*$"))
752 (move-to-column min-indent t)
753 (insert cs) (setq cs ccs) ;switch to CCS after the first line
755 (if (eobp) (setq cce ce))
757 (when block (move-to-column max-indent t))
760 (not (or (eobp) (progn (forward-line) nil))))))))))
763 (defun comment-region (beg end &optional arg)
764 "Comment or uncomment each line in the region.
765 With just \\[universal-prefix] prefix arg, uncomment each line in region BEG..END.
766 Numeric prefix arg ARG means use ARG comment characters.
767 If ARG is negative, delete that many comment characters instead.
768 By default, comments start at the left margin, are terminated on each line,
769 even for syntax in which newline does not end the comment and blank lines
770 do not get comments. This can be changed with `comment-style'.
772 The strings used as comment starts are built from
773 `comment-start' without trailing spaces and `comment-padding'."
774 (interactive "*r\nP")
775 (comment-normalize-vars)
776 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
777 (let* ((numarg (prefix-numeric-value arg))
779 (style (cdr (assoc comment-style comment-styles)))
780 (lines (nth 2 style))
781 (block (nth 1 style))
782 (multi (nth 0 style)))
784 ;; we use `chars' instead of `syntax' because `\n' might be
785 ;; of end-comment syntax rather than of whitespace syntax.
786 ;; sanitize BEG and END
787 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
788 (setq beg (max beg (point)))
789 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
790 (setq end (min end (point)))
791 (if (>= beg end) (error "Nothing to comment"))
797 (progn (goto-char beg) (beginning-of-line)
798 (skip-syntax-forward " ")
800 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
802 (or (not (string= "" comment-end)) block)
803 (progn (goto-char beg) (search-forward "\n" end t)))))
805 ;; don't add end-markers just because the user asked for `block'
806 (unless (or lines (string= "" comment-end)) (setq block nil))
809 ((consp arg) (uncomment-region beg end))
810 ((< numarg 0) (uncomment-region beg end (- numarg)))
812 (setq numarg (if (and (null arg) (= (length comment-start) 1))
814 (comment-region-internal
816 (let ((s (comment-padright comment-start numarg)))
817 (if (string-match comment-start-skip s) s
818 (comment-padright comment-start)))
819 (let ((s (comment-padleft comment-end numarg)))
820 (and s (if (string-match comment-end-skip s) s
821 (comment-padright comment-end))))
822 (if multi (comment-padright comment-continue numarg))
823 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
828 (defun comment-box (beg end &optional arg)
829 "Comment out the BEG..END region, putting it inside a box.
830 The numeric prefix ARG specifies how many characters to add to begin- and
831 end- comment markers additionally to what `comment-add' already specifies."
832 (interactive "*r\np")
833 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
835 (comment-region beg end (+ comment-add arg))))
838 (defun comment-dwim (arg)
839 "Call the comment command you want (Do What I Mean).
840 If the region is active and `transient-mark-mode' is on, call
841 `comment-region' (unless it only consists in comments, in which
842 case it calls `uncomment-region').
843 Else, if the current line is empty, insert a comment and indent it.
844 Else if a prefix ARG is specified, call `comment-kill'.
845 Else, call `comment-indent'."
847 (comment-normalize-vars)
848 (if (and mark-active transient-mark-mode)
849 (let ((beg (min (point) (mark)))
850 (end (max (point) (mark))))
851 (if (save-excursion ;; check for already commented region
853 (comment-forward (point-max))
855 (uncomment-region beg end arg)
856 (comment-region beg end arg)))
857 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
858 ;; FIXME: If there's no comment to kill on this line and ARG is
859 ;; specified, calling comment-kill is not very clever.
860 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
861 (let ((add (if arg (prefix-numeric-value arg)
862 (if (= (length comment-start) 1) comment-add 0))))
863 (insert (comment-padright comment-start add))
865 (unless (string= "" comment-end)
866 (insert (comment-padleft comment-end add)))
867 (indent-according-to-mode))))))
869 (defcustom comment-auto-fill-only-comments nil
870 "Non-nil means to only auto-fill inside comments.
871 This has no effect in modes that do not define a comment syntax."
876 (defun comment-indent-new-line (&optional soft)
877 "Break line at point and indent, continuing comment if within one.
878 This indents the body of the continued comment
879 under the previous comment line.
881 This command is intended for styles where you write a comment per line,
882 starting a new comment (and terminating it if necessary) on each line.
883 If you want to continue one comment across several lines, use \\[newline-and-indent].
885 If a fill column is specified, it overrides the use of the comment column
886 or comment indentation.
888 The inserted newline is marked hard if variable `use-hard-newlines' is true,
889 unless optional argument SOFT is non-nil."
891 (comment-normalize-vars t)
893 ;; If we are not inside a comment and we only auto-fill comments,
894 ;; don't do anything (unless no comment syntax is defined).
895 (unless (and comment-start
896 comment-auto-fill-only-comments
898 (prog1 (setq compos (comment-beginning))
899 (setq comin (point))))))
901 ;; Now we know we should auto-fill.
902 (delete-region (progn (skip-chars-backward " \t") (point))
903 (progn (skip-chars-forward " \t") (point)))
904 (if soft (insert-and-inherit ?\n) (newline 1))
907 (indent-to-left-margin)
908 (insert-and-inherit fill-prefix))
910 ;; If necessary check whether we're inside a comment.
911 (unless (or comment-multi-line compos (null comment-start))
914 (setq compos (comment-beginning))
915 (setq comin (point))))
917 ;; If we're not inside a comment, just try to indent.
918 (if (not compos) (indent-according-to-mode)
919 (let* ((comment-column
920 ;; The continuation indentation should be somewhere between
921 ;; the current line's indentation (plus 2 for good measure)
922 ;; and the current comment's indentation, with a preference
923 ;; for comment-column.
926 (min (current-column) (max comment-column
927 (+ 2 (current-indentation))))))
928 (comstart (buffer-substring compos comin))
930 (string-match (regexp-quote (comment-string-strip
934 (if normalp comment-end
935 ;; The comment starter is not the normal comment-start
936 ;; so we can't just use comment-end.
939 (if (not (comment-forward)) comment-end
940 (comment-string-strip
942 (save-excursion (comment-enter-backward) (point))
945 (comment-start comstart)
946 ;; Force comment-continue to be recreated from comment-start.
947 (comment-continue nil))
948 (insert-and-inherit ?\n)
950 (comment-indent (cadr (assoc comment-style comment-styles)))
954 (let ((comend (buffer-substring pt (point))))
955 ;; The 1+ is to make sure we delete the \n inserted above.
956 (delete-region pt (1+ (point)))
960 (forward-char))))))))))
962 (provide 'newcomment)
965 ;; $Log: newcomment.el,v $
966 ;; Revision 1.14 2000/05/23 20:06:10 monnier
967 ;; (comment-make-extra-lines): Don't use `assert'.
969 ;; Revision 1.13 2000/05/22 04:23:37 monnier
970 ;; (comment-region-internal): Go back to BEG after quoting
971 ;; the nested comment markers.
973 ;; Revision 1.12 2000/05/21 00:27:31 monnier
974 ;; (comment-styles): New `box-multi'.
975 ;; (comment-normalize-vars): Better default for comment-continue to
976 ;; avoid whitespace-only continuations.
977 ;; (comment-search-forward): Always move even in the no-syntax case.
978 ;; (comment-padright): Only obey N if it's only obeyed for padleft.
979 ;; (comment-make-extra-lines): Better handling of empty continuations.
980 ;; Use `=' for the filler if comment-start has only one character.
981 ;; (uncomment-region): Try handling the special `=' filler.
982 ;; (comment-region): Allow LINES even if MULTI is nil.
983 ;; (comment-box): Choose box style based on comment-style.
985 ;; Revision 1.11 2000/05/19 15:37:41 monnier
986 ;; Fix license text and author.
987 ;; Move aliases (indent-for-comment, set-comment-column, kill-comment
988 ;; and indent-new-comment-line) to the beginning of the file.
989 ;; Get rid of the last few CLisms.
990 ;; (comment-forward): Avoid decf.
991 ;; (comment-make-extra-lines): Comment-out asserts.
992 ;; (comment-with-narrowing): Properly create uninterned symbol.
993 ;; (comment-region-internal): Comment-out asserts. Avoid incf and decf.
994 ;; (comment-indent-new-line): Fix bug where compt could be set but
995 ;; not comstart. Set comment-column more carefully.
997 ;; Revision 1.10 2000/05/17 19:32:32 monnier
998 ;; (comment-beginning): Handle unclosed comment.
999 ;; (comment-auto-fill-only-comments): New var.
1000 ;; (comment-indent-new-line): Obey comment-auto-fill-only-comments.
1001 ;; Align with comment-column rather than previous comment if previous
1002 ;; comment's indentation is greater than comment-column.
1004 ;; Revision 1.9 2000/05/16 22:02:37 monnier
1005 ;; (comment-string-strip): Strip terminating newlines.
1006 ;; (comment-search-forward): Make LIMIT compulsory.
1007 ;; If an unterminated string (rather than a comment) is found, try again,
1008 ;; assuming that the region starts inside a string.
1009 ;; (comment-beginning): Make sure we don't move if we find a comment but
1010 ;; it's not the one we're in.
1011 ;; (comment-enter-backward): Handle the case where comment-end-skip fails.
1012 ;; (comment-indent): Normalize variables and use line-end-position.
1013 ;; (comment-kill): Use line-end-position.
1014 ;; (comment-spill): Remove.
1015 ;; (comment-indent-new-line): Renamed from indent-new-comment-line.
1016 ;; Cleaned up old commented-out code.
1017 ;; Reset comment-continue and comment-end before calling comment-indent.
1019 ;; Revision 1.8 2000/05/14 00:56:10 monnier
1020 ;; (comment-start, comment-start-skip, comment-end): Made `defvar'.
1021 ;; (comment-style): Extract the choice out of comment-styles.
1022 ;; (comment-continue): Just a simple string now.
1023 ;; (comment-normalize-vars): Update for the new comment-continue.
1024 ;; (until, comment-end-quote-re): Removed.
1025 ;; (comment-quote-re, comment-quote-nested): New functions for quoting.
1026 ;; These quote both the end and the start and also work for single-chars.
1027 ;; (comment-padright): Added lots of comments.
1028 ;; (comment-padleft): Added more comments. Check comment-end rather than
1029 ;; STR to determine whether N can be applied or not.
1030 ;; (uncomment-region): Rename BLOCK to BOX.
1031 ;; Use the new comment-quote-nested.
1032 ;; Use only one marker and properly set it back to nil.
1033 ;; Be more picky when eliminating continuation markers.
1035 ;; Revision 1.7 2000/05/13 19:41:08 monnier
1036 ;; (comment-use-syntax): Change `maybe' to `undecided'.
1037 ;; (comment-quote-nested): New. Replaces comment-nested.
1038 ;; (comment-add): Turn into a mere defvar or a integer.
1039 ;; (comment-style): Change default to `plain'.
1040 ;; (comment-styles): Rename `plain' to `indent' and create a new plainer `plain'
1041 ;; (comment-string-reverse): Use nreverse.
1042 ;; (comment-normalize-vars): Change `maybe' to `undecided', add comments.
1043 ;; Don't infer the setting of comment-nested anymore (the default for
1044 ;; comment-quote-nested is safe). Use comment-quote-nested.
1045 ;; (comment-end-quote-re): Use comment-quote-nested.
1046 ;; (comment-search-forward): Obey LIMIT.
1047 ;; (comment-indent): Don't skip forward further past comment-search-forward.
1048 ;; (comment-padleft): Use comment-quote-nested.
1049 ;; (comment-make-extra-lines): Use `cons' rather than `values'.
1050 ;; (comment-region-internal): New arg INDENT. Use line-end-position.
1051 ;; Avoid multiple-value-setq.
1052 ;; (comment-region): Follow the new comment-add semantics.
1053 ;; Don't do box comments any more.
1054 ;; (comment-box): New function.
1055 ;; (comment-dwim): Only do the region stuff is transient-mark-active.
1057 ;; Revision 1.6 1999/12/08 00:19:51 monnier
1058 ;; various fixes and gratuitous movements.
1060 ;; Revision 1.5 1999/11/30 16:20:55 monnier
1061 ;; (comment-style(s)): Replaces comment-extra-lines (and comment-multi-line).
1062 ;; (comment-use-syntax): Whether to use the syntax-table or just the regexps.
1063 ;; (comment-end-skip): To find the end of the text.
1066 ;; Revision 1.4 1999/11/29 01:31:47 monnier
1067 ;; (comment-find): New function.
1068 ;; (indent-for-comment, set-comment-column, kill-comment): use it.
1070 ;; Revision 1.3 1999/11/29 00:49:18 monnier
1071 ;; (kill-comment): Fixed by rewriting it with syntax-tables rather than regexps
1072 ;; (comment-normalize-vars): Set default (cdr comment-continue)
1073 ;; (comment-end-quote-re): new function taken out of `comment-region-internal'
1074 ;; (uncomment-region): Rewritten using syntax-tables. Also unquotes
1075 ;; nested comment-ends and eliminates continuation markers.
1076 ;; (comment-region-internal): Don't create a default for cce.
1077 ;; Use `comment-end-quote-re'.
1079 ;; Revision 1.2 1999/11/28 21:33:55 monnier
1080 ;; (comment-make-extra-lines): Moved out of comment-region-internal.
1081 ;; (comment-with-narrowing): New macro. Provides a way to preserve
1082 ;; indentation inside narrowing.
1083 ;; (comment-region-internal): Add "\n" to close the comment if necessary.
1084 ;; Correctly handle commenting-out when BEG is not bolp.
1086 ;; Revision 1.1 1999/11/28 18:51:06 monnier
1087 ;; First "working" version:
1088 ;; - uncomment-region doesn't work for some unknown reason
1089 ;; - comment-multi-line allows the use of multi line comments
1090 ;; - comment-extra-lines allows yet another style choice
1091 ;; - comment-add allows to default to `;;'
1092 ;; - comment-region on a comment calls uncomment-region
1093 ;; - C-u C-u comment-region aligns comment end markers
1094 ;; - C-u C-u C-u comment-region puts the comment inside a rectangle
1095 ;; - comment-region will try to quote comment-end markers inside the region
1096 ;; - comment-start markers are placed at the indentation level
1099 ;;; newcomment.el ends here