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