1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999, 2000, 2002, 2003, 2004,
4 ;; 2005, 2006 Free Software Foundation, Inc.
6 ;; Author: code extracted from Emacs-20's simple.el
7 ;; Maintainer: Stefan Monnier <monnier@iro.umontreal.ca>
8 ;; Keywords: comment uncomment
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
29 ;; A replacement for simple.el's comment-related functions.
33 ;; - boxed comments in Perl are not properly uncommented because they are
34 ;; uncommented one-line at a time.
35 ;; - nested comments in sgml-mode are not properly quoted.
36 ;; - single-char nestable comment-start can only do the "\\s<+" stuff
37 ;; if the corresponding closing marker happens to be right.
38 ;; - uncomment-region with a numeric argument can render multichar
39 ;; comment markers invalid.
40 ;; - comment-indent or comment-region when called inside a comment
41 ;; will happily break the surrounding comment.
42 ;; - comment-quote-nested will not (un)quote properly all nested comment
43 ;; markers if there are more than just comment-start and comment-end.
44 ;; For example, in Pascal where {...*) and (*...} are possible.
48 ;; - rebox.el-style refill.
49 ;; - quantized steps in comment-alignment.
50 ;; - try to align tail comments.
51 ;; - check what c-comment-line-break-function has to say.
52 ;; - spill auto-fill of comments onto the end of the next line.
53 ;; - uncomment-region with a consp (for blocks) or somehow make the
54 ;; deletion of continuation markers less dangerous.
55 ;; - drop block-comment-<foo> unless it's really used.
56 ;; - uncomment-region on a subpart of a comment.
57 ;; - support gnu-style "multi-line with space in continue".
58 ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
61 ;; - when auto-filling a comment, try to move the comment to the left
62 ;; rather than break it (if possible).
63 ;; - sometimes default the comment-column to the same
64 ;; one used on the preceding line(s).
69 (defalias 'indent-for-comment
'comment-indent
)
71 (defalias 'set-comment-column
'comment-set-column
)
73 (defalias 'kill-comment
'comment-kill
)
75 (defalias 'indent-new-comment-line
'comment-indent-new-line
)
78 "Indenting and filling of comments."
83 ;; Autoload this to avoid warnings, since some major modes define it.
85 (defvar comment-use-syntax
'undecided
86 "Non-nil if syntax-tables can be used instead of regexps.
87 Can also be `undecided' which means that a somewhat expensive test will
88 be used to try to determine whether syntax-tables should be trusted
89 to understand comments or not in the given buffer.
90 Major modes should set this variable.")
92 (defcustom comment-fill-column nil
93 "Column to use for `comment-indent'. If nil, use `fill-column' instead."
94 :type
'(choice (const nil
) integer
)
98 (defcustom comment-column
32
99 "Column to indent right-margin comments to.
100 Each mode establishes a different default value for this variable; you
101 can set the value for a particular mode using that mode's hook.
102 Comments might be indented to a value smaller than this in order
103 not to go beyond `comment-fill-column'."
106 (make-variable-buffer-local 'comment-column
)
107 ;;;###autoload(put 'comment-column 'safe-local-variable 'integerp)
110 (defvar comment-start nil
111 "*String to insert to start a new comment, or nil if no comment syntax.")
112 ;;;###autoload(put 'comment-start 'safe-local-variable 'string-or-null-p)
115 (defvar comment-start-skip nil
116 "*Regexp to match the start of a comment plus everything up to its body.
117 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
118 at the place matched by the close of the first pair.")
119 ;;;###autoload(put 'comment-start-skip 'safe-local-variable 'string-or-null-p)
122 (defvar comment-end-skip nil
123 "Regexp to match the end of a comment plus everything up to its body.")
124 ;;;###autoload(put 'comment-end-skip 'safe-local-variable 'string-or-null-p)
127 (defvar comment-end
""
128 "*String to insert to end a new comment.
129 Should be an empty string if comments are terminated by end-of-line.")
130 ;;;###autoload(put 'comment-end 'safe-local-variable 'string-or-null-p)
133 (defvar comment-indent-function
'comment-indent-default
134 "Function to compute desired indentation for a comment.
135 This function is called with no args with point at the beginning of
136 the comment's starting delimiter and should return either the desired
137 column indentation or nil.
138 If nil is returned, indentation is delegated to `indent-according-to-mode'.")
141 (defvar comment-insert-comment-function nil
142 "Function to insert a comment when a line doesn't contain one.
143 The function has no args.
145 Applicable at least in modes for languages like fixed-format Fortran where
146 comments always start in column zero.")
148 (defvar comment-region-function
'comment-region-default
149 "Function to comment a region.
150 Its args are the same as those of `comment-region', but BEG and END are
151 guaranteed to be correctly ordered. It is called within `save-excursion'.
153 Applicable at least in modes for languages like fixed-format Fortran where
154 comments always start in column zero.")
156 (defvar uncomment-region-function
'uncomment-region-default
157 "Function to uncomment a region.
158 Its args are the same as those of `uncomment-region', but BEG and END are
159 guaranteed to be correctly ordered. It is called within `save-excursion'.
161 Applicable at least in modes for languages like fixed-format Fortran where
162 comments always start in column zero.")
165 (defvar block-comment-start nil
)
166 (defvar block-comment-end nil
)
168 (defvar comment-quote-nested t
169 "Non-nil if nested comments should be quoted.
170 This should be locally set by each major mode if needed.")
172 (defvar comment-continue nil
173 "Continuation string to insert for multiline comments.
174 This string will be added at the beginning of each line except the very
175 first one when commenting a region with a commenting style that allows
176 comments to span several lines.
177 It should generally have the same length as `comment-start' in order to
178 preserve indentation.
179 If it is nil a value will be automatically derived from `comment-start'
180 by replacing its first character with a space.")
182 (defvar comment-add
0
183 "How many more comment chars should be inserted by `comment-region'.
184 This determines the default value of the numeric argument of `comment-region'.
185 This should generally stay 0, except for a few modes like Lisp where
186 it can be convenient to set it to 1 so that regions are commented with
189 (defconst comment-styles
190 '((plain .
(nil nil nil nil
))
191 (indent .
(nil nil nil t
))
192 (aligned .
(nil t nil t
))
193 (multi-line .
(t nil nil t
))
194 (extra-line .
(t nil t t
))
196 (box-multi .
(t t t t
)))
197 "Possible comment styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
198 STYLE should be a mnemonic symbol.
199 MULTI specifies that comments are allowed to span multiple lines.
200 ALIGN specifies that the `comment-end' markers should be aligned.
201 EXTRA specifies that an extra line should be used before and after the
202 region to comment (to put the `comment-end' and `comment-start').
203 INDENT specifies that the `comment-start' markers should not be put at the
204 left margin but at the current indentation of the region to comment.")
207 (defcustom comment-style
'plain
208 "Style to be used for `comment-region'.
209 See `comment-styles' for a list of available styles."
210 :type
(if (boundp 'comment-styles
)
211 `(choice ,@(mapcar (lambda (s) `(const ,(car s
))) comment-styles
))
216 (defcustom comment-padding
" "
217 "Padding string that `comment-region' puts between comment chars and text.
218 Can also be an integer which will be automatically turned into a string
219 of the corresponding number of spaces.
221 Extra spacing between the comment characters and the comment text
222 makes the comment easier to read. Default is 1. nil means 0."
223 :type
'(choice string integer
(const nil
))
227 (defcustom comment-multi-line nil
228 "Non-nil means `comment-indent-new-line' continues comments.
229 That is, it inserts no new terminator or starter.
230 This affects `auto-fill-mode', which is the main reason to
231 customize this variable.
233 It also affects \\[indent-new-comment-line]. However, if you want this
234 behavior for explicit filling, you might as well use \\[newline-and-indent]."
238 (defcustom comment-empty-lines nil
239 "If nil, `comment-region' does not comment out empty lines.
240 If t, it always comments out empty lines.
241 if `eol' it only comments out empty lines if comments are
242 terminated by the end of line (i.e. `comment-end' is empty)."
243 :type
'(choice (const :tag
"Never" nil
)
244 (const :tag
"Always" t
)
245 (const :tag
"EOl-terminated" 'eol
))
252 (defun comment-string-strip (str beforep afterp
)
253 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
254 (string-match (concat "\\`" (if beforep
"\\s-*")
255 "\\(.*?\\)" (if afterp
"\\s-*\n?")
257 (match-string 1 str
))
259 (defun comment-string-reverse (s)
260 "Return the mirror image of string S, without any trailing space."
261 (comment-string-strip (concat (nreverse (string-to-list s
))) nil t
))
264 (defun comment-normalize-vars (&optional noerror
)
265 "Check and setup the variables needed by other commenting functions.
266 Functions autoloaded from newcomment.el, being entry points, should call
267 this function before any other, so the rest of the code can assume that
268 the variables are properly set."
269 (unless (and (not comment-start
) noerror
)
270 (unless comment-start
271 (let ((cs (read-string "No comment syntax is defined. Use: ")))
272 (if (zerop (length cs
))
273 (error "No comment syntax defined")
274 (set (make-local-variable 'comment-start
) cs
))))
275 ;; comment-use-syntax
276 (when (eq comment-use-syntax
'undecided
)
277 (set (make-local-variable 'comment-use-syntax
)
278 (let ((st (syntax-table))
280 (ce (if (string= "" comment-end
) "\n" comment-end
)))
281 ;; Try to skip over a comment using forward-comment
282 ;; to see if the syntax tables properly recognize it.
284 (set-syntax-table st
)
285 (insert cs
" hello " ce
)
286 (goto-char (point-min))
287 (and (forward-comment 1) (eobp))))))
289 (unless comment-padding
(setq comment-padding
0))
290 (when (integerp comment-padding
)
291 (setq comment-padding
(make-string comment-padding ?
)))
293 ;;(setq comment-start (comment-string-strip comment-start t nil))
294 ;;(setq comment-end (comment-string-strip comment-end nil t))
296 (unless (or comment-continue
(string= comment-end
""))
297 (set (make-local-variable 'comment-continue
)
298 (concat (if (string-match "\\S-\\S-" comment-start
) " " "|")
299 (substring comment-start
1)))
300 ;; Hasn't been necessary yet.
301 ;; (unless (string-match comment-start-skip comment-continue)
302 ;; (kill-local-variable 'comment-continue))
304 ;; comment-skip regexps
305 (unless (and comment-start-skip
306 ;; In case comment-start has changed since last time.
307 (string-match comment-start-skip comment-start
))
308 (set (make-local-variable 'comment-start-skip
)
309 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
310 (regexp-quote (comment-string-strip comment-start t t
))
311 ;; Let's not allow any \s- but only [ \t] since \n
312 ;; might be both a comment-end marker and \s-.
314 (unless (and comment-end-skip
315 ;; In case comment-end has changed since last time.
316 (string-match comment-end-skip comment-end
))
317 (let ((ce (if (string= "" comment-end
) "\n"
318 (comment-string-strip comment-end t t
))))
319 (set (make-local-variable 'comment-end-skip
)
320 ;; We use [ \t] rather than \s- because we don't want to
321 ;; remove ^L in C mode when uncommenting.
322 (concat "[ \t]*\\(\\s>" (if comment-quote-nested
"" "+")
323 "\\|" (regexp-quote (substring ce
0 1))
324 (if (and comment-quote-nested
(<= (length ce
) 1)) "" "+")
325 (regexp-quote (substring ce
1))
328 (defun comment-quote-re (str unp
)
329 (concat (regexp-quote (substring str
0 1))
330 "\\\\" (if unp
"+" "*")
331 (regexp-quote (substring str
1))))
333 (defun comment-quote-nested (cs ce unp
)
334 "Quote or unquote nested comments.
335 If UNP is non-nil, unquote nested comment markers."
336 (setq cs
(comment-string-strip cs t t
))
337 (setq ce
(comment-string-strip ce t t
))
338 (when (and comment-quote-nested
(> (length ce
) 0))
339 (let ((re (concat (comment-quote-re ce unp
)
340 "\\|" (comment-quote-re cs unp
))))
341 (goto-char (point-min))
342 (while (re-search-forward re nil t
)
343 (goto-char (match-beginning 0))
345 (if unp
(delete-char 1) (insert "\\"))
346 (when (= (length ce
) 1)
347 ;; If the comment-end is a single char, adding a \ after that
348 ;; "first" char won't deactivate it, so we turn such a CE
349 ;; into !CS. I.e. for pascal, we turn } into !{
351 (when (string= (match-string 0) ce
)
352 (replace-match (concat "!" cs
) t t
))
353 (when (and (< (point-min) (match-beginning 0))
354 (string= (buffer-substring (1- (match-beginning 0))
358 (delete-char (- (match-end 0) (match-beginning 0)))
365 (defvar comment-use-global-state nil
366 "Non-nil means that the global syntactic context is used.
367 More specifically, it means that `syntax-ppss' is used to find out whether
368 point is within a string or not. Major modes whose syntax is faithfully
369 described by the syntax-tables can set this to non-nil so comment markers
370 in strings will not confuse Emacs.")
372 (defun comment-search-forward (limit &optional noerror
)
373 "Find a comment start between point and LIMIT.
374 Moves point to inside the comment and returns the position of the
375 comment-starter. If no comment is found, moves point to LIMIT
376 and raises an error or returns nil if NOERROR is non-nil."
377 (if (not comment-use-syntax
)
378 (if (re-search-forward comment-start-skip limit noerror
)
379 (or (match-end 1) (match-beginning 0))
381 (unless noerror
(error "No comment")))
383 ;; Assume (at first) that pt is outside of any string.
384 (s (parse-partial-sexp pt
(or limit
(point-max)) nil nil
385 (if comment-use-global-state
(syntax-ppss pt
))
387 (when (and (nth 8 s
) (nth 3 s
) (not comment-use-global-state
))
388 ;; The search ended at eol inside a string. Try to see if it
389 ;; works better when we assume that pt is inside a string.
390 (setq s
(parse-partial-sexp
391 pt
(or limit
(point-max)) nil nil
392 (list nil nil nil
(nth 3 s
) nil nil nil nil
)
394 (if (not (and (nth 8 s
) (not (nth 3 s
))))
395 (unless noerror
(error "No comment"))
396 ;; We found the comment.
399 (bol (line-beginning-position))
401 (while (and (null end
) (>= (point) bol
))
402 (if (looking-at comment-start-skip
)
403 (setq end
(min (or limit
(point-max)) (match-end 0)))
405 (goto-char (or end pos
))
408 (defun comment-search-backward (&optional limit noerror
)
409 "Find a comment start between LIMIT and point.
410 Moves point to inside the comment and returns the position of the
411 comment-starter. If no comment is found, moves point to LIMIT
412 and raises an error or returns nil if NOERROR is non-nil."
413 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
414 ;; stop there. This can be rather bad in general, but since
415 ;; comment-search-backward is only used to find the comment-column (in
416 ;; comment-set-column) and to find the comment-start string (via
417 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
418 (if (not (re-search-backward comment-start-skip limit t
))
419 (unless noerror
(error "No comment"))
421 (let* ((end (match-end 0))
422 (cs (comment-search-forward end t
))
425 (progn (beginning-of-line)
426 (comment-search-backward limit noerror
))
427 (while (progn (goto-char cs
)
430 (setq cs
(comment-search-forward end t
))))
435 (defun comment-beginning ()
436 "Find the beginning of the enclosing comment.
437 Returns nil if not inside a comment, else moves point and returns
438 the same as `comment-search-backward'."
440 ;; We should really test `in-string-p' but that can be expensive.
441 (unless (eq (get-text-property (point) 'face
) 'font-lock-string-face
)
443 (cs (comment-search-backward nil t
)))
448 ;; For modes where comment-start and comment-end are the same,
449 ;; the search above may have found a `ce' rather than a `cs'.
450 (or (if comment-end-skip
(not (looking-at comment-end-skip
)))
451 ;; Maybe font-lock knows that it's a `cs'?
452 (eq (get-text-property (match-end 0) 'face
)
453 'font-lock-comment-face
)
454 (unless (eq (get-text-property (point) 'face
)
455 'font-lock-comment-face
)
456 ;; Let's assume it's a `cs' if we're on the same line.
457 (>= (line-end-position) pt
)))
458 ;; Make sure that PT is not past the end of the comment.
459 (if (comment-forward 1) (> (point) pt
) (eobp))))
464 (defun comment-forward (&optional n
)
465 "Skip forward over N comments.
466 Just like `forward-comment' but only for positive N
467 and can use regexps instead of syntax."
469 (if (< n
0) (error "No comment-backward")
470 (if comment-use-syntax
(forward-comment n
)
473 (if (or (forward-comment 1)
474 (and (looking-at comment-start-skip
)
475 (goto-char (match-end 0))
476 (re-search-forward comment-end-skip nil
'move
)))
480 (defun comment-enter-backward ()
481 "Move from the end of a comment to the end of its content.
482 Point is assumed to be just at the end of a comment."
485 (progn (backward-char) (skip-syntax-backward " "))
488 (narrow-to-region (line-beginning-position) (point))
489 (goto-char (point-min))
490 (re-search-forward (concat comment-end-skip
"\\'") nil t
))
491 (goto-char (match-beginning 0)))
492 ;; comment-end-skip not found. Maybe we're at EOB which implicitly
493 ;; closes the comment.
494 ((eobp) (skip-syntax-backward " "))
496 ;; else comment-end-skip was not found probably because it was not
497 ;; set right. Since \\s> should catch the single-char case, we'll
498 ;; blindly assume we're at the end of a two-char comment-end.
500 (skip-chars-backward (string (char-after)))
501 (skip-syntax-backward " ")))))
508 (defun comment-indent-default ()
509 "Default for `comment-indent-function'."
510 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
511 (or (match-end 1) (/= (current-column) (current-indentation))))
513 (when (or (/= (current-column) (current-indentation))
514 (and (> comment-add
0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
518 (defun comment-indent (&optional continue
)
519 "Indent this line's comment to `comment-column', or insert an empty comment.
520 If CONTINUE is non-nil, use the `comment-continue' markers if any."
522 (comment-normalize-vars)
523 (let* ((empty (save-excursion (beginning-of-line)
524 (looking-at "[ \t]*$")))
525 (starter (or (and continue comment-continue
)
526 (and empty block-comment-start
) comment-start
))
527 (ender (or (and continue comment-continue
"")
528 (and empty block-comment-end
) comment-end
)))
529 (unless starter
(error "No comment syntax defined"))
531 (let* ((eolpos (line-end-position))
532 (begpos (comment-search-forward eolpos t
))
534 ;; An existing comment?
537 (if (and (not (looking-at "[\t\n ]"))
538 (looking-at comment-end-skip
))
539 ;; The comment is empty and we have skipped all its space
540 ;; and landed right before the comment-ender:
541 ;; Go back to the middle of the space.
542 (forward-char (/ (skip-chars-backward " \t") -
2)))
543 (setq cpos
(point-marker)))
544 ;; If none, insert one.
545 (if comment-insert-comment-function
546 (funcall comment-insert-comment-function
)
548 ;; Some `comment-indent-function's insist on not moving
549 ;; comments that are in column 0, so we first go to the
550 ;; likely target column.
551 (indent-to comment-column
)
552 ;; Ensure there's a space before the comment for things
553 ;; like sh where it matters (as well as being neater).
554 (unless (memq (char-before) '(nil ?
\n ?
\t ?\
))
556 (setq begpos
(point))
558 (setq cpos
(point-marker))
561 ;; Compute desired indent.
562 (setq indent
(save-excursion (funcall comment-indent-function
)))
563 ;; If `indent' is nil and there's code before the comment, we can't
564 ;; use `indent-according-to-mode', so we default to comment-column.
565 (unless (or indent
(save-excursion (skip-chars-backward " \t") (bolp)))
566 (setq indent comment-column
))
568 ;; comment-indent-function refuses: delegate to line-indent.
569 (indent-according-to-mode)
570 ;; If the comment is at the left of code, adjust the indentation.
571 (unless (save-excursion (skip-chars-backward " \t") (bolp))
572 ;; Avoid moving comments past the fill-column.
573 (let ((max (+ (current-column)
574 (- (or comment-fill-column fill-column
)
575 (save-excursion (end-of-line) (current-column))))))
577 (setq indent max
) ;Don't move past the fill column.
578 ;; We can choose anywhere between indent..max.
579 ;; Let's try to align to a comment on the previous line.
582 (save-excursion (skip-chars-backward " \t")
583 (1+ (current-column))))))
585 (when (and (zerop (forward-line -
1))
586 (setq other
(comment-search-forward
587 (line-end-position) t
)))
588 (goto-char other
) (setq other
(current-column))))
589 (if (and other
(<= other max
) (>= other min
))
590 ;; There is a comment and it's in the range: bingo.
592 ;; Let's try to align to a comment on the next line, then.
595 (when (and (zerop (forward-line 1))
596 (setq other
(comment-search-forward
597 (line-end-position) t
)))
598 (goto-char other
) (setq other
(current-column))))
599 (if (and other
(<= other max
) (> other min
))
600 ;; There is a comment and it's in the range: bingo.
601 (setq indent other
))))))))
602 (unless (= (current-column) indent
)
603 ;; If that's different from current, change it.
604 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
605 (indent-to (if (bolp) indent
606 (max indent
(1+ (current-column)))))))
608 (set-marker cpos nil
))))
611 (defun comment-set-column (arg)
612 "Set the comment column based on point.
613 With no ARG, set the comment column to the current column.
614 With just minus as arg, kill any comment on this line.
615 With any other arg, set comment column to indentation of the previous comment
616 and then align or create a comment on this line at that column."
619 ((eq arg
'-
) (comment-kill nil
))
621 (comment-normalize-vars)
624 (comment-search-backward)
626 (goto-char (comment-search-forward (line-end-position)))
627 (setq comment-column
(current-column))
628 (message "Comment column set to %d" comment-column
))
630 (t (setq comment-column
(current-column))
631 (message "Comment column set to %d" comment-column
))))
634 (defun comment-kill (arg)
635 "Kill the comment on this line, if any.
636 With prefix ARG, kill comments on that many lines starting with this one."
638 (comment-normalize-vars)
639 (dotimes (_ (prefix-numeric-value arg
))
642 (let ((cs (comment-search-forward (line-end-position) t
)))
645 (skip-syntax-backward " ")
648 (kill-region cs
(if (bolp) (1- (point)) (point)))
649 (indent-according-to-mode))))
650 (if arg
(forward-line 1))))
652 (defun comment-padright (str &optional n
)
653 "Construct a string composed of STR plus `comment-padding'.
654 It also adds N copies of the last non-whitespace chars of STR.
655 If STR already contains padding, the corresponding amount is
656 ignored from `comment-padding'.
658 If N is `re', a regexp is returned instead, that would match
659 the string for any N."
661 (when (and (stringp str
) (not (string= "" str
)))
662 ;; Separate the actual string from any leading/trailing padding
663 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str
)
664 (let ((s (match-string 1 str
)) ;actual string
665 (lpad (substring str
0 (match-beginning 1))) ;left padding
666 (rpad (concat (substring str
(match-end 1)) ;original right padding
667 (substring comment-padding
;additional right padding
668 (min (- (match-end 0) (match-end 1))
669 (length comment-padding
)))))
670 ;; We can only duplicate C if the comment-end has multiple chars
671 ;; or if comments can be nested, else the comment-end `}' would
672 ;; be turned into `}}}' where only the first ends the comment
673 ;; and the rest becomes bogus junk.
674 (multi (not (and comment-quote-nested
675 ;; comment-end is a single char
676 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end
)))))
677 (if (not (symbolp n
))
678 (concat lpad s
(when multi
(make-string n
(aref str
(1- (match-end 1))))) rpad
)
679 ;; construct a regexp that would match anything from just S
680 ;; to any possible output of this function for any N.
681 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c
)) "?"))
682 lpad
"") ;padding is not required
684 (when multi
"+") ;the last char of S might be repeated
685 (mapconcat (lambda (c) (concat (regexp-quote (string c
)) "?"))
686 rpad
"")))))) ;padding is not required
688 (defun comment-padleft (str &optional n
)
689 "Construct a string composed of `comment-padding' plus STR.
690 It also adds N copies of the first non-whitespace chars of STR.
691 If STR already contains padding, the corresponding amount is
692 ignored from `comment-padding'.
694 If N is `re', a regexp is returned instead, that would match
695 the string for any N."
697 (when (and (stringp str
) (not (string= "" str
)))
698 ;; Only separate the left pad because we assume there is no right pad.
699 (string-match "\\`\\s-*" str
)
700 (let ((s (substring str
(match-end 0)))
701 (pad (concat (substring comment-padding
702 (min (- (match-end 0) (match-beginning 0))
703 (length comment-padding
)))
704 (match-string 0 str
)))
705 (c (aref str
(match-end 0))) ;the first non-space char of STR
706 ;; We can only duplicate C if the comment-end has multiple chars
707 ;; or if comments can be nested, else the comment-end `}' would
708 ;; be turned into `}}}' where only the first ends the comment
709 ;; and the rest becomes bogus junk.
710 (multi (not (and comment-quote-nested
711 ;; comment-end is a single char
712 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end
)))))
713 (if (not (symbolp n
))
714 (concat pad
(when multi
(make-string n c
)) s
)
715 ;; Construct a regexp that would match anything from just S
716 ;; to any possible output of this function for any N.
717 ;; We match any number of leading spaces because this regexp will
718 ;; be used for uncommenting where we might want to remove
719 ;; uncomment markers with arbitrary leading space (because
720 ;; they were aligned).
722 (if multi
(concat (regexp-quote (string c
)) "*"))
723 (regexp-quote s
))))))
726 (defun uncomment-region (beg end
&optional arg
)
727 "Uncomment each line in the BEG .. END region.
728 The numeric prefix ARG can specify a number of chars to remove from the
730 (interactive "*r\nP")
731 (comment-normalize-vars)
732 (when (> beg end
) (setq beg
(prog1 end
(setq end beg
))))
733 ;; Bind `comment-use-global-state' to nil. While uncommenting a region
734 ;; (which works a line at a time), a comment can appear to be
735 ;; included in a mult-line string, but it is actually not.
736 (let ((comment-use-global-state nil
))
738 (funcall uncomment-region-function beg end arg
))))
740 (defun uncomment-region-default (beg end
&optional arg
)
741 "Uncomment each line in the BEG .. END region.
742 The numeric prefix ARG can specify a number of chars to remove from the
745 (setq end
(copy-marker end
))
746 (let* ((numarg (prefix-numeric-value arg
))
747 (ccs comment-continue
)
748 (srei (comment-padright ccs
're
))
749 (csre (comment-padright comment-start
're
))
750 (sre (and srei
(concat "^\\s-*?\\(" srei
"\\)")))
752 (while (and (< (point) end
)
753 (setq spt
(comment-search-forward end t
)))
755 ;; Find the end of the comment.
758 (unless (or (comment-forward)
759 ;; Allow non-terminated comments.
761 (error "Can't find the comment end"))
764 (box-equal nil
)) ;Whether we might be using `=' for boxes.
766 (narrow-to-region spt ept
)
768 ;; Remove the comment-start.
770 (skip-syntax-backward " ")
771 ;; A box-comment starts with a looong comment-start marker.
772 (when (and (or (and (= (- (point) (point-min)) 1)
774 (looking-at "=\\{7\\}")
775 (not (eq (char-before (point-max)) ?
\n))
776 (skip-chars-forward "="))
777 (> (- (point) (point-min) (length comment-start
)) 7))
778 (> (count-lines (point-min) (point-max)) 2))
780 ;; Skip the padding. Padding can come from comment-padding and/or
781 ;; from comment-start, so we first check comment-start.
782 (if (or (save-excursion (goto-char (point-min)) (looking-at csre
))
783 (looking-at (regexp-quote comment-padding
)))
784 (goto-char (match-end 0)))
785 (when (and sre
(looking-at (concat "\\s-*\n\\s-*" srei
)))
786 (goto-char (match-end 0)))
787 (if (null arg
) (delete-region (point-min) (point))
788 (skip-syntax-backward " ")
789 (delete-char (- numarg
))
791 (save-excursion (goto-char (point-min))
792 (looking-at comment-start-skip
)))
793 ;; If there's something left but it doesn't look like
794 ;; a comment-start any more, just remove it.
795 (delete-region (point-min) (point))))
797 ;; Remove the end-comment (and leading padding and such).
798 (goto-char (point-max)) (comment-enter-backward)
799 ;; Check for special `=' used sometimes in comment-box.
800 (when (and box-equal
(not (eq (char-before (point-max)) ?
\n)))
802 ;; skip `=' but only if there are at least 7.
803 (when (> (skip-chars-backward "=") -
7) (goto-char pos
))))
804 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
805 (when (and (bolp) (not (bobp))) (backward-char))
806 (if (null arg
) (delete-region (point) (point-max))
807 (skip-syntax-forward " ")
809 (unless (or (eobp) (looking-at comment-end-skip
))
810 ;; If there's something left but it doesn't look like
811 ;; a comment-end any more, just remove it.
812 (delete-region (point) (point-max)))))
814 ;; Unquote any nested end-comment.
815 (comment-quote-nested comment-start comment-end t
)
817 ;; Eliminate continuation markers as well.
819 (let* ((cce (comment-string-reverse (or comment-continue
821 (erei (and box
(comment-padleft cce
're
)))
822 (ere (and erei
(concat "\\(" erei
"\\)\\s-*$"))))
823 (goto-char (point-min))
825 (if (and ere
(re-search-forward
826 ere
(line-end-position) t
))
827 (replace-match "" t t nil
(if (match-end 2) 2 1))
830 (re-search-forward sre
(line-end-position) t
))
831 (replace-match "" t t nil
(if (match-end 2) 2 1)))))
832 ;; Go to the end for the next comment.
833 (goto-char (point-max))))))
834 (set-marker end nil
))
836 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent
&optional block
)
837 "Make the leading and trailing extra lines.
838 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
841 ;; Try to match CS and CE's content so they align aesthetically.
843 (setq ce
(comment-string-strip ce t t
))
844 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce
"\n" cs
))
846 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
849 (let* ((width (- max-indent min-indent
))
850 (s (concat cs
"a=m" cce
))
851 (e (concat ccs
"a=m" ce
))
852 (c (if (string-match ".*\\S-\\S-" cs
)
853 (aref cs
(1- (match-end 0)))
854 (if (and (equal comment-end
"") (string-match ".*\\S-" cs
))
855 (aref cs
(1- (match-end 0))) ?
=)))
857 (_ (string-match re s
))
860 (make-string (+ width
(- (match-end 0)
861 (match-beginning 0) lcs
3)) c
)))
862 (setq cs
(replace-match fill t t s
))
863 (when (and (not (string-match comment-start-skip cs
))
864 (string-match "a=m" s
))
865 ;; The whitespace around CS cannot be ignored: put it back.
867 (setq fill
(make-string (- width lcs
) c
))
868 (setq cs
(replace-match fill t t s
)))
870 (setq ce
(replace-match fill t t e
))))
871 (cons (concat cs
"\n" (make-string min-indent ?
) ccs
)
872 (concat cce
"\n" (make-string (+ min-indent eindent
) ?
) ce
))))
874 (defmacro comment-with-narrowing
(beg end
&rest body
)
875 "Execute BODY with BEG..END narrowing.
876 Space is added (and then removed) at the beginning for the text's
877 indentation to be kept as it was before narrowing."
878 (declare (debug t
) (indent 2))
879 (let ((bindent (make-symbol "bindent")))
880 `(let ((,bindent
(save-excursion (goto-char ,beg
) (current-column))))
882 (narrow-to-region ,beg
,end
)
883 (goto-char (point-min))
884 (insert (make-string ,bindent ?
))
887 ;; remove the bindent
889 (goto-char (point-min))
890 (when (looking-at " *")
891 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent
)))
893 (setq ,bindent
(- ,bindent n
))))
897 (while (and (> ,bindent
0) (re-search-forward " *" e t
))
898 (let ((n (min ,bindent
(- (match-end 0) (match-beginning 0) 1))))
899 (goto-char (match-beginning 0))
901 (setq ,bindent
(- ,bindent n
)))))))))))
903 (defun comment-add (arg)
904 (if (and (null arg
) (= (string-match "[ \t]*\\'" comment-start
) 1))
906 (1- (prefix-numeric-value arg
))))
908 (defun comment-region-internal (beg end cs ce
909 &optional ccs cce block lines indent
)
910 "Comment region BEG .. END.
911 CS and CE are the comment start string and comment end string,
912 respectively. CCS and CCE are the comment continuation strings
913 for the start and end of lines, respectively (default to CS and CE).
914 BLOCK indicates that end of lines should be marked with either CCE,
915 CE or CS \(if CE is empty) and that those markers should be aligned.
916 LINES indicates that an extra lines will be used at the beginning
917 and end of the region for CE and CS.
918 INDENT indicates to put CS and CCS at the current indentation of
919 the region rather than at left margin."
920 ;;(assert (< beg end))
921 (let ((no-empty (not (or (eq comment-empty-lines t
)
922 (and comment-empty-lines
(zerop (length ce
)))))))
923 ;; Sanitize CE and CCE.
924 (if (and (stringp ce
) (string= "" ce
)) (setq ce nil
))
925 (if (and (stringp cce
) (string= "" cce
)) (setq cce nil
))
926 ;; If CE is empty, multiline cannot be used.
927 (unless ce
(setq ccs nil cce nil
))
928 ;; Should we mark empty lines as well ?
929 (if (or ccs block lines
) (setq no-empty nil
))
930 ;; Make sure we have end-markers for BLOCK mode.
931 (when block
(unless ce
(setq ce
(comment-string-reverse cs
))))
932 ;; If BLOCK is not requested, we don't need CCE.
933 (unless block
(setq cce nil
))
934 ;; Continuation defaults to the same as CS and CE.
935 (unless ccs
(setq ccs cs cce ce
))
939 ;; If the end is not at the end of a line and the comment-end
940 ;; is implicit (i.e. a newline), explicitly insert a newline.
941 (unless (or ce
(eolp)) (insert "\n") (indent-according-to-mode))
942 (comment-with-narrowing beg end
943 (let ((min-indent (point-max))
945 (goto-char (point-min))
946 ;; Quote any nested comment marker
947 (comment-quote-nested comment-start comment-end nil
)
949 ;; Loop over all lines to find the needed indentations.
950 (goto-char (point-min))
953 (unless (looking-at "[ \t]*$")
954 (setq min-indent
(min min-indent
(current-indentation))))
956 (setq max-indent
(max max-indent
(current-column)))
957 (not (or (eobp) (progn (forward-line) nil
)))))
960 (+ max-indent
(max (length cs
) (length ccs
))
961 ;; Inserting ccs can change max-indent by (1- tab-width)
962 ;; but only if there are TABs in the boxed text, of course.
963 (if (save-excursion (goto-char beg
)
964 (search-forward "\t" end t
))
966 (unless indent
(setq min-indent
0))
968 ;; make the leading and trailing lines if requested
971 (comment-make-extra-lines
972 cs ce ccs cce min-indent max-indent block
)))
974 (setq ce
(cdr csce
))))
976 (goto-char (point-min))
977 ;; Loop over all lines from BEG to END.
980 (unless (and no-empty
(looking-at "[ \t]*$"))
981 (move-to-column min-indent t
)
982 (insert cs
) (setq cs ccs
) ;switch to CCS after the first line
984 (if (eobp) (setq cce ce
))
986 (when block
(move-to-column max-indent t
))
989 (not (or (eobp) (progn (forward-line) nil
))))))))))
992 (defun comment-region (beg end
&optional arg
)
993 "Comment or uncomment each line in the region.
994 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
995 Numeric prefix ARG means use ARG comment characters.
996 If ARG is negative, delete that many comment characters instead.
997 By default, comments start at the left margin, are terminated on each line,
998 even for syntax in which newline does not end the comment and blank lines
999 do not get comments. This can be changed with `comment-style'.
1001 The strings used as comment starts are built from
1002 `comment-start' without trailing spaces and `comment-padding'."
1003 (interactive "*r\nP")
1004 (comment-normalize-vars)
1005 (if (> beg end
) (let (mid) (setq mid beg beg end end mid
)))
1007 ;; FIXME: maybe we should call uncomment depending on ARG.
1008 (funcall comment-region-function beg end arg
)))
1010 (defun comment-region-default (beg end
&optional arg
)
1011 (let* ((numarg (prefix-numeric-value arg
))
1012 (style (cdr (assoc comment-style comment-styles
)))
1013 (lines (nth 2 style
))
1014 (block (nth 1 style
))
1015 (multi (nth 0 style
)))
1016 ;; we use `chars' instead of `syntax' because `\n' might be
1017 ;; of end-comment syntax rather than of whitespace syntax.
1018 ;; sanitize BEG and END
1019 (goto-char beg
) (skip-chars-forward " \t\n\r") (beginning-of-line)
1020 (setq beg
(max beg
(point)))
1021 (goto-char end
) (skip-chars-backward " \t\n\r") (end-of-line)
1022 (setq end
(min end
(point)))
1023 (if (>= beg end
) (error "Nothing to comment"))
1029 (progn (goto-char beg
) (beginning-of-line)
1030 (skip-syntax-forward " ")
1032 (progn (goto-char end
) (end-of-line) (skip-syntax-backward " ")
1034 (or block
(not (string= "" comment-end
)))
1035 (or block
(progn (goto-char beg
) (search-forward "\n" end t
)))))
1037 ;; don't add end-markers just because the user asked for `block'
1038 (unless (or lines
(string= "" comment-end
)) (setq block nil
))
1041 ((consp arg
) (uncomment-region beg end
))
1042 ((< numarg
0) (uncomment-region beg end
(- numarg
)))
1044 (setq numarg
(comment-add arg
))
1045 (comment-region-internal
1047 (let ((s (comment-padright comment-start numarg
)))
1048 (if (string-match comment-start-skip s
) s
1049 (comment-padright comment-start
)))
1050 (let ((s (comment-padleft comment-end numarg
)))
1051 (and s
(if (string-match comment-end-skip s
) s
1052 (comment-padright comment-end
))))
1053 (if multi
(comment-padright comment-continue numarg
))
1055 (comment-padleft (comment-string-reverse comment-continue
) numarg
))
1060 (defun comment-box (beg end
&optional arg
)
1061 "Comment out the BEG .. END region, putting it inside a box.
1062 The numeric prefix ARG specifies how many characters to add to begin- and
1063 end- comment markers additionally to what `comment-add' already specifies."
1064 (interactive "*r\np")
1065 (let ((comment-style (if (cadr (assoc comment-style comment-styles
))
1067 (comment-region beg end
(+ comment-add arg
))))
1071 (defun comment-or-uncomment-region (beg end
&optional arg
)
1072 "Call `comment-region', unless the region only consists of comments,
1073 in which case call `uncomment-region'. If a prefix arg is given, it
1074 is passed on to the respective function."
1075 (interactive "*r\nP")
1076 (comment-normalize-vars)
1077 (funcall (if (save-excursion ;; check for already commented region
1079 (comment-forward (point-max))
1081 'uncomment-region
'comment-region
)
1085 (defun comment-dwim (arg)
1086 "Call the comment command you want (Do What I Mean).
1087 If the region is active and `transient-mark-mode' is on, call
1088 `comment-region' (unless it only consists of comments, in which
1089 case it calls `uncomment-region').
1090 Else, if the current line is empty, insert a comment and indent it.
1091 Else if a prefix ARG is specified, call `comment-kill'.
1092 Else, call `comment-indent'.
1093 You can configure `comment-style' to change the way regions are commented."
1095 (comment-normalize-vars)
1096 (if (and mark-active transient-mark-mode
)
1097 (comment-or-uncomment-region (region-beginning) (region-end) arg
)
1098 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
1099 ;; FIXME: If there's no comment to kill on this line and ARG is
1100 ;; specified, calling comment-kill is not very clever.
1101 (if arg
(comment-kill (and (integerp arg
) arg
)) (comment-indent))
1102 (let ((add (comment-add arg
)))
1103 ;; Some modes insist on keeping column 0 comment in column 0
1104 ;; so we need to move away from it before inserting the comment.
1105 (indent-according-to-mode)
1106 (insert (comment-padright comment-start add
))
1108 (unless (string= "" comment-end
)
1109 (insert (comment-padleft comment-end add
)))
1110 (indent-according-to-mode))))))
1113 (defcustom comment-auto-fill-only-comments nil
1114 "Non-nil means to only auto-fill inside comments.
1115 This has no effect in modes that do not define a comment syntax."
1119 (defun comment-valid-prefix-p (prefix compos
)
1121 ;; Accept any prefix if the current comment is not EOL-terminated.
1122 (save-excursion (goto-char compos
) (comment-forward) (not (bolp)))
1123 ;; Accept any prefix that starts with a comment-start marker.
1124 (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip
"\\)")
1128 (defun comment-indent-new-line (&optional soft
)
1129 "Break line at point and indent, continuing comment if within one.
1130 This indents the body of the continued comment
1131 under the previous comment line.
1133 This command is intended for styles where you write a comment per line,
1134 starting a new comment (and terminating it if necessary) on each line.
1135 If you want to continue one comment across several lines, use \\[newline-and-indent].
1137 If a fill column is specified, it overrides the use of the comment column
1138 or comment indentation.
1140 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1141 unless optional argument SOFT is non-nil."
1143 (comment-normalize-vars t
)
1145 ;; If we are not inside a comment and we only auto-fill comments,
1146 ;; don't do anything (unless no comment syntax is defined).
1147 (unless (and comment-start
1148 comment-auto-fill-only-comments
1149 (not (interactive-p))
1150 (not (save-excursion
1151 (prog1 (setq compos
(comment-beginning))
1152 (setq comin
(point))))))
1154 ;; Now we know we should auto-fill.
1155 ;; Insert the newline before removing empty space so that markers
1156 ;; get preserved better.
1157 (if soft
(insert-and-inherit ?
\n) (newline 1))
1158 (save-excursion (forward-char -
1) (delete-horizontal-space))
1159 (delete-horizontal-space)
1161 (if (and fill-prefix
(not adaptive-fill-mode
))
1162 ;; Blindly trust a non-adaptive fill-prefix.
1164 (indent-to-left-margin)
1165 (insert-before-markers-and-inherit fill-prefix
))
1167 ;; If necessary check whether we're inside a comment.
1168 (unless (or compos
(null comment-start
))
1171 (setq compos
(comment-beginning))
1172 (setq comin
(point))))
1175 ;; If there's an adaptive prefix, use it unless we're inside
1176 ;; a comment and the prefix is not a comment starter.
1179 (comment-valid-prefix-p fill-prefix compos
)))
1180 (indent-to-left-margin)
1181 (insert-and-inherit fill-prefix
))
1182 ;; If we're not inside a comment, just try to indent.
1183 ((not compos
) (indent-according-to-mode))
1185 (let* ((comment-column
1186 ;; The continuation indentation should be somewhere between
1187 ;; the current line's indentation (plus 2 for good measure)
1188 ;; and the current comment's indentation, with a preference
1189 ;; for comment-column.
1191 ;; FIXME: use prev line's info rather than first line's.
1193 (min (current-column) (max comment-column
1194 (+ 2 (current-indentation))))))
1195 (comstart (buffer-substring compos comin
))
1197 (string-match (regexp-quote (comment-string-strip
1201 (if normalp comment-end
1202 ;; The comment starter is not the normal comment-start
1203 ;; so we can't just use comment-end.
1206 (if (not (comment-forward)) comment-end
1207 (comment-string-strip
1209 (save-excursion (comment-enter-backward) (point))
1212 (comment-start comstart
)
1213 (continuep (or comment-multi-line
1214 (cadr (assoc comment-style comment-styles
))))
1215 ;; Force comment-continue to be recreated from comment-start.
1216 ;; FIXME: wrong if comment-continue was set explicitly!
1217 ;; FIXME: use prev line's continuation if available.
1218 (comment-continue nil
))
1219 (if (and comment-multi-line
(> (length comment-end
) 0))
1220 (indent-according-to-mode)
1221 (insert-and-inherit ?
\n)
1223 (comment-indent continuep
)
1227 (let ((comend (buffer-substring pt
(point))))
1228 ;; The 1+ is to make sure we delete the \n inserted above.
1229 (delete-region pt
(1+ (point)))
1231 (insert comend
))))))))))))
1233 (provide 'newcomment
)
1235 ;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
1236 ;;; newcomment.el ends here