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