*** empty log message ***
[emacs.git] / lisp / newcomment.el
blob74d255fabf026cd6b1000c203b678a8862c348d9
1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999, 2000 Free Software Foundation Inc.
5 ;; Author: code extracted from Emacs-20's simple.el
6 ;; Maintainer: Stefan Monnier <monnier@cs.yale.edu>
7 ;; Keywords: comment uncomment
9 ;; This file is part of GNU Emacs.
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.
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.
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.
26 ;;; Commentary:
28 ;; A replacement for simple.el's comment-related functions.
30 ;;; Bugs:
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.
45 ;;; Todo:
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.
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).
65 ;;; Code:
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)
76 (defgroup comment nil
77 "Indenting and filling of comments."
78 :prefix "comment-"
79 :version "21.1"
80 :group 'fill)
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.")
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))
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)
103 ;;;###autoload
104 (defvar comment-start nil
105 "*String to insert to start a new comment, or nil if no comment syntax.")
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.")
113 ;;;###autoload
114 (defvar comment-end-skip nil
115 "Regexp to match the end of a comment plus everything up to its body.")
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.")
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'.")
130 (defvar block-comment-start nil)
131 (defvar block-comment-end nil)
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.")
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.")
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.")
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.")
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))
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.
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)))
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)
195 ;;;;
196 ;;;; Helpers
197 ;;;;
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))
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))
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))
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 "\\)"))))))
266 (defun comment-quote-re (str unp)
267 (concat (regexp-quote (substring str 0 1))
268 "\\\\" (if unp "+" "*")
269 (regexp-quote (substring str 1))))
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))))))))
299 ;;;;
300 ;;;; Navigation
301 ;;;;
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)))))
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))))
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))))
390 (goto-char pt)
391 nil)))))
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))))
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 " "))))))
429 ;;;;
430 ;;;; Commands
431 ;;;;
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))))
439 (when (or (/= (current-column) (current-indentation))
440 (and (> comment-add 0) (looking-at "\\s<\\S<")))
441 comment-column)))
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 ;; Ensure there's a space before the comment for things
477 ;; like sh where it matters (as well as being neater).
478 (unless (eq ?\ (char-syntax (char-before)))
479 (insert ?\ ))
480 (insert starter)
481 (setq cpos (point-marker))
482 (insert ender)))
483 (goto-char begpos)
484 ;; Compute desired indent.
485 (setq indent (save-excursion (funcall comment-indent-function)))
486 (if (not indent)
487 ;; comment-indent-function refuses: delegate to indent.
488 (indent-according-to-mode)
489 ;; Avoid moving comments past the fill-column.
490 (unless (save-excursion (skip-chars-backward " \t") (bolp))
491 (setq indent
492 (min indent
493 (+ (current-column)
494 (- (or comment-fill-column fill-column)
495 (save-excursion (end-of-line) (current-column)))))))
496 (unless (= (current-column) indent)
497 ;; If that's different from current, change it.
498 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
499 (indent-to (if (bolp) indent
500 (max indent (1+ (current-column)))))))
501 (goto-char cpos)
502 (set-marker cpos nil))))
504 ;;;###autoload
505 (defun comment-set-column (arg)
506 "Set the comment column based on point.
507 With no ARG, set the comment column to the current column.
508 With just minus as arg, kill any comment on this line.
509 With any other arg, set comment column to indentation of the previous comment
510 and then align or create a comment on this line at that column."
511 (interactive "P")
512 (cond
513 ((eq arg '-) (comment-kill nil))
514 (arg
515 (save-excursion
516 (beginning-of-line)
517 (comment-search-backward)
518 (beginning-of-line)
519 (goto-char (comment-search-forward (line-end-position)))
520 (setq comment-column (current-column))
521 (message "Comment column set to %d" comment-column))
522 (comment-indent))
523 (t (setq comment-column (current-column))
524 (message "Comment column set to %d" comment-column))))
526 ;;;###autoload
527 (defun comment-kill (arg)
528 "Kill the comment on this line, if any.
529 With prefix ARG, kill comments on that many lines starting with this one."
530 (interactive "P")
531 (dotimes (_ (prefix-numeric-value arg))
532 (save-excursion
533 (beginning-of-line)
534 (let ((cs (comment-search-forward (line-end-position) t)))
535 (when cs
536 (goto-char cs)
537 (skip-syntax-backward " ")
538 (setq cs (point))
539 (comment-forward)
540 (kill-region cs (if (bolp) (1- (point)) (point)))
541 (indent-according-to-mode))))
542 (if arg (forward-line 1))))
544 (defun comment-padright (str &optional n)
545 "Construct a string composed of STR plus `comment-padding'.
546 It also adds N copies of the last non-whitespace chars of STR.
547 If STR already contains padding, the corresponding amount is
548 ignored from `comment-padding'.
549 N defaults to 0.
550 If N is `re', a regexp is returned instead, that would match
551 the string for any N."
552 (setq n (or n 0))
553 (when (and (stringp str) (not (string= "" str)))
554 ;; Separate the actual string from any leading/trailing padding
555 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
556 (let ((s (match-string 1 str)) ;actual string
557 (lpad (substring str 0 (match-beginning 1))) ;left padding
558 (rpad (concat (substring str (match-end 1)) ;original right padding
559 (substring comment-padding ;additional right padding
560 (min (- (match-end 0) (match-end 1))
561 (length comment-padding)))))
562 ;; We can only duplicate C if the comment-end has multiple chars
563 ;; or if comments can be nested, else the comment-end `}' would
564 ;; be turned into `}}}' where only the first ends the comment
565 ;; and the rest becomes bogus junk.
566 (multi (not (and comment-quote-nested
567 ;; comment-end is a single char
568 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
569 (if (not (symbolp n))
570 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
571 ;; construct a regexp that would match anything from just S
572 ;; to any possible output of this function for any N.
573 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
574 lpad "") ;padding is not required
575 (regexp-quote s)
576 (when multi "+") ;the last char of S might be repeated
577 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
578 rpad "")))))) ;padding is not required
580 (defun comment-padleft (str &optional n)
581 "Construct a string composed of `comment-padding' plus STR.
582 It also adds N copies of the first non-whitespace chars of STR.
583 If STR already contains padding, the corresponding amount is
584 ignored from `comment-padding'.
585 N defaults to 0.
586 If N is `re', a regexp is returned instead, that would match
587 the string for any N."
588 (setq n (or n 0))
589 (when (and (stringp str) (not (string= "" str)))
590 ;; Only separate the left pad because we assume there is no right pad.
591 (string-match "\\`\\s-*" str)
592 (let ((s (substring str (match-end 0)))
593 (pad (concat (substring comment-padding
594 (min (- (match-end 0) (match-beginning 0))
595 (length comment-padding)))
596 (match-string 0 str)))
597 (c (aref str (match-end 0))) ;the first non-space char of STR
598 ;; We can only duplicate C if the comment-end has multiple chars
599 ;; or if comments can be nested, else the comment-end `}' would
600 ;; be turned into `}}}' where only the first ends the comment
601 ;; and the rest becomes bogus junk.
602 (multi (not (and comment-quote-nested
603 ;; comment-end is a single char
604 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
605 (if (not (symbolp n))
606 (concat pad (when multi (make-string n c)) s)
607 ;; Construct a regexp that would match anything from just S
608 ;; to any possible output of this function for any N.
609 ;; We match any number of leading spaces because this regexp will
610 ;; be used for uncommenting where we might want to remove
611 ;; uncomment markers with arbitrary leading space (because
612 ;; they were aligned).
613 (concat "\\s-*"
614 (if multi (concat (regexp-quote (string c)) "*"))
615 (regexp-quote s))))))
617 ;;;###autoload
618 (defun uncomment-region (beg end &optional arg)
619 "Uncomment each line in the BEG .. END region.
620 The numeric prefix ARG can specify a number of chars to remove from the
621 comment markers."
622 (interactive "*r\nP")
623 (comment-normalize-vars)
624 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
625 (save-excursion
626 (goto-char beg)
627 (setq end (copy-marker end))
628 (let* ((numarg (prefix-numeric-value arg))
629 (ccs comment-continue)
630 (srei (comment-padright ccs 're))
631 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
632 spt)
633 (while (and (< (point) end)
634 (setq spt (comment-search-forward end t)))
635 (let ((ipt (point))
636 ;; Find the end of the comment.
637 (ept (progn
638 (goto-char spt)
639 (unless (comment-forward)
640 (error "Can't find the comment end"))
641 (point)))
642 (box nil)
643 (box-equal nil)) ;Whether we might be using `=' for boxes.
644 (save-restriction
645 (narrow-to-region spt ept)
647 ;; Remove the comment-start.
648 (goto-char ipt)
649 (skip-syntax-backward " ")
650 ;; A box-comment starts with a looong comment-start marker.
651 (when (and (or (and (= (- (point) (point-min)) 1)
652 (setq box-equal t)
653 (looking-at "=\\{7\\}")
654 (not (eq (char-before (point-max)) ?\n))
655 (skip-chars-forward "="))
656 (> (- (point) (point-min) (length comment-start)) 7))
657 (> (count-lines (point-min) (point-max)) 2))
658 (setq box t))
659 (when (looking-at (regexp-quote comment-padding))
660 (goto-char (match-end 0)))
661 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
662 (goto-char (match-end 0)))
663 (if (null arg) (delete-region (point-min) (point))
664 (skip-syntax-backward " ")
665 (delete-char (- numarg)))
667 ;; Remove the end-comment (and leading padding and such).
668 (goto-char (point-max)) (comment-enter-backward)
669 ;; Check for special `=' used sometimes in comment-box.
670 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
671 (let ((pos (point)))
672 ;; skip `=' but only if there are at least 7.
673 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
674 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
675 (when (and (bolp) (not (bobp))) (backward-char))
676 (if (null arg) (delete-region (point) (point-max))
677 (skip-syntax-forward " ")
678 (delete-char numarg)))
680 ;; Unquote any nested end-comment.
681 (comment-quote-nested comment-start comment-end t)
683 ;; Eliminate continuation markers as well.
684 (when sre
685 (let* ((cce (comment-string-reverse (or comment-continue
686 comment-start)))
687 (erei (and box (comment-padleft cce 're)))
688 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
689 (goto-char (point-min))
690 (while (progn
691 (if (and ere (re-search-forward
692 ere (line-end-position) t))
693 (replace-match "" t t nil (if (match-end 2) 2 1))
694 (setq ere nil))
695 (forward-line 1)
696 (re-search-forward sre (line-end-position) t))
697 (replace-match "" t t nil (if (match-end 2) 2 1)))))
698 ;; Go to the end for the next comment.
699 (goto-char (point-max)))))
700 (set-marker end nil))))
702 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
703 "Make the leading and trailing extra lines.
704 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
705 (let ((eindent 0))
706 (if (not block)
707 ;; Try to match CS and CE's content so they align aesthetically.
708 (progn
709 (setq ce (comment-string-strip ce t t))
710 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
711 (setq eindent
712 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
713 0))))
714 ;; box comment
715 (let* ((width (- max-indent min-indent))
716 (s (concat cs "a=m" cce))
717 (e (concat ccs "a=m" ce))
718 (c (if (string-match ".*\\S-\\S-" cs)
719 (aref cs (1- (match-end 0)))
720 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
721 (aref cs (1- (match-end 0))) ?=)))
722 (re "\\s-*a=m\\s-*")
723 (_ (string-match re s))
724 (lcs (length cs))
725 (fill
726 (make-string (+ width (- (match-end 0)
727 (match-beginning 0) lcs 3)) c)))
728 (setq cs (replace-match fill t t s))
729 (when (and (not (string-match comment-start-skip cs))
730 (string-match "a=m" s))
731 ;; The whitespace around CS cannot be ignored: put it back.
732 (setq re "a=m")
733 (setq fill (make-string (- width lcs) c))
734 (setq cs (replace-match fill t t s)))
735 (string-match re e)
736 (setq ce (replace-match fill t t e))))
737 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
738 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
740 (defmacro comment-with-narrowing (beg end &rest body)
741 "Execute BODY with BEG..END narrowing.
742 Space is added (and then removed) at the beginning for the text's
743 indentation to be kept as it was before narrowing."
744 (declare (debug t) (indent 2))
745 (let ((bindent (make-symbol "bindent")))
746 `(let ((,bindent (save-excursion (goto-char beg) (current-column))))
747 (save-restriction
748 (narrow-to-region beg end)
749 (goto-char (point-min))
750 (insert (make-string ,bindent ? ))
751 (prog1
752 (progn ,@body)
753 ;; remove the bindent
754 (save-excursion
755 (goto-char (point-min))
756 (when (looking-at " *")
757 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
758 (delete-char n)
759 (setq ,bindent (- ,bindent n))))
760 (end-of-line)
761 (let ((e (point)))
762 (beginning-of-line)
763 (while (and (> ,bindent 0) (re-search-forward " *" e t))
764 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
765 (goto-char (match-beginning 0))
766 (delete-char n)
767 (setq ,bindent (- ,bindent n)))))))))))
769 (defun comment-region-internal (beg end cs ce
770 &optional ccs cce block lines indent)
771 "Comment region BEG .. END.
772 CS and CE are the comment start resp end string.
773 CCS and CCE are the comment continuation strings for the start resp end
774 of lines (default to CS and CE).
775 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
776 \(if CE is empty) and that those markers should be aligned.
777 LINES indicates that an extra lines will be used at the beginning and end
778 of the region for CE and CS.
779 INDENT indicates to put CS and CCS at the current indentation of the region
780 rather than at left margin."
781 ;;(assert (< beg end))
782 (let ((no-empty t))
783 ;; Sanitize CE and CCE.
784 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
785 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
786 ;; If CE is empty, multiline cannot be used.
787 (unless ce (setq ccs nil cce nil))
788 ;; Should we mark empty lines as well ?
789 (if (or ccs block lines) (setq no-empty nil))
790 ;; Make sure we have end-markers for BLOCK mode.
791 (when block (unless ce (setq ce (comment-string-reverse cs))))
792 ;; If BLOCK is not requested, we don't need CCE.
793 (unless block (setq cce nil))
794 ;; Continuation defaults to the same as CS and CE.
795 (unless ccs (setq ccs cs cce ce))
797 (save-excursion
798 (goto-char end)
799 ;; If the end is not at the end of a line and the comment-end
800 ;; is implicit (i.e. a newline), explicitly insert a newline.
801 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
802 (comment-with-narrowing beg end
803 (let ((min-indent (point-max))
804 (max-indent 0))
805 (goto-char (point-min))
806 ;; Quote any nested comment marker
807 (comment-quote-nested comment-start comment-end nil)
809 ;; Loop over all lines to find the needed indentations.
810 (goto-char (point-min))
811 (while
812 (progn
813 (unless (looking-at "[ \t]*$")
814 (setq min-indent (min min-indent (current-indentation))))
815 (end-of-line)
816 (setq max-indent (max max-indent (current-column)))
817 (not (or (eobp) (progn (forward-line) nil)))))
819 ;; Inserting ccs can change max-indent by (1- tab-width).
820 (setq max-indent
821 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
822 (unless indent (setq min-indent 0))
824 ;; make the leading and trailing lines if requested
825 (when lines
826 (let ((csce
827 (comment-make-extra-lines
828 cs ce ccs cce min-indent max-indent block)))
829 (setq cs (car csce))
830 (setq ce (cdr csce))))
832 (goto-char (point-min))
833 ;; Loop over all lines from BEG to END.
834 (while
835 (progn
836 (unless (and no-empty (looking-at "[ \t]*$"))
837 (move-to-column min-indent t)
838 (insert cs) (setq cs ccs) ;switch to CCS after the first line
839 (end-of-line)
840 (if (eobp) (setq cce ce))
841 (when cce
842 (when block (move-to-column max-indent t))
843 (insert cce)))
844 (end-of-line)
845 (not (or (eobp) (progn (forward-line) nil))))))))))
847 ;;;###autoload
848 (defun comment-region (beg end &optional arg)
849 "Comment or uncomment each line in the region.
850 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
851 Numeric prefix arg ARG means use ARG comment characters.
852 If ARG is negative, delete that many comment characters instead.
853 By default, comments start at the left margin, are terminated on each line,
854 even for syntax in which newline does not end the comment and blank lines
855 do not get comments. This can be changed with `comment-style'.
857 The strings used as comment starts are built from
858 `comment-start' without trailing spaces and `comment-padding'."
859 (interactive "*r\nP")
860 (comment-normalize-vars)
861 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
862 (let* ((numarg (prefix-numeric-value arg))
863 (add comment-add)
864 (style (cdr (assoc comment-style comment-styles)))
865 (lines (nth 2 style))
866 (block (nth 1 style))
867 (multi (nth 0 style)))
868 (save-excursion
869 ;; we use `chars' instead of `syntax' because `\n' might be
870 ;; of end-comment syntax rather than of whitespace syntax.
871 ;; sanitize BEG and END
872 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
873 (setq beg (max beg (point)))
874 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
875 (setq end (min end (point)))
876 (if (>= beg end) (error "Nothing to comment"))
878 ;; sanitize LINES
879 (setq lines
880 (and
881 lines ;; multi
882 (progn (goto-char beg) (beginning-of-line)
883 (skip-syntax-forward " ")
884 (>= (point) beg))
885 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
886 (<= (point) end))
887 (or block (not (string= "" comment-end)))
888 (or block (progn (goto-char beg) (search-forward "\n" end t))))))
890 ;; don't add end-markers just because the user asked for `block'
891 (unless (or lines (string= "" comment-end)) (setq block nil))
893 (cond
894 ((consp arg) (uncomment-region beg end))
895 ((< numarg 0) (uncomment-region beg end (- numarg)))
897 (setq numarg (if (and (null arg) (= (length comment-start) 1))
898 add (1- numarg)))
899 (comment-region-internal
900 beg end
901 (let ((s (comment-padright comment-start numarg)))
902 (if (string-match comment-start-skip s) s
903 (comment-padright comment-start)))
904 (let ((s (comment-padleft comment-end numarg)))
905 (and s (if (string-match comment-end-skip s) s
906 (comment-padright comment-end))))
907 (if multi (comment-padright comment-continue numarg))
908 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
909 block
910 lines
911 (nth 3 style))))))
913 (defun comment-box (beg end &optional arg)
914 "Comment out the BEG .. END region, putting it inside a box.
915 The numeric prefix ARG specifies how many characters to add to begin- and
916 end- comment markers additionally to what `comment-add' already specifies."
917 (interactive "*r\np")
918 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
919 'box-multi 'box)))
920 (comment-region beg end (+ comment-add arg))))
923 ;;;###autoload
924 (defun comment-or-uncomment-region (beg end &optional arg)
925 "Call `comment-region', unless the region only consists of comments,
926 in which case call `uncomment-region'. If a prefix arg is given, it
927 is passed on to the respective function."
928 (interactive "*r\nP")
929 (funcall (if (save-excursion ;; check for already commented region
930 (goto-char beg)
931 (comment-forward (point-max))
932 (<= end (point)))
933 'uncomment-region 'comment-region)
934 beg end arg))
936 ;;;###autoload
937 (defun comment-dwim (arg)
938 "Call the comment command you want (Do What I Mean).
939 If the region is active and `transient-mark-mode' is on, call
940 `comment-region' (unless it only consists of comments, in which
941 case it calls `uncomment-region').
942 Else, if the current line is empty, insert a comment and indent it.
943 Else if a prefix ARG is specified, call `comment-kill'.
944 Else, call `comment-indent'."
945 (interactive "*P")
946 (comment-normalize-vars)
947 (if (and mark-active transient-mark-mode)
948 (comment-or-uncomment-region (region-beginning) (region-end) arg)
949 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
950 ;; FIXME: If there's no comment to kill on this line and ARG is
951 ;; specified, calling comment-kill is not very clever.
952 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
953 (let ((add (if arg (prefix-numeric-value arg)
954 (if (= (length comment-start) 1) comment-add 0))))
955 ;; Some modes insist on keeping column 0 comment in column 0
956 ;; so we need to move away from it before inserting the comment.
957 (indent-according-to-mode)
958 (insert (comment-padright comment-start add))
959 (save-excursion
960 (unless (string= "" comment-end)
961 (insert (comment-padleft comment-end add)))
962 (indent-according-to-mode))))))
964 (defcustom comment-auto-fill-only-comments nil
965 "Non-nil means to only auto-fill inside comments.
966 This has no effect in modes that do not define a comment syntax."
967 :type 'boolean)
969 (defun comment-valid-prefix (prefix compos)
971 ;; Accept any prefix if the current comment is not EOL-terminated.
972 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
973 ;; Accept any prefix that starts with a comment-start marker.
974 (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
975 fill-prefix)))
977 ;;;###autoload
978 (defun comment-indent-new-line (&optional soft)
979 "Break line at point and indent, continuing comment if within one.
980 This indents the body of the continued comment
981 under the previous comment line.
983 This command is intended for styles where you write a comment per line,
984 starting a new comment (and terminating it if necessary) on each line.
985 If you want to continue one comment across several lines, use \\[newline-and-indent].
987 If a fill column is specified, it overrides the use of the comment column
988 or comment indentation.
990 The inserted newline is marked hard if variable `use-hard-newlines' is true,
991 unless optional argument SOFT is non-nil."
992 (interactive)
993 (comment-normalize-vars t)
994 (let (compos comin)
995 ;; If we are not inside a comment and we only auto-fill comments,
996 ;; don't do anything (unless no comment syntax is defined).
997 (unless (and comment-start
998 comment-auto-fill-only-comments
999 (not (interactive-p))
1000 (not (save-excursion
1001 (prog1 (setq compos (comment-beginning))
1002 (setq comin (point))))))
1004 ;; Now we know we should auto-fill.
1005 ;; Insert the newline before removing empty space so that markers
1006 ;; get preserved better.
1007 (if soft (insert-and-inherit ?\n) (newline 1))
1008 (save-excursion (forward-char -1) (delete-horizontal-space))
1009 (delete-horizontal-space)
1011 (if (and fill-prefix (not adaptive-fill-mode))
1012 ;; Blindly trust a non-adaptive fill-prefix.
1013 (progn
1014 (indent-to-left-margin)
1015 (insert-before-markers-and-inherit fill-prefix))
1017 ;; If necessary check whether we're inside a comment.
1018 (unless (or compos (null comment-start))
1019 (save-excursion
1020 (backward-char)
1021 (setq compos (comment-beginning))
1022 (setq comin (point))))
1024 (cond
1025 ;; If there's an adaptive prefix, use it unless we're inside
1026 ;; a comment and the prefix is not a comment starter.
1027 ((and fill-prefix
1028 (or (not compos)
1029 (comment-valid-prefix fill-prefix compos)))
1030 (indent-to-left-margin)
1031 (insert-and-inherit fill-prefix))
1032 ;; If we're not inside a comment, just try to indent.
1033 ((not compos) (indent-according-to-mode))
1035 (let* ((comment-column
1036 ;; The continuation indentation should be somewhere between
1037 ;; the current line's indentation (plus 2 for good measure)
1038 ;; and the current comment's indentation, with a preference
1039 ;; for comment-column.
1040 (save-excursion
1041 ;; FIXME: use prev line's info rather than first line's.
1042 (goto-char compos)
1043 (min (current-column) (max comment-column
1044 (+ 2 (current-indentation))))))
1045 (comstart (buffer-substring compos comin))
1046 (normalp
1047 (string-match (regexp-quote (comment-string-strip
1048 comment-start t t))
1049 comstart))
1050 (comment-end
1051 (if normalp comment-end
1052 ;; The comment starter is not the normal comment-start
1053 ;; so we can't just use comment-end.
1054 (save-excursion
1055 (goto-char compos)
1056 (if (not (comment-forward)) comment-end
1057 (comment-string-strip
1058 (buffer-substring
1059 (save-excursion (comment-enter-backward) (point))
1060 (point))
1061 nil t)))))
1062 (comment-start comstart)
1063 (continuep (or comment-multi-line
1064 (cadr (assoc comment-style comment-styles))))
1065 ;; Force comment-continue to be recreated from comment-start.
1066 ;; FIXME: wrong if comment-continue was set explicitly!
1067 ;; FIXME: use prev line's continuation if available.
1068 (comment-continue nil))
1069 (if (and comment-multi-line (> (length comment-end) 0))
1070 (indent-according-to-mode)
1071 (insert-and-inherit ?\n)
1072 (forward-char -1)
1073 (comment-indent continuep)
1074 (save-excursion
1075 (let ((pt (point)))
1076 (end-of-line)
1077 (let ((comend (buffer-substring pt (point))))
1078 ;; The 1+ is to make sure we delete the \n inserted above.
1079 (delete-region pt (1+ (point)))
1080 (end-of-line 0)
1081 (insert comend))))))))))))
1083 (provide 'newcomment)
1085 ;;; newcomment.el ends here