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