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