*** empty log message ***
[bpt/emacs.git] / lisp / newcomment.el
1 ;;; newcomment.el --- (un)comment regions of buffers
2
3 ;; Copyright (C) 1999-2000 Free Software Foundation Inc.
4
5 ;; Author: code extracted from Emacs-20's simple.el
6 ;; Maintainer: Stefan Monnier <monnier@cs.yale.edu>
7 ;; Keywords: comment uncomment
8 ;; Version: $Name: $
9 ;; Revision: $Id: newcomment.el,v 1.16 2000/06/04 22:02:11 monnier Exp $
10
11 ;; This file is part of GNU Emacs.
12
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)
16 ;; any later version.
17
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.
22
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.
27
28 ;;; Commentary:
29
30 ;; A replacement for simple.el's comment-related functions.
31
32 ;;; Bugs:
33
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.
44
45 ;;; Todo:
46
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.
57
58 ;;; Code:
59
60 ;;;###autoload
61 (defalias 'indent-for-comment 'comment-indent)
62 ;;;###autoload
63 (defalias 'set-comment-column 'comment-set-column)
64 ;;;###autoload
65 (defalias 'kill-comment 'comment-kill)
66 ;;;###autoload
67 (defalias 'indent-new-comment-line 'comment-indent-new-line)
68
69 ;;;###autoload
70 (defgroup comment nil
71 "Indenting and filling of comments."
72 :prefix "comment-"
73 :version "21.1"
74 :group 'fill)
75
76 (defvar comment-use-syntax 'undecided
77 "Non-nil if syntax-tables can be used instead of regexps.
78 Can also be `undecided' which means that a somewhat expensive test will
79 be used to try to determine whether syntax-tables should be trusted
80 to understand comments or not in the given buffer.
81 Major modes should set this variable.")
82
83 ;;;###autoload
84 (defcustom comment-column 32
85 "*Column to indent right-margin comments to.
86 Setting this variable automatically makes it local to the current buffer.
87 Each mode establishes a different default value for this variable; you
88 can set the value for a particular mode using that mode's hook."
89 :type 'integer
90 :group 'comment)
91 (make-variable-buffer-local 'comment-column)
92
93 ;;;###autoload
94 (defvar comment-start nil
95 "*String to insert to start a new comment, or nil if no comment syntax.")
96
97 ;;;###autoload
98 (defvar comment-start-skip nil
99 "*Regexp to match the start of a comment plus everything up to its body.
100 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
101 at the place matched by the close of the first pair.")
102
103 ;;;###autoload
104 (defvar comment-end-skip nil
105 "Regexp to match the end of a comment plus everything up to its body.")
106
107 ;;;###autoload
108 (defvar comment-end ""
109 "*String to insert to end a new comment.
110 Should be an empty string if comments are terminated by end-of-line.")
111
112 ;;;###autoload
113 (defvar comment-indent-function
114 (lambda () comment-column)
115 "Function to compute desired indentation for a comment.
116 This function is called with no args with point at the beginning of
117 the comment's starting delimiter.")
118
119 (defvar block-comment-start nil)
120 (defvar block-comment-end nil)
121
122 (defvar comment-quote-nested t
123 "Non-nil if nested comments should be quoted.
124 This should be locally set by each major mode if needed.")
125
126 (defvar comment-continue nil
127 "Continuation string to insert for multiline comments.
128 This string will be added at the beginning of each line except the very
129 first one when commenting a region with a commenting style that allows
130 comments to span several lines.
131 It should generally have the same length as `comment-start' in order to
132 preserve indentation.
133 If it is nil a value will be automatically derived from `comment-start'
134 by replacing its first character with a space.")
135
136 (defvar comment-add 0
137 "How many more comment chars should be inserted by `comment-region'.
138 This determines the default value of the numeric argument of `comment-region'.
139 This should generally stay 0, except for a few modes like Lisp where
140 it can be convenient to set it to 1 so that regions are commented with
141 two semi-colons.")
142
143 (defconst comment-styles
144 '((plain . (nil nil nil nil))
145 (indent . (nil nil nil t))
146 (aligned . (nil t nil t))
147 (multi-line . (t nil nil t))
148 (extra-line . (t nil t t))
149 (box . (nil t t t))
150 (box-multi . (t t t t)))
151 "Possible comment styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
152 STYLE should be a mnemonic symbol.
153 MULTI specifies that comments are allowed to span multiple lines.
154 ALIGN specifies that the `comment-end' markers should be aligned.
155 EXTRA specifies that an extra line should be used before and after the
156 region to comment (to put the `comment-end' and `comment-start').
157 INDENT specifies that the `comment-start' markers should not be put at the
158 left margin but at the current indentation of the region to comment.")
159
160 ;;;###autoload
161 (defcustom comment-style 'plain
162 "*Style to be used for `comment-region'.
163 See `comment-styles' for a list of available styles."
164 :group 'comment
165 :type (if (boundp 'comment-styles)
166 `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles))
167 'symbol))
168
169 ;;;###autoload
170 (defcustom comment-padding " "
171 "Padding string that `comment-region' puts between comment chars and text.
172 Can also be an integer which will be automatically turned into a string
173 of the corresponding number of spaces.
174
175 Extra spacing between the comment characters and the comment text
176 makes the comment easier to read. Default is 1. nil means 0.")
177
178 ;;;###autoload
179 (defcustom comment-multi-line nil
180 "*Non-nil means \\[comment-indent-new-line] continues comments, with no new terminator or starter.
181 This is obsolete because you might as well use \\[newline-and-indent]."
182 :type 'boolean
183 :group 'comment)
184
185 ;;;;
186 ;;;; Helpers
187 ;;;;
188
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?")
193 "\\'") str)
194 (match-string 1 str))
195
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))
199
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))
206 (cs comment-start)
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.
210 (with-temp-buffer
211 (set-syntax-table st)
212 (insert cs " hello " ce)
213 (goto-char (point-min))
214 (and (forward-comment 1) (eobp))))))
215 ;; comment-padding
216 (when (integerp comment-padding)
217 (setq comment-padding (make-string comment-padding ? )))
218 ;; comment markers
219 ;;(setq comment-start (comment-string-strip comment-start t nil))
220 ;;(setq comment-end (comment-string-strip comment-end nil t))
221 ;; comment-continue
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))
231 "+\\)\\s-*")))
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))
240 "\\)"))))))
241
242 (defun comment-quote-re (str unp)
243 (concat (regexp-quote (substring str 0 1))
244 "\\\\" (if unp "+" "*")
245 (regexp-quote (substring str 1))))
246
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))
258 (forward-char 1)
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 !{
264 (if (not unp)
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))
269 (1- (match-end 0)))
270 (concat "!" cs)))
271 (backward-char 2)
272 (delete-char (- (match-end 0) (match-beginning 0)))
273 (insert ce))))))))
274
275 ;;;;
276 ;;;; Navigation
277 ;;;;
278
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))
287 (goto-char limit)
288 (unless noerror (error "No comment")))
289 (let* ((pt (point))
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)
298 t)))
299 (if (not (and (nth 8 s) (not (nth 3 s))))
300 (unless noerror (error "No comment"))
301 ;; We found the comment.
302 (let ((pos (point))
303 (start (nth 8 s))
304 (bol (line-beginning-position))
305 (end nil))
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)))
309 (backward-char)))
310 (goto-char (or end pos))
311 start)))))
312
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"))
325 (beginning-of-line)
326 (let* ((end (match-end 0))
327 (cs (comment-search-forward end t))
328 (pt (point)))
329 (if (not cs)
330 (progn (beginning-of-line)
331 (comment-search-backward limit noerror))
332 (while (progn (goto-char cs)
333 (comment-forward)
334 (and (< (point) end)
335 (setq cs (comment-search-forward end t))))
336 (setq pt (point)))
337 (goto-char pt)
338 cs))))
339
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'."
344 (let ((pt (point))
345 (cs (comment-search-backward nil t)))
346 (when cs
347 (if (save-excursion
348 (goto-char cs)
349 (if (comment-forward 1) (> (point) pt) (eobp)))
350 cs
351 (goto-char pt)
352 nil))))
353
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."
358 (setq n (or n 1))
359 (if (< n 0) (error "No comment-backward")
360 (if comment-use-syntax (forward-comment n)
361 (while (> n 0)
362 (skip-syntax-forward " ")
363 (setq n
364 (if (and (looking-at comment-start-skip)
365 (re-search-forward comment-end-skip nil 'move))
366 (1- n) -1)))
367 (= n 0))))
368
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."
372 (if (bolp)
373 ;; comment-end = ""
374 (progn (backward-char) (skip-syntax-backward " "))
375 (let ((end (point)))
376 (beginning-of-line)
377 (save-restriction
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))
385 (backward-char 2)
386 (skip-chars-backward (string (char-after)))
387 (skip-syntax-backward " "))))))
388
389 ;;;;
390 ;;;; Commands
391 ;;;;
392
393 ;;;###autoload
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."
397 (interactive "*")
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)))
405 (cond
406 ((null starter)
407 (error "No comment syntax defined"))
408 (t (let* ((eolpos (line-end-position))
409 cpos indent begpos)
410 (beginning-of-line)
411 (if (not (setq begpos (comment-search-forward eolpos t)))
412 (setq begpos (point))
413 (setq cpos (point-marker))
414 (goto-char begpos))
415 ;; Compute desired indent.
416 (if (= (current-column)
417 (setq indent (funcall comment-indent-function)))
418 (goto-char begpos)
419 ;; If that's different from current, change it.
420 (skip-chars-backward " \t")
421 (delete-region (point) begpos)
422 (indent-to indent))
423 ;; An existing comment?
424 (if cpos
425 (progn (goto-char cpos) (set-marker cpos nil))
426 ;; No, insert one.
427 (insert starter)
428 (save-excursion
429 (insert ender))))))))
430
431 ;;;###autoload
432 (defun comment-set-column (arg)
433 "Set the comment column based on point.
434 With no ARG, set the comment column to the current column.
435 With just minus as arg, kill any comment on this line.
436 With any other arg, set comment column to indentation of the previous comment
437 and then align or create a comment on this line at that column."
438 (interactive "P")
439 (cond
440 ((eq arg '-) (comment-kill nil))
441 (arg
442 (save-excursion
443 (beginning-of-line)
444 (comment-search-backward)
445 (beginning-of-line)
446 (goto-char (comment-search-forward (line-end-position)))
447 (setq comment-column (current-column))
448 (message "Comment column set to %d" comment-column))
449 (comment-indent))
450 (t (setq comment-column (current-column))
451 (message "Comment column set to %d" comment-column))))
452
453 ;;;###autoload
454 (defun comment-kill (arg)
455 "Kill the comment on this line, if any.
456 With prefix ARG, kill comments on that many lines starting with this one."
457 (interactive "P")
458 (dotimes (_ (prefix-numeric-value arg))
459 (save-excursion
460 (beginning-of-line)
461 (let ((cs (comment-search-forward (line-end-position) t)))
462 (when cs
463 (goto-char cs)
464 (skip-syntax-backward " ")
465 (setq cs (point))
466 (comment-forward)
467 (kill-region cs (if (bolp) (1- (point)) (point)))
468 (indent-according-to-mode))))
469 (if arg (forward-line 1))))
470
471 (defun comment-padright (str &optional n)
472 "Construct a string composed of STR plus `comment-padding'.
473 It also adds N copies of the last non-whitespace chars of STR.
474 If STR already contains padding, the corresponding amount is
475 ignored from `comment-padding'.
476 N defaults to 0.
477 If N is `re', a regexp is returned instead, that would match
478 the string for any N."
479 (setq n (or n 0))
480 (when (and (stringp str) (not (string= "" str)))
481 ;; Separate the actual string from any leading/trailing padding
482 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
483 (let ((s (match-string 1 str)) ;actual string
484 (lpad (substring str 0 (match-beginning 1))) ;left padding
485 (rpad (concat (substring str (match-end 1)) ;original right padding
486 (substring comment-padding ;additional right padding
487 (min (- (match-end 0) (match-end 1))
488 (length comment-padding)))))
489 ;; We can only duplicate C if the comment-end has multiple chars
490 ;; or if comments can be nested, else the comment-end `}' would
491 ;; be turned into `}}}' where only the first ends the comment
492 ;; and the rest becomes bogus junk.
493 (multi (not (and comment-quote-nested
494 ;; comment-end is a single char
495 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
496 (if (not (symbolp n))
497 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
498 ;; construct a regexp that would match anything from just S
499 ;; to any possible output of this function for any N.
500 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
501 lpad "") ;padding is not required
502 (regexp-quote s)
503 (when multi "+") ;the last char of S might be repeated
504 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
505 rpad "")))))) ;padding is not required
506
507 (defun comment-padleft (str &optional n)
508 "Construct a string composed of `comment-padding' plus STR.
509 It also adds N copies of the first non-whitespace chars of STR.
510 If STR already contains padding, the corresponding amount is
511 ignored from `comment-padding'.
512 N defaults to 0.
513 If N is `re', a regexp is returned instead, that would match
514 the string for any N."
515 (setq n (or n 0))
516 (when (and (stringp str) (not (string= "" str)))
517 ;; Only separate the left pad because we assume there is no right pad.
518 (string-match "\\`\\s-*" str)
519 (let ((s (substring str (match-end 0)))
520 (pad (concat (substring comment-padding
521 (min (- (match-end 0) (match-beginning 0))
522 (length comment-padding)))
523 (match-string 0 str)))
524 (c (aref str (match-end 0))) ;the first non-space char of STR
525 ;; We can only duplicate C if the comment-end has multiple chars
526 ;; or if comments can be nested, else the comment-end `}' would
527 ;; be turned into `}}}' where only the first ends the comment
528 ;; and the rest becomes bogus junk.
529 (multi (not (and comment-quote-nested
530 ;; comment-end is a single char
531 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
532 (if (not (symbolp n))
533 (concat pad (when multi (make-string n c)) s)
534 ;; Construct a regexp that would match anything from just S
535 ;; to any possible output of this function for any N.
536 ;; We match any number of leading spaces because this regexp will
537 ;; be used for uncommenting where we might want to remove
538 ;; uncomment markers with arbitrary leading space (because
539 ;; they were aligned).
540 (concat "\\s-*"
541 (if multi (concat (regexp-quote (string c)) "*"))
542 (regexp-quote s))))))
543
544 ;;;###autoload
545 (defun uncomment-region (beg end &optional arg)
546 "Uncomment each line in the BEG..END region.
547 The numeric prefix ARG can specify a number of chars to remove from the
548 comment markers."
549 (interactive "*r\nP")
550 (comment-normalize-vars)
551 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
552 (save-excursion
553 (goto-char beg)
554 (setq end (copy-marker end))
555 (let ((numarg (prefix-numeric-value arg))
556 spt)
557 (while (and (< (point) end)
558 (setq spt (comment-search-forward end t)))
559 (let* ((ipt (point))
560 ;; Find the end of the comment.
561 (ept (progn
562 (goto-char spt)
563 (unless (comment-forward)
564 (error "Can't find the comment end"))
565 (point)))
566 (box nil)
567 (ccs comment-continue)
568 (srei (comment-padright ccs 're))
569 (sre (and srei (concat "^\\s-*?\\(" srei "\\)"))))
570 (save-restriction
571 (narrow-to-region spt ept)
572 ;; Remove the comment-start.
573 (goto-char ipt)
574 (skip-syntax-backward " ")
575 ;; Check for special `=' used sometimes in comment-box.
576 (when (and (= (- (point) (point-min)) 1) (looking-at "=\\{7\\}"))
577 (skip-chars-forward "="))
578 ;; A box-comment starts with a looong comment-start marker.
579 (when (> (- (point) (point-min) (length comment-start)) 7)
580 (setq box t))
581 (when (looking-at (regexp-quote comment-padding))
582 (goto-char (match-end 0)))
583 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
584 (goto-char (match-end 0)))
585 (if (null arg) (delete-region (point-min) (point))
586 (skip-syntax-backward " ")
587 (delete-char (- numarg)))
588
589 ;; Remove the end-comment (and leading padding and such).
590 (goto-char (point-max)) (comment-enter-backward)
591 ;; Check for special `=' used sometimes in comment-box.
592 (when (and (= (- (point-max) (point)) 1) (> (point) 7)
593 (save-excursion (backward-char 7)
594 (looking-at "=\\{7\\}")))
595 (skip-chars-backward "="))
596 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
597 (when (and (bolp) (not (bobp))) (backward-char))
598 (if (null arg) (delete-region (point) (point-max))
599 (skip-syntax-forward " ")
600 (delete-char numarg)))
601
602 ;; Unquote any nested end-comment.
603 (comment-quote-nested comment-start comment-end t)
604
605 ;; Eliminate continuation markers as well.
606 (when sre
607 (let* ((cce (comment-string-reverse (or comment-continue
608 comment-start)))
609 (erei (and box (comment-padleft cce 're)))
610 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
611 (goto-char (point-min))
612 (while (progn
613 (if (and ere (re-search-forward
614 ere (line-end-position) t))
615 (replace-match "" t t nil (if (match-end 2) 2 1))
616 (setq ere nil))
617 (forward-line 1)
618 (re-search-forward sre (line-end-position) t))
619 (replace-match "" t t nil (if (match-end 2) 2 1)))))
620 ;; Go the the end for the next comment.
621 (goto-char (point-max)))))
622 (set-marker end nil))))
623
624 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
625 "Make the leading and trailing extra lines.
626 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
627 (let ((eindent 0))
628 (if (not block)
629 ;; Try to match CS and CE's content so they align aesthetically.
630 (progn
631 (setq ce (comment-string-strip ce t t))
632 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
633 (setq eindent
634 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
635 0))))
636 ;; box comment
637 (let* ((width (- max-indent min-indent))
638 (s (concat cs "a=m" cce))
639 (e (concat ccs "a=m" ce))
640 (c (if (string-match ".*\\S-\\S-" cs)
641 (aref cs (1- (match-end 0))) ?=))
642 (_ (string-match "\\s-*a=m\\s-*" s))
643 (fill
644 (make-string (+ width (- (match-end 0)
645 (match-beginning 0) (length cs) 3)) c)))
646 (setq cs (replace-match fill t t s))
647 (string-match "\\s-*a=m\\s-*" e)
648 (setq ce (replace-match fill t t e))))
649 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
650 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
651
652 (def-edebug-spec comment-with-narrowing t)
653 (put 'comment-with-narrowing 'lisp-indent-function 2)
654 (defmacro comment-with-narrowing (beg end &rest body)
655 "Execute BODY with BEG..END narrowing.
656 Space is added (and then removed) at the beginning for the text's
657 indentation to be kept as it was before narrowing."
658 (let ((bindent (make-symbol "bindent")))
659 `(let ((,bindent (save-excursion (goto-char beg) (current-column))))
660 (save-restriction
661 (narrow-to-region beg end)
662 (goto-char (point-min))
663 (insert (make-string ,bindent ? ))
664 (prog1
665 (progn ,@body)
666 ;; remove the bindent
667 (save-excursion
668 (goto-char (point-min))
669 (when (looking-at " *")
670 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
671 (delete-char n)
672 (setq ,bindent (- ,bindent n))))
673 (end-of-line)
674 (let ((e (point)))
675 (beginning-of-line)
676 (while (and (> ,bindent 0) (re-search-forward " *" e t))
677 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
678 (goto-char (match-beginning 0))
679 (delete-char n)
680 (setq ,bindent (- ,bindent n)))))))))))
681
682 (defun comment-region-internal (beg end cs ce
683 &optional ccs cce block lines indent)
684 "Comment region BEG..END.
685 CS and CE are the comment start resp end string.
686 CCS and CCE are the comment continuation strings for the start resp end
687 of lines (default to CS and CE).
688 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
689 \(if CE is empty) and that those markers should be aligned.
690 LINES indicates that an extra lines will be used at the beginning and end
691 of the region for CE and CS.
692 INDENT indicates to put CS and CCS at the current indentation of the region
693 rather than at left margin."
694 ;;(assert (< beg end))
695 (let ((no-empty t))
696 ;; Sanitize CE and CCE.
697 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
698 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
699 ;; If CE is empty, multiline cannot be used.
700 (unless ce (setq ccs nil cce nil))
701 ;; Should we mark empty lines as well ?
702 (if (or ccs block lines) (setq no-empty nil))
703 ;; Make sure we have end-markers for BLOCK mode.
704 (when block (unless ce (setq ce (comment-string-reverse cs))))
705 ;; If BLOCK is not requested, we don't need CCE.
706 (unless block (setq cce nil))
707 ;; Continuation defaults to the same as CS and CE.
708 (unless ccs (setq ccs cs cce ce))
709
710 (save-excursion
711 (goto-char end)
712 ;; If the end is not at the end of a line and the comment-end
713 ;; is implicit (i.e. a newline), explicitly insert a newline.
714 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
715 (comment-with-narrowing beg end
716 (let ((min-indent (point-max))
717 (max-indent 0))
718 (goto-char (point-min))
719 ;; Quote any nested comment marker
720 (comment-quote-nested comment-start comment-end nil)
721
722 ;; Loop over all lines to find the needed indentations.
723 (goto-char (point-min))
724 (while
725 (progn
726 (unless (looking-at "[ \t]*$")
727 (setq min-indent (min min-indent (current-indentation))))
728 (end-of-line)
729 (setq max-indent (max max-indent (current-column)))
730 (not (or (eobp) (progn (forward-line) nil)))))
731
732 ;; Inserting ccs can change max-indent by (1- tab-width).
733 (setq max-indent
734 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
735 (unless indent (setq min-indent 0))
736
737 ;; make the leading and trailing lines if requested
738 (when lines
739 (let ((csce
740 (comment-make-extra-lines
741 cs ce ccs cce min-indent max-indent block)))
742 (setq cs (car csce))
743 (setq ce (cdr csce))))
744
745 (goto-char (point-min))
746 ;; Loop over all lines from BEG to END.
747 (while
748 (progn
749 (unless (and no-empty (looking-at "[ \t]*$"))
750 (move-to-column min-indent t)
751 (insert cs) (setq cs ccs) ;switch to CCS after the first line
752 (end-of-line)
753 (if (eobp) (setq cce ce))
754 (when cce
755 (when block (move-to-column max-indent t))
756 (insert cce)))
757 (end-of-line)
758 (not (or (eobp) (progn (forward-line) nil))))))))))
759
760 ;;;###autoload
761 (defun comment-region (beg end &optional arg)
762 "Comment or uncomment each line in the region.
763 With just \\[universal-prefix] prefix arg, uncomment each line in region BEG..END.
764 Numeric prefix arg ARG means use ARG comment characters.
765 If ARG is negative, delete that many comment characters instead.
766 By default, comments start at the left margin, are terminated on each line,
767 even for syntax in which newline does not end the comment and blank lines
768 do not get comments. This can be changed with `comment-style'.
769
770 The strings used as comment starts are built from
771 `comment-start' without trailing spaces and `comment-padding'."
772 (interactive "*r\nP")
773 (comment-normalize-vars)
774 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
775 (let* ((numarg (prefix-numeric-value arg))
776 (add comment-add)
777 (style (cdr (assoc comment-style comment-styles)))
778 (lines (nth 2 style))
779 (block (nth 1 style))
780 (multi (nth 0 style)))
781 (save-excursion
782 ;; we use `chars' instead of `syntax' because `\n' might be
783 ;; of end-comment syntax rather than of whitespace syntax.
784 ;; sanitize BEG and END
785 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
786 (setq beg (max beg (point)))
787 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
788 (setq end (min end (point)))
789 (if (>= beg end) (error "Nothing to comment"))
790
791 ;; sanitize LINES
792 (setq lines
793 (and
794 lines ;; multi
795 (progn (goto-char beg) (beginning-of-line)
796 (skip-syntax-forward " ")
797 (>= (point) beg))
798 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
799 (<= (point) end))
800 (or (not (string= "" comment-end)) block)
801 (progn (goto-char beg) (search-forward "\n" end t)))))
802
803 ;; don't add end-markers just because the user asked for `block'
804 (unless (or lines (string= "" comment-end)) (setq block nil))
805
806 (cond
807 ((consp arg) (uncomment-region beg end))
808 ((< numarg 0) (uncomment-region beg end (- numarg)))
809 (t
810 (setq numarg (if (and (null arg) (= (length comment-start) 1))
811 add (1- numarg)))
812 (comment-region-internal
813 beg end
814 (let ((s (comment-padright comment-start numarg)))
815 (if (string-match comment-start-skip s) s
816 (comment-padright comment-start)))
817 (let ((s (comment-padleft comment-end numarg)))
818 (and s (if (string-match comment-end-skip s) s
819 (comment-padright comment-end))))
820 (if multi (comment-padright comment-continue numarg))
821 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
822 block
823 lines
824 (nth 3 style))))))
825
826 (defun comment-box (beg end &optional arg)
827 "Comment out the BEG..END region, putting it inside a box.
828 The numeric prefix ARG specifies how many characters to add to begin- and
829 end- comment markers additionally to what `comment-add' already specifies."
830 (interactive "*r\np")
831 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
832 'box-multi 'box)))
833 (comment-region beg end (+ comment-add arg))))
834
835 ;;;###autoload
836 (defun comment-dwim (arg)
837 "Call the comment command you want (Do What I Mean).
838 If the region is active and `transient-mark-mode' is on, call
839 `comment-region' (unless it only consists in comments, in which
840 case it calls `uncomment-region').
841 Else, if the current line is empty, insert a comment and indent it.
842 Else if a prefix ARG is specified, call `comment-kill'.
843 Else, call `comment-indent'."
844 (interactive "*P")
845 (comment-normalize-vars)
846 (if (and mark-active transient-mark-mode)
847 (let ((beg (min (point) (mark)))
848 (end (max (point) (mark))))
849 (if (save-excursion ;; check for already commented region
850 (goto-char beg)
851 (comment-forward (point-max))
852 (<= end (point)))
853 (uncomment-region beg end arg)
854 (comment-region beg end arg)))
855 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
856 ;; FIXME: If there's no comment to kill on this line and ARG is
857 ;; specified, calling comment-kill is not very clever.
858 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
859 (let ((add (if arg (prefix-numeric-value arg)
860 (if (= (length comment-start) 1) comment-add 0))))
861 (insert (comment-padright comment-start add))
862 (save-excursion
863 (unless (string= "" comment-end)
864 (insert (comment-padleft comment-end add)))
865 (indent-according-to-mode))))))
866
867 (defcustom comment-auto-fill-only-comments nil
868 "Non-nil means to only auto-fill inside comments.
869 This has no effect in modes that do not define a comment syntax."
870 :type 'boolean
871 :group 'comment)
872
873 ;;;###autoload
874 (defun comment-indent-new-line (&optional soft)
875 "Break line at point and indent, continuing comment if within one.
876 This indents the body of the continued comment
877 under the previous comment line.
878
879 This command is intended for styles where you write a comment per line,
880 starting a new comment (and terminating it if necessary) on each line.
881 If you want to continue one comment across several lines, use \\[newline-and-indent].
882
883 If a fill column is specified, it overrides the use of the comment column
884 or comment indentation.
885
886 The inserted newline is marked hard if variable `use-hard-newlines' is true,
887 unless optional argument SOFT is non-nil."
888 (interactive)
889 (comment-normalize-vars t)
890 (let (compos comin)
891 ;; If we are not inside a comment and we only auto-fill comments,
892 ;; don't do anything (unless no comment syntax is defined).
893 (unless (and comment-start
894 comment-auto-fill-only-comments
895 (not (save-excursion
896 (prog1 (setq compos (comment-beginning))
897 (setq comin (point))))))
898
899 ;; Now we know we should auto-fill.
900 (delete-region (progn (skip-chars-backward " \t") (point))
901 (progn (skip-chars-forward " \t") (point)))
902 (if soft (insert-and-inherit ?\n) (newline 1))
903 (if fill-prefix
904 (progn
905 (indent-to-left-margin)
906 (insert-and-inherit fill-prefix))
907
908 ;; If necessary check whether we're inside a comment.
909 (unless (or comment-multi-line compos (null comment-start))
910 (save-excursion
911 (backward-char)
912 (setq compos (comment-beginning))
913 (setq comin (point))))
914
915 ;; If we're not inside a comment, just try to indent.
916 (if (not compos) (indent-according-to-mode)
917 (let* ((comment-column
918 ;; The continuation indentation should be somewhere between
919 ;; the current line's indentation (plus 2 for good measure)
920 ;; and the current comment's indentation, with a preference
921 ;; for comment-column.
922 (save-excursion
923 (goto-char compos)
924 (min (current-column) (max comment-column
925 (+ 2 (current-indentation))))))
926 (comstart (buffer-substring compos comin))
927 (normalp
928 (string-match (regexp-quote (comment-string-strip
929 comment-start t t))
930 comstart))
931 (comment-end
932 (if normalp comment-end
933 ;; The comment starter is not the normal comment-start
934 ;; so we can't just use comment-end.
935 (save-excursion
936 (goto-char compos)
937 (if (not (comment-forward)) comment-end
938 (comment-string-strip
939 (buffer-substring
940 (save-excursion (comment-enter-backward) (point))
941 (point))
942 nil t)))))
943 (comment-start comstart)
944 ;; Force comment-continue to be recreated from comment-start.
945 (comment-continue nil))
946 (insert-and-inherit ?\n)
947 (forward-char -1)
948 (comment-indent (cadr (assoc comment-style comment-styles)))
949 (save-excursion
950 (let ((pt (point)))
951 (end-of-line)
952 (let ((comend (buffer-substring pt (point))))
953 ;; The 1+ is to make sure we delete the \n inserted above.
954 (delete-region pt (1+ (point)))
955 (beginning-of-line)
956 (backward-char)
957 (insert comend)
958 (forward-char))))))))))
959
960 (provide 'newcomment)
961
962 ;;; Change Log:
963 ;; $Log: newcomment.el,v $
964 ;; Revision 1.16 2000/06/04 22:02:11 monnier
965 ;; (comment-indent): Ignore comment-indent-hook.
966 ;;
967 ;; Revision 1.15 2000/05/25 19:05:46 monnier
968 ;; Add abundant autoload cookies.
969 ;; (comment-style): Be careful not to depend on runtime data at compile-time.
970 ;; (comment-indent-hook): Remove.
971 ;; (comment-indent): Check if comment-indent-hook is bound.
972 ;; (comment-region): Docstring fix.
973 ;;
974 ;; Revision 1.14 2000/05/23 20:06:10 monnier
975 ;; (comment-make-extra-lines): Don't use `assert'.
976 ;;
977 ;; Revision 1.13 2000/05/22 04:23:37 monnier
978 ;; (comment-region-internal): Go back to BEG after quoting
979 ;; the nested comment markers.
980 ;;
981 ;; Revision 1.12 2000/05/21 00:27:31 monnier
982 ;; (comment-styles): New `box-multi'.
983 ;; (comment-normalize-vars): Better default for comment-continue to
984 ;; avoid whitespace-only continuations.
985 ;; (comment-search-forward): Always move even in the no-syntax case.
986 ;; (comment-padright): Only obey N if it's only obeyed for padleft.
987 ;; (comment-make-extra-lines): Better handling of empty continuations.
988 ;; Use `=' for the filler if comment-start has only one character.
989 ;; (uncomment-region): Try handling the special `=' filler.
990 ;; (comment-region): Allow LINES even if MULTI is nil.
991 ;; (comment-box): Choose box style based on comment-style.
992 ;;
993 ;; Revision 1.11 2000/05/19 15:37:41 monnier
994 ;; Fix license text and author.
995 ;; Move aliases (indent-for-comment, set-comment-column, kill-comment
996 ;; and indent-new-comment-line) to the beginning of the file.
997 ;; Get rid of the last few CLisms.
998 ;; (comment-forward): Avoid decf.
999 ;; (comment-make-extra-lines): Comment-out asserts.
1000 ;; (comment-with-narrowing): Properly create uninterned symbol.
1001 ;; (comment-region-internal): Comment-out asserts. Avoid incf and decf.
1002 ;; (comment-indent-new-line): Fix bug where compt could be set but
1003 ;; not comstart. Set comment-column more carefully.
1004 ;;
1005 ;; Revision 1.10 2000/05/17 19:32:32 monnier
1006 ;; (comment-beginning): Handle unclosed comment.
1007 ;; (comment-auto-fill-only-comments): New var.
1008 ;; (comment-indent-new-line): Obey comment-auto-fill-only-comments.
1009 ;; Align with comment-column rather than previous comment if previous
1010 ;; comment's indentation is greater than comment-column.
1011 ;;
1012 ;; Revision 1.9 2000/05/16 22:02:37 monnier
1013 ;; (comment-string-strip): Strip terminating newlines.
1014 ;; (comment-search-forward): Make LIMIT compulsory.
1015 ;; If an unterminated string (rather than a comment) is found, try again,
1016 ;; assuming that the region starts inside a string.
1017 ;; (comment-beginning): Make sure we don't move if we find a comment but
1018 ;; it's not the one we're in.
1019 ;; (comment-enter-backward): Handle the case where comment-end-skip fails.
1020 ;; (comment-indent): Normalize variables and use line-end-position.
1021 ;; (comment-kill): Use line-end-position.
1022 ;; (comment-spill): Remove.
1023 ;; (comment-indent-new-line): Renamed from indent-new-comment-line.
1024 ;; Cleaned up old commented-out code.
1025 ;; Reset comment-continue and comment-end before calling comment-indent.
1026 ;;
1027 ;; Revision 1.8 2000/05/14 00:56:10 monnier
1028 ;; (comment-start, comment-start-skip, comment-end): Made `defvar'.
1029 ;; (comment-style): Extract the choice out of comment-styles.
1030 ;; (comment-continue): Just a simple string now.
1031 ;; (comment-normalize-vars): Update for the new comment-continue.
1032 ;; (until, comment-end-quote-re): Removed.
1033 ;; (comment-quote-re, comment-quote-nested): New functions for quoting.
1034 ;; These quote both the end and the start and also work for single-chars.
1035 ;; (comment-padright): Added lots of comments.
1036 ;; (comment-padleft): Added more comments. Check comment-end rather than
1037 ;; STR to determine whether N can be applied or not.
1038 ;; (uncomment-region): Rename BLOCK to BOX.
1039 ;; Use the new comment-quote-nested.
1040 ;; Use only one marker and properly set it back to nil.
1041 ;; Be more picky when eliminating continuation markers.
1042 ;;
1043 ;; Revision 1.7 2000/05/13 19:41:08 monnier
1044 ;; (comment-use-syntax): Change `maybe' to `undecided'.
1045 ;; (comment-quote-nested): New. Replaces comment-nested.
1046 ;; (comment-add): Turn into a mere defvar or a integer.
1047 ;; (comment-style): Change default to `plain'.
1048 ;; (comment-styles): Rename `plain' to `indent' and create a new plainer `plain'
1049 ;; (comment-string-reverse): Use nreverse.
1050 ;; (comment-normalize-vars): Change `maybe' to `undecided', add comments.
1051 ;; Don't infer the setting of comment-nested anymore (the default for
1052 ;; comment-quote-nested is safe). Use comment-quote-nested.
1053 ;; (comment-end-quote-re): Use comment-quote-nested.
1054 ;; (comment-search-forward): Obey LIMIT.
1055 ;; (comment-indent): Don't skip forward further past comment-search-forward.
1056 ;; (comment-padleft): Use comment-quote-nested.
1057 ;; (comment-make-extra-lines): Use `cons' rather than `values'.
1058 ;; (comment-region-internal): New arg INDENT. Use line-end-position.
1059 ;; Avoid multiple-value-setq.
1060 ;; (comment-region): Follow the new comment-add semantics.
1061 ;; Don't do box comments any more.
1062 ;; (comment-box): New function.
1063 ;; (comment-dwim): Only do the region stuff is transient-mark-active.
1064 ;;
1065 ;; Revision 1.6 1999/12/08 00:19:51 monnier
1066 ;; various fixes and gratuitous movements.
1067 ;;
1068 ;; Revision 1.5 1999/11/30 16:20:55 monnier
1069 ;; (comment-style(s)): Replaces comment-extra-lines (and comment-multi-line).
1070 ;; (comment-use-syntax): Whether to use the syntax-table or just the regexps.
1071 ;; (comment-end-skip): To find the end of the text.
1072 ;; ...
1073 ;;
1074 ;; Revision 1.4 1999/11/29 01:31:47 monnier
1075 ;; (comment-find): New function.
1076 ;; (indent-for-comment, set-comment-column, kill-comment): use it.
1077 ;;
1078 ;; Revision 1.3 1999/11/29 00:49:18 monnier
1079 ;; (kill-comment): Fixed by rewriting it with syntax-tables rather than regexps
1080 ;; (comment-normalize-vars): Set default (cdr comment-continue)
1081 ;; (comment-end-quote-re): new function taken out of `comment-region-internal'
1082 ;; (uncomment-region): Rewritten using syntax-tables. Also unquotes
1083 ;; nested comment-ends and eliminates continuation markers.
1084 ;; (comment-region-internal): Don't create a default for cce.
1085 ;; Use `comment-end-quote-re'.
1086 ;;
1087 ;; Revision 1.2 1999/11/28 21:33:55 monnier
1088 ;; (comment-make-extra-lines): Moved out of comment-region-internal.
1089 ;; (comment-with-narrowing): New macro. Provides a way to preserve
1090 ;; indentation inside narrowing.
1091 ;; (comment-region-internal): Add "\n" to close the comment if necessary.
1092 ;; Correctly handle commenting-out when BEG is not bolp.
1093 ;;
1094 ;; Revision 1.1 1999/11/28 18:51:06 monnier
1095 ;; First "working" version:
1096 ;; - uncomment-region doesn't work for some unknown reason
1097 ;; - comment-multi-line allows the use of multi line comments
1098 ;; - comment-extra-lines allows yet another style choice
1099 ;; - comment-add allows to default to `;;'
1100 ;; - comment-region on a comment calls uncomment-region
1101 ;; - C-u C-u comment-region aligns comment end markers
1102 ;; - C-u C-u C-u comment-region puts the comment inside a rectangle
1103 ;; - comment-region will try to quote comment-end markers inside the region
1104 ;; - comment-start markers are placed at the indentation level
1105 ;;
1106
1107 ;;; newcomment.el ends here