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