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