(PKG_CHECK_MODULES): Fix quoting.
[emacs.git] / lisp / newcomment.el
blob7bd4465c9f29c51e547b65ab8bea18a4c6e80cf6
1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999,2000,2003 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 (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)))
206 ;;;;
207 ;;;; Helpers
208 ;;;;
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))
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))
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 (unless (and (not comment-start) noerror)
228 (unless comment-start
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))
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 "\\)"))))))
284 (defun comment-quote-re (str unp)
285 (concat (regexp-quote (substring str 0 1))
286 "\\\\" (if unp "+" "*")
287 (regexp-quote (substring str 1))))
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))))))))
317 ;;;;
318 ;;;; Navigation
319 ;;;;
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)))))
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))))
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))))
408 (goto-char pt)
409 nil)))))
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))))
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 " "))))))
447 ;;;;
448 ;;;; Commands
449 ;;;;
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))))
457 (when (or (/= (current-column) (current-indentation))
458 (and (> comment-add 0) (looking-at "\\s<\\S<")))
459 comment-column)))
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 `indent' is nil and there's code before the comment, we can't
505 ;; use `indent-according-to-mode', so we default to comment-column.
506 (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
507 (setq indent comment-column))
508 (if (not indent)
509 ;; comment-indent-function refuses: delegate to line-indent.
510 (indent-according-to-mode)
511 ;; If the comment is at the left of code, adjust the indentation.
512 (unless (save-excursion (skip-chars-backward " \t") (bolp))
513 ;; Avoid moving comments past the fill-column.
514 (let ((max (+ (current-column)
515 (- (or comment-fill-column fill-column)
516 (save-excursion (end-of-line) (current-column))))))
517 (if (<= max indent)
518 (setq indent max) ;Don't move past the fill column.
519 ;; We can choose anywhere between indent..max.
520 ;; Let's try to align to a comment on the previous line.
521 (let ((other nil)
522 (min (max indent
523 (save-excursion (skip-chars-backward " \t")
524 (1+ (current-column))))))
525 (save-excursion
526 (when (and (zerop (forward-line -1))
527 (setq other (comment-search-forward
528 (line-end-position) t)))
529 (goto-char other) (setq other (current-column))))
530 (if (and other (<= other max) (>= other min))
531 ;; There is a comment and it's in the range: bingo.
532 (setq indent other)
533 ;; Let's try to align to a comment on the next line, then.
534 (let ((other nil))
535 (save-excursion
536 (when (and (zerop (forward-line 1))
537 (setq other (comment-search-forward
538 (line-end-position) t)))
539 (goto-char other) (setq other (current-column))))
540 (if (and other (<= other max) (> other min))
541 ;; There is a comment and it's in the range: bingo.
542 (setq indent other))))))))
543 (unless (= (current-column) indent)
544 ;; If that's different from current, change it.
545 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
546 (indent-to (if (bolp) indent
547 (max indent (1+ (current-column)))))))
548 (goto-char cpos)
549 (set-marker cpos nil))))
551 ;;;###autoload
552 (defun comment-set-column (arg)
553 "Set the comment column based on point.
554 With no ARG, set the comment column to the current column.
555 With just minus as arg, kill any comment on this line.
556 With any other arg, set comment column to indentation of the previous comment
557 and then align or create a comment on this line at that column."
558 (interactive "P")
559 (cond
560 ((eq arg '-) (comment-kill nil))
561 (arg
562 (comment-normalize-vars)
563 (save-excursion
564 (beginning-of-line)
565 (comment-search-backward)
566 (beginning-of-line)
567 (goto-char (comment-search-forward (line-end-position)))
568 (setq comment-column (current-column))
569 (message "Comment column set to %d" comment-column))
570 (comment-indent))
571 (t (setq comment-column (current-column))
572 (message "Comment column set to %d" comment-column))))
574 ;;;###autoload
575 (defun comment-kill (arg)
576 "Kill the comment on this line, if any.
577 With prefix ARG, kill comments on that many lines starting with this one."
578 (interactive "P")
579 (comment-normalize-vars)
580 (dotimes (_ (prefix-numeric-value arg))
581 (save-excursion
582 (beginning-of-line)
583 (let ((cs (comment-search-forward (line-end-position) t)))
584 (when cs
585 (goto-char cs)
586 (skip-syntax-backward " ")
587 (setq cs (point))
588 (comment-forward)
589 (kill-region cs (if (bolp) (1- (point)) (point)))
590 (indent-according-to-mode))))
591 (if arg (forward-line 1))))
593 (defun comment-padright (str &optional n)
594 "Construct a string composed of STR plus `comment-padding'.
595 It also adds N copies of the last non-whitespace chars of STR.
596 If STR already contains padding, the corresponding amount is
597 ignored from `comment-padding'.
598 N defaults to 0.
599 If N is `re', a regexp is returned instead, that would match
600 the string for any N."
601 (setq n (or n 0))
602 (when (and (stringp str) (not (string= "" str)))
603 ;; Separate the actual string from any leading/trailing padding
604 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
605 (let ((s (match-string 1 str)) ;actual string
606 (lpad (substring str 0 (match-beginning 1))) ;left padding
607 (rpad (concat (substring str (match-end 1)) ;original right padding
608 (substring comment-padding ;additional right padding
609 (min (- (match-end 0) (match-end 1))
610 (length comment-padding)))))
611 ;; We can only duplicate C if the comment-end has multiple chars
612 ;; or if comments can be nested, else the comment-end `}' would
613 ;; be turned into `}}}' where only the first ends the comment
614 ;; and the rest becomes bogus junk.
615 (multi (not (and comment-quote-nested
616 ;; comment-end is a single char
617 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
618 (if (not (symbolp n))
619 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
620 ;; construct a regexp that would match anything from just S
621 ;; to any possible output of this function for any N.
622 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
623 lpad "") ;padding is not required
624 (regexp-quote s)
625 (when multi "+") ;the last char of S might be repeated
626 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
627 rpad "")))))) ;padding is not required
629 (defun comment-padleft (str &optional n)
630 "Construct a string composed of `comment-padding' plus STR.
631 It also adds N copies of the first non-whitespace chars of STR.
632 If STR already contains padding, the corresponding amount is
633 ignored from `comment-padding'.
634 N defaults to 0.
635 If N is `re', a regexp is returned instead, that would match
636 the string for any N."
637 (setq n (or n 0))
638 (when (and (stringp str) (not (string= "" str)))
639 ;; Only separate the left pad because we assume there is no right pad.
640 (string-match "\\`\\s-*" str)
641 (let ((s (substring str (match-end 0)))
642 (pad (concat (substring comment-padding
643 (min (- (match-end 0) (match-beginning 0))
644 (length comment-padding)))
645 (match-string 0 str)))
646 (c (aref str (match-end 0))) ;the first non-space char of STR
647 ;; We can only duplicate C if the comment-end has multiple chars
648 ;; or if comments can be nested, else the comment-end `}' would
649 ;; be turned into `}}}' where only the first ends the comment
650 ;; and the rest becomes bogus junk.
651 (multi (not (and comment-quote-nested
652 ;; comment-end is a single char
653 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
654 (if (not (symbolp n))
655 (concat pad (when multi (make-string n c)) s)
656 ;; Construct a regexp that would match anything from just S
657 ;; to any possible output of this function for any N.
658 ;; We match any number of leading spaces because this regexp will
659 ;; be used for uncommenting where we might want to remove
660 ;; uncomment markers with arbitrary leading space (because
661 ;; they were aligned).
662 (concat "\\s-*"
663 (if multi (concat (regexp-quote (string c)) "*"))
664 (regexp-quote s))))))
666 ;;;###autoload
667 (defun uncomment-region (beg end &optional arg)
668 "Uncomment each line in the BEG .. END region.
669 The numeric prefix ARG can specify a number of chars to remove from the
670 comment markers."
671 (interactive "*r\nP")
672 (comment-normalize-vars)
673 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
674 (save-excursion
675 (goto-char beg)
676 (setq end (copy-marker end))
677 (let* ((numarg (prefix-numeric-value arg))
678 (ccs comment-continue)
679 (srei (comment-padright ccs 're))
680 (csre (comment-padright comment-start 're))
681 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
682 spt)
683 (while (and (< (point) end)
684 (setq spt (comment-search-forward end t)))
685 (let ((ipt (point))
686 ;; Find the end of the comment.
687 (ept (progn
688 (goto-char spt)
689 (unless (comment-forward)
690 (error "Can't find the comment end"))
691 (point)))
692 (box nil)
693 (box-equal nil)) ;Whether we might be using `=' for boxes.
694 (save-restriction
695 (narrow-to-region spt ept)
697 ;; Remove the comment-start.
698 (goto-char ipt)
699 (skip-syntax-backward " ")
700 ;; A box-comment starts with a looong comment-start marker.
701 (when (and (or (and (= (- (point) (point-min)) 1)
702 (setq box-equal t)
703 (looking-at "=\\{7\\}")
704 (not (eq (char-before (point-max)) ?\n))
705 (skip-chars-forward "="))
706 (> (- (point) (point-min) (length comment-start)) 7))
707 (> (count-lines (point-min) (point-max)) 2))
708 (setq box t))
709 ;; Skip the padding. Padding can come from comment-padding and/or
710 ;; from comment-start, so we first check comment-start.
711 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
712 (looking-at (regexp-quote comment-padding)))
713 (goto-char (match-end 0)))
714 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
715 (goto-char (match-end 0)))
716 (if (null arg) (delete-region (point-min) (point))
717 (skip-syntax-backward " ")
718 (delete-char (- numarg))
719 (unless (or (bobp)
720 (save-excursion (goto-char (point-min))
721 (looking-at comment-start-skip)))
722 ;; If there's something left but it doesn't look like
723 ;; a comment-start any more, just remove it.
724 (delete-region (point-min) (point))))
726 ;; Remove the end-comment (and leading padding and such).
727 (goto-char (point-max)) (comment-enter-backward)
728 ;; Check for special `=' used sometimes in comment-box.
729 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
730 (let ((pos (point)))
731 ;; skip `=' but only if there are at least 7.
732 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
733 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
734 (when (and (bolp) (not (bobp))) (backward-char))
735 (if (null arg) (delete-region (point) (point-max))
736 (skip-syntax-forward " ")
737 (delete-char numarg)
738 (unless (or (eobp) (looking-at comment-end-skip))
739 ;; If there's something left but it doesn't look like
740 ;; a comment-end any more, just remove it.
741 (delete-region (point) (point-max)))))
743 ;; Unquote any nested end-comment.
744 (comment-quote-nested comment-start comment-end t)
746 ;; Eliminate continuation markers as well.
747 (when sre
748 (let* ((cce (comment-string-reverse (or comment-continue
749 comment-start)))
750 (erei (and box (comment-padleft cce 're)))
751 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
752 (goto-char (point-min))
753 (while (progn
754 (if (and ere (re-search-forward
755 ere (line-end-position) t))
756 (replace-match "" t t nil (if (match-end 2) 2 1))
757 (setq ere nil))
758 (forward-line 1)
759 (re-search-forward sre (line-end-position) t))
760 (replace-match "" t t nil (if (match-end 2) 2 1)))))
761 ;; Go to the end for the next comment.
762 (goto-char (point-max)))))
763 (set-marker end nil))))
765 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
766 "Make the leading and trailing extra lines.
767 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
768 (let ((eindent 0))
769 (if (not block)
770 ;; Try to match CS and CE's content so they align aesthetically.
771 (progn
772 (setq ce (comment-string-strip ce t t))
773 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
774 (setq eindent
775 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
776 0))))
777 ;; box comment
778 (let* ((width (- max-indent min-indent))
779 (s (concat cs "a=m" cce))
780 (e (concat ccs "a=m" ce))
781 (c (if (string-match ".*\\S-\\S-" cs)
782 (aref cs (1- (match-end 0)))
783 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
784 (aref cs (1- (match-end 0))) ?=)))
785 (re "\\s-*a=m\\s-*")
786 (_ (string-match re s))
787 (lcs (length cs))
788 (fill
789 (make-string (+ width (- (match-end 0)
790 (match-beginning 0) lcs 3)) c)))
791 (setq cs (replace-match fill t t s))
792 (when (and (not (string-match comment-start-skip cs))
793 (string-match "a=m" s))
794 ;; The whitespace around CS cannot be ignored: put it back.
795 (setq re "a=m")
796 (setq fill (make-string (- width lcs) c))
797 (setq cs (replace-match fill t t s)))
798 (string-match re e)
799 (setq ce (replace-match fill t t e))))
800 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
801 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
803 (defmacro comment-with-narrowing (beg end &rest body)
804 "Execute BODY with BEG..END narrowing.
805 Space is added (and then removed) at the beginning for the text's
806 indentation to be kept as it was before narrowing."
807 (declare (debug t) (indent 2))
808 (let ((bindent (make-symbol "bindent")))
809 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
810 (save-restriction
811 (narrow-to-region ,beg ,end)
812 (goto-char (point-min))
813 (insert (make-string ,bindent ? ))
814 (prog1
815 (progn ,@body)
816 ;; remove the bindent
817 (save-excursion
818 (goto-char (point-min))
819 (when (looking-at " *")
820 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
821 (delete-char n)
822 (setq ,bindent (- ,bindent n))))
823 (end-of-line)
824 (let ((e (point)))
825 (beginning-of-line)
826 (while (and (> ,bindent 0) (re-search-forward " *" e t))
827 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
828 (goto-char (match-beginning 0))
829 (delete-char n)
830 (setq ,bindent (- ,bindent n)))))))))))
832 (defun comment-region-internal (beg end cs ce
833 &optional ccs cce block lines indent)
834 "Comment region BEG .. END.
835 CS and CE are the comment start resp end string.
836 CCS and CCE are the comment continuation strings for the start resp end
837 of lines (default to CS and CE).
838 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
839 \(if CE is empty) and that those markers should be aligned.
840 LINES indicates that an extra lines will be used at the beginning and end
841 of the region for CE and CS.
842 INDENT indicates to put CS and CCS at the current indentation of the region
843 rather than at left margin."
844 ;;(assert (< beg end))
845 (let ((no-empty (not (or (eq comment-empty-lines t)
846 (and comment-empty-lines (zerop (length ce)))))))
847 ;; Sanitize CE and CCE.
848 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
849 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
850 ;; If CE is empty, multiline cannot be used.
851 (unless ce (setq ccs nil cce nil))
852 ;; Should we mark empty lines as well ?
853 (if (or ccs block lines) (setq no-empty nil))
854 ;; Make sure we have end-markers for BLOCK mode.
855 (when block (unless ce (setq ce (comment-string-reverse cs))))
856 ;; If BLOCK is not requested, we don't need CCE.
857 (unless block (setq cce nil))
858 ;; Continuation defaults to the same as CS and CE.
859 (unless ccs (setq ccs cs cce ce))
861 (save-excursion
862 (goto-char end)
863 ;; If the end is not at the end of a line and the comment-end
864 ;; is implicit (i.e. a newline), explicitly insert a newline.
865 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
866 (comment-with-narrowing beg end
867 (let ((min-indent (point-max))
868 (max-indent 0))
869 (goto-char (point-min))
870 ;; Quote any nested comment marker
871 (comment-quote-nested comment-start comment-end nil)
873 ;; Loop over all lines to find the needed indentations.
874 (goto-char (point-min))
875 (while
876 (progn
877 (unless (looking-at "[ \t]*$")
878 (setq min-indent (min min-indent (current-indentation))))
879 (end-of-line)
880 (setq max-indent (max max-indent (current-column)))
881 (not (or (eobp) (progn (forward-line) nil)))))
883 ;; Inserting ccs can change max-indent by (1- tab-width).
884 (setq max-indent
885 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
886 (unless indent (setq min-indent 0))
888 ;; make the leading and trailing lines if requested
889 (when lines
890 (let ((csce
891 (comment-make-extra-lines
892 cs ce ccs cce min-indent max-indent block)))
893 (setq cs (car csce))
894 (setq ce (cdr csce))))
896 (goto-char (point-min))
897 ;; Loop over all lines from BEG to END.
898 (while
899 (progn
900 (unless (and no-empty (looking-at "[ \t]*$"))
901 (move-to-column min-indent t)
902 (insert cs) (setq cs ccs) ;switch to CCS after the first line
903 (end-of-line)
904 (if (eobp) (setq cce ce))
905 (when cce
906 (when block (move-to-column max-indent t))
907 (insert cce)))
908 (end-of-line)
909 (not (or (eobp) (progn (forward-line) nil))))))))))
911 ;;;###autoload
912 (defun comment-region (beg end &optional arg)
913 "Comment or uncomment each line in the region.
914 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
915 Numeric prefix arg ARG means use ARG comment characters.
916 If ARG is negative, delete that many comment characters instead.
917 By default, comments start at the left margin, are terminated on each line,
918 even for syntax in which newline does not end the comment and blank lines
919 do not get comments. This can be changed with `comment-style'.
921 The strings used as comment starts are built from
922 `comment-start' without trailing spaces and `comment-padding'."
923 (interactive "*r\nP")
924 (comment-normalize-vars)
925 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
926 (let* ((numarg (prefix-numeric-value arg))
927 (add comment-add)
928 (style (cdr (assoc comment-style comment-styles)))
929 (lines (nth 2 style))
930 (block (nth 1 style))
931 (multi (nth 0 style)))
932 (save-excursion
933 ;; we use `chars' instead of `syntax' because `\n' might be
934 ;; of end-comment syntax rather than of whitespace syntax.
935 ;; sanitize BEG and END
936 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
937 (setq beg (max beg (point)))
938 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
939 (setq end (min end (point)))
940 (if (>= beg end) (error "Nothing to comment"))
942 ;; sanitize LINES
943 (setq lines
944 (and
945 lines ;; multi
946 (progn (goto-char beg) (beginning-of-line)
947 (skip-syntax-forward " ")
948 (>= (point) beg))
949 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
950 (<= (point) end))
951 (or block (not (string= "" comment-end)))
952 (or block (progn (goto-char beg) (search-forward "\n" end t))))))
954 ;; don't add end-markers just because the user asked for `block'
955 (unless (or lines (string= "" comment-end)) (setq block nil))
957 (cond
958 ((consp arg) (uncomment-region beg end))
959 ((< numarg 0) (uncomment-region beg end (- numarg)))
961 (setq numarg (if (and (null arg) (= (length comment-start) 1))
962 add (1- numarg)))
963 (comment-region-internal
964 beg end
965 (let ((s (comment-padright comment-start numarg)))
966 (if (string-match comment-start-skip s) s
967 (comment-padright comment-start)))
968 (let ((s (comment-padleft comment-end numarg)))
969 (and s (if (string-match comment-end-skip s) s
970 (comment-padright comment-end))))
971 (if multi (comment-padright comment-continue numarg))
972 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
973 block
974 lines
975 (nth 3 style))))))
977 (defun comment-box (beg end &optional arg)
978 "Comment out the BEG .. END region, putting it inside a box.
979 The numeric prefix ARG specifies how many characters to add to begin- and
980 end- comment markers additionally to what `comment-add' already specifies."
981 (interactive "*r\np")
982 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
983 'box-multi 'box)))
984 (comment-region beg end (+ comment-add arg))))
987 ;;;###autoload
988 (defun comment-or-uncomment-region (beg end &optional arg)
989 "Call `comment-region', unless the region only consists of comments,
990 in which case call `uncomment-region'. If a prefix arg is given, it
991 is passed on to the respective function."
992 (interactive "*r\nP")
993 (comment-normalize-vars)
994 (funcall (if (save-excursion ;; check for already commented region
995 (goto-char beg)
996 (comment-forward (point-max))
997 (<= end (point)))
998 'uncomment-region 'comment-region)
999 beg end arg))
1001 ;;;###autoload
1002 (defun comment-dwim (arg)
1003 "Call the comment command you want (Do What I Mean).
1004 If the region is active and `transient-mark-mode' is on, call
1005 `comment-region' (unless it only consists of comments, in which
1006 case it calls `uncomment-region').
1007 Else, if the current line is empty, insert a comment and indent it.
1008 Else if a prefix ARG is specified, call `comment-kill'.
1009 Else, call `comment-indent'."
1010 (interactive "*P")
1011 (comment-normalize-vars)
1012 (if (and mark-active transient-mark-mode)
1013 (comment-or-uncomment-region (region-beginning) (region-end) arg)
1014 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
1015 ;; FIXME: If there's no comment to kill on this line and ARG is
1016 ;; specified, calling comment-kill is not very clever.
1017 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
1018 (let ((add (if arg (prefix-numeric-value arg)
1019 (if (= (length comment-start) 1) comment-add 0))))
1020 ;; Some modes insist on keeping column 0 comment in column 0
1021 ;; so we need to move away from it before inserting the comment.
1022 (indent-according-to-mode)
1023 (insert (comment-padright comment-start add))
1024 (save-excursion
1025 (unless (string= "" comment-end)
1026 (insert (comment-padleft comment-end add)))
1027 (indent-according-to-mode))))))
1029 (defcustom comment-auto-fill-only-comments nil
1030 "Non-nil means to only auto-fill inside comments.
1031 This has no effect in modes that do not define a comment syntax."
1032 :type 'boolean)
1034 (defun comment-valid-prefix-p (prefix compos)
1036 ;; Accept any prefix if the current comment is not EOL-terminated.
1037 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1038 ;; Accept any prefix that starts with a comment-start marker.
1039 (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1040 prefix)))
1042 ;;;###autoload
1043 (defun comment-indent-new-line (&optional soft)
1044 "Break line at point and indent, continuing comment if within one.
1045 This indents the body of the continued comment
1046 under the previous comment line.
1048 This command is intended for styles where you write a comment per line,
1049 starting a new comment (and terminating it if necessary) on each line.
1050 If you want to continue one comment across several lines, use \\[newline-and-indent].
1052 If a fill column is specified, it overrides the use of the comment column
1053 or comment indentation.
1055 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1056 unless optional argument SOFT is non-nil."
1057 (interactive)
1058 (comment-normalize-vars t)
1059 (let (compos comin)
1060 ;; If we are not inside a comment and we only auto-fill comments,
1061 ;; don't do anything (unless no comment syntax is defined).
1062 (unless (and comment-start
1063 comment-auto-fill-only-comments
1064 (not (interactive-p))
1065 (not (save-excursion
1066 (prog1 (setq compos (comment-beginning))
1067 (setq comin (point))))))
1069 ;; Now we know we should auto-fill.
1070 ;; Insert the newline before removing empty space so that markers
1071 ;; get preserved better.
1072 (if soft (insert-and-inherit ?\n) (newline 1))
1073 (save-excursion (forward-char -1) (delete-horizontal-space))
1074 (delete-horizontal-space)
1076 (if (and fill-prefix (not adaptive-fill-mode))
1077 ;; Blindly trust a non-adaptive fill-prefix.
1078 (progn
1079 (indent-to-left-margin)
1080 (insert-before-markers-and-inherit fill-prefix))
1082 ;; If necessary check whether we're inside a comment.
1083 (unless (or compos (null comment-start))
1084 (save-excursion
1085 (backward-char)
1086 (setq compos (comment-beginning))
1087 (setq comin (point))))
1089 (cond
1090 ;; If there's an adaptive prefix, use it unless we're inside
1091 ;; a comment and the prefix is not a comment starter.
1092 ((and fill-prefix
1093 (or (not compos)
1094 (comment-valid-prefix-p fill-prefix compos)))
1095 (indent-to-left-margin)
1096 (insert-and-inherit fill-prefix))
1097 ;; If we're not inside a comment, just try to indent.
1098 ((not compos) (indent-according-to-mode))
1100 (let* ((comment-column
1101 ;; The continuation indentation should be somewhere between
1102 ;; the current line's indentation (plus 2 for good measure)
1103 ;; and the current comment's indentation, with a preference
1104 ;; for comment-column.
1105 (save-excursion
1106 ;; FIXME: use prev line's info rather than first line's.
1107 (goto-char compos)
1108 (min (current-column) (max comment-column
1109 (+ 2 (current-indentation))))))
1110 (comstart (buffer-substring compos comin))
1111 (normalp
1112 (string-match (regexp-quote (comment-string-strip
1113 comment-start t t))
1114 comstart))
1115 (comment-end
1116 (if normalp comment-end
1117 ;; The comment starter is not the normal comment-start
1118 ;; so we can't just use comment-end.
1119 (save-excursion
1120 (goto-char compos)
1121 (if (not (comment-forward)) comment-end
1122 (comment-string-strip
1123 (buffer-substring
1124 (save-excursion (comment-enter-backward) (point))
1125 (point))
1126 nil t)))))
1127 (comment-start comstart)
1128 (continuep (or comment-multi-line
1129 (cadr (assoc comment-style comment-styles))))
1130 ;; Force comment-continue to be recreated from comment-start.
1131 ;; FIXME: wrong if comment-continue was set explicitly!
1132 ;; FIXME: use prev line's continuation if available.
1133 (comment-continue nil))
1134 (if (and comment-multi-line (> (length comment-end) 0))
1135 (indent-according-to-mode)
1136 (insert-and-inherit ?\n)
1137 (forward-char -1)
1138 (comment-indent continuep)
1139 (save-excursion
1140 (let ((pt (point)))
1141 (end-of-line)
1142 (let ((comend (buffer-substring pt (point))))
1143 ;; The 1+ is to make sure we delete the \n inserted above.
1144 (delete-region pt (1+ (point)))
1145 (end-of-line 0)
1146 (insert comend))))))))))))
1148 (provide 'newcomment)
1150 ;;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
1151 ;;; newcomment.el ends here