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