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