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