international/characters.el: Fix simple mistake ((car chars) -> elt), delete duplicat...
[emacs.git] / lisp / newcomment.el
bloba7fedf20f5377639b1d47615828334288922d9c7
1 ;;; newcomment.el --- (un)comment regions of buffers -*- lexical-binding: t -*-
3 ;; Copyright (C) 1999-2012 Free Software Foundation, Inc.
5 ;; Author: code extracted from Emacs-20's simple.el
6 ;; Maintainer: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; Keywords: comment uncomment
8 ;; Package: emacs
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 3 of the License, or
15 ;; (at your option) any later version.
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. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; A replacement for simple.el's comment-related functions.
29 ;;; Bugs:
31 ;; - boxed comments in Perl are not properly uncommented because they are
32 ;; uncommented one-line at a time.
33 ;; - nested comments in sgml-mode are not properly quoted.
34 ;; - single-char nestable comment-start can only do the "\\s<+" stuff
35 ;; if the corresponding closing marker happens to be right.
36 ;; - uncomment-region with a numeric argument can render multichar
37 ;; comment markers invalid.
38 ;; - comment-indent or comment-region when called inside a comment
39 ;; will happily break the surrounding comment.
40 ;; - comment-quote-nested will not (un)quote properly all nested comment
41 ;; markers if there are more than just comment-start and comment-end.
42 ;; For example, in Pascal where {...*) and (*...} are possible.
44 ;;; Todo:
46 ;; - rebox.el-style refill.
47 ;; - quantized steps in comment-alignment.
48 ;; - try to align tail comments.
49 ;; - check what c-comment-line-break-function has to say.
50 ;; - spill auto-fill of comments onto the end of the next line.
51 ;; - uncomment-region with a consp (for blocks) or somehow make the
52 ;; deletion of continuation markers less dangerous.
53 ;; - drop block-comment-<foo> unless it's really used.
54 ;; - uncomment-region on a subpart of a comment.
55 ;; - support gnu-style "multi-line with space in continue".
56 ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
57 ;; is not turned on.
59 ;; - when auto-filling a comment, try to move the comment to the left
60 ;; rather than break it (if possible).
61 ;; - sometimes default the comment-column to the same
62 ;; one used on the preceding line(s).
64 ;;; Code:
66 ;;;###autoload
67 (defalias 'indent-for-comment 'comment-indent)
68 ;;;###autoload
69 (defalias 'set-comment-column 'comment-set-column)
70 ;;;###autoload
71 (defalias 'kill-comment 'comment-kill)
72 ;;;###autoload
73 (defalias 'indent-new-comment-line 'comment-indent-new-line)
75 (defgroup comment nil
76 "Indenting and filling of comments."
77 :prefix "comment-"
78 :version "21.1"
79 :group 'fill)
81 ;; Autoload this to avoid warnings, since some major modes define it.
82 ;;;###autoload
83 (defvar comment-use-syntax 'undecided
84 "Non-nil if syntax-tables can be used instead of regexps.
85 Can also be `undecided' which means that a somewhat expensive test will
86 be used to try to determine whether syntax-tables should be trusted
87 to understand comments or not in the given buffer.
88 Major modes should set this variable.")
90 (defcustom comment-fill-column nil
91 "Column to use for `comment-indent'. If nil, use `fill-column' instead."
92 :type '(choice (const nil) integer)
93 :group 'comment)
95 ;;;###autoload
96 (defcustom comment-column 32
97 "Column to indent right-margin comments to.
98 Each mode may establish 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 different value in order not to go beyond
101 `comment-fill-column' or in order to align them with surrounding comments."
102 :type 'integer
103 :group 'comment)
104 (make-variable-buffer-local 'comment-column)
105 ;;;###autoload
106 (put 'comment-column 'safe-local-variable 'integerp)
108 ;;;###autoload
109 (defvar comment-start nil
110 "String to insert to start a new comment, or nil if no comment syntax.")
111 ;;;###autoload
112 (put 'comment-start 'safe-local-variable 'string-or-null-p)
114 ;;;###autoload
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
120 (put 'comment-start-skip 'safe-local-variable 'string-or-null-p)
122 ;;;###autoload
123 (defvar comment-end-skip nil
124 "Regexp to match the end of a comment plus everything back to its body.")
125 ;;;###autoload
126 (put 'comment-end-skip 'safe-local-variable 'string-or-null-p)
128 ;;;###autoload
129 (defvar comment-end (purecopy "")
130 "String to insert to end a new comment.
131 Should be an empty string if comments are terminated by end-of-line.")
132 ;;;###autoload
133 (put 'comment-end 'safe-local-variable 'string-or-null-p)
135 ;;;###autoload
136 (defvar comment-indent-function 'comment-indent-default
137 "Function to compute desired indentation for a comment.
138 This function is called with no args with point at the beginning of
139 the comment's starting delimiter and should return either the desired
140 column indentation or nil.
141 If nil is returned, indentation is delegated to `indent-according-to-mode'.")
143 ;;;###autoload
144 (defvar comment-insert-comment-function nil
145 "Function to insert a comment when a line doesn't contain one.
146 The function has no args.
148 Applicable at least in modes for languages like fixed-format Fortran where
149 comments always start in column zero.")
151 (defvar comment-region-function 'comment-region-default
152 "Function to comment a region.
153 Its args are the same as those of `comment-region', but BEG and END are
154 guaranteed to be correctly ordered. It is called within `save-excursion'.
156 Applicable at least in modes for languages like fixed-format Fortran where
157 comments always start in column zero.")
159 (defvar uncomment-region-function 'uncomment-region-default
160 "Function to uncomment a region.
161 Its args are the same as those of `uncomment-region', but BEG and END are
162 guaranteed to be correctly ordered. It is called within `save-excursion'.
164 Applicable at least in modes for languages like fixed-format Fortran where
165 comments always start in column zero.")
167 ;; ?? never set
168 (defvar block-comment-start nil)
169 (defvar block-comment-end nil)
171 (defvar comment-quote-nested t
172 "Non-nil if nested comments should be quoted.
173 This should be locally set by each major mode if needed.")
175 (defvar comment-continue nil
176 "Continuation string to insert for multiline comments.
177 This string will be added at the beginning of each line except the very
178 first one when commenting a region with a commenting style that allows
179 comments to span several lines.
180 It should generally have the same length as `comment-start' in order to
181 preserve indentation.
182 If it is nil a value will be automatically derived from `comment-start'
183 by replacing its first character with a space.")
185 (defvar comment-add 0
186 "How many more comment chars should be inserted by `comment-region'.
187 This determines the default value of the numeric argument of `comment-region'.
188 The `plain' comment style doubles this value.
190 This should generally stay 0, except for a few modes like Lisp where
191 it is 1 so that regions are commented with two or three semi-colons.")
193 ;;;###autoload
194 (defconst comment-styles
195 '((plain nil nil nil nil
196 "Start in column 0 (do not indent), as in Emacs-20")
197 (indent-or-triple nil nil nil multi-char
198 "Start in column 0, but only for single-char starters")
199 (indent nil nil nil t
200 "Full comment per line, ends not aligned")
201 (aligned nil t nil t
202 "Full comment per line, ends aligned")
203 (box nil t t t
204 "Full comment per line, ends aligned, + top and bottom")
205 (extra-line t nil t t
206 "One comment for all lines, end on a line by itself")
207 (multi-line t nil nil t
208 "One comment for all lines, end on last commented line")
209 (box-multi t t t t
210 "One comment for all lines, + top and bottom"))
211 "Comment region style definitions.
212 Each style is defined with a form (STYLE . (MULTI ALIGN EXTRA INDENT DOC)).
213 DOC should succinctly describe the style.
214 STYLE should be a mnemonic symbol.
215 MULTI specifies that comments are allowed to span multiple lines.
216 e.g. in C it comments regions as
217 /* blabla
218 * bli */
219 rather than
220 /* blabla */
221 /* bli */
222 if `comment-end' is empty, this has no effect.
224 ALIGN specifies that the `comment-end' markers should be aligned.
225 e.g. in C it comments regions as
226 /* blabla */
227 /* bli */
228 rather than
229 /* blabla */
230 /* bli */
231 if `comment-end' is empty, this has no effect, unless EXTRA is also set,
232 in which case the comment gets wrapped in a box.
234 EXTRA specifies that an extra line should be used before and after the
235 region to comment (to put the `comment-end' and `comment-start').
236 e.g. in C it comments regions as
238 * blabla
239 * bli
241 rather than
242 /* blabla
243 * bli */
244 if the comment style is not multi line, this has no effect, unless ALIGN
245 is also set, in which case the comment gets wrapped in a box.
247 INDENT specifies that the `comment-start' markers should not be put at the
248 left margin but at the current indentation of the region to comment.
249 If INDENT is `multi-char', that means indent multi-character
250 comment starters, but not one-character comment starters.")
252 ;;;###autoload
253 (defcustom comment-style 'indent
254 "Style to be used for `comment-region'.
255 See `comment-styles' for a list of available styles."
256 :type (if (boundp 'comment-styles)
257 `(choice
258 ,@(mapcar (lambda (s)
259 `(const :tag ,(format "%s: %s" (car s) (nth 5 s))
260 ,(car s)))
261 comment-styles))
262 'symbol)
263 :version "23.1"
264 :group 'comment)
266 ;;;###autoload
267 (defcustom comment-padding (purecopy " ")
268 "Padding string that `comment-region' puts between comment chars and text.
269 Can also be an integer which will be automatically turned into a string
270 of the corresponding number of spaces.
272 Extra spacing between the comment characters and the comment text
273 makes the comment easier to read. Default is 1. nil means 0."
274 :type '(choice string integer (const nil))
275 :group 'comment)
277 (defcustom comment-inline-offset 1
278 "Inline comments have to be preceded by at least this many spaces.
279 This is useful when style-conventions require a certain minimal offset.
280 Python's PEP8 for example recommends two spaces, so you could do:
282 \(add-hook 'python-mode-hook
283 (lambda () (set (make-local-variable 'comment-inline-offset) 2)))
285 See `comment-padding' for whole-line comments."
286 :version "24.3"
287 :type 'integer
288 :group 'comment)
290 ;;;###autoload
291 (defcustom comment-multi-line nil
292 "Non-nil means `comment-indent-new-line' continues comments.
293 That is, it inserts no new terminator or starter.
294 This affects `auto-fill-mode', which is the main reason to
295 customize this variable.
297 It also affects \\[indent-new-comment-line]. However, if you want this
298 behavior for explicit filling, you might as well use \\[newline-and-indent]."
299 :type 'boolean
300 :group 'comment)
302 (defcustom comment-empty-lines nil
303 "If nil, `comment-region' does not comment out empty lines.
304 If t, it always comments out empty lines.
305 If `eol' it only comments out empty lines if comments are
306 terminated by the end of line (i.e. `comment-end' is empty)."
307 :type '(choice (const :tag "Never" nil)
308 (const :tag "Always" t)
309 (const :tag "EOl-terminated" 'eol))
310 :group 'comment)
312 ;;;;
313 ;;;; Helpers
314 ;;;;
316 (defun comment-string-strip (str beforep afterp)
317 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
318 (string-match (concat "\\`" (if beforep "\\s-*")
319 "\\(.*?\\)" (if afterp "\\s-*\n?")
320 "\\'") str)
321 (match-string 1 str))
323 (defun comment-string-reverse (s)
324 "Return the mirror image of string S, without any trailing space."
325 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
327 ;;;###autoload
328 (defun comment-normalize-vars (&optional noerror)
329 "Check and setup the variables needed by other commenting functions.
330 Functions autoloaded from newcomment.el, being entry points, should call
331 this function before any other, so the rest of the code can assume that
332 the variables are properly set."
333 (unless (and (not comment-start) noerror)
334 (unless comment-start
335 (let ((cs (read-string "No comment syntax is defined. Use: ")))
336 (if (zerop (length cs))
337 (error "No comment syntax defined")
338 (set (make-local-variable 'comment-start) cs)
339 (set (make-local-variable 'comment-start-skip) cs))))
340 ;; comment-use-syntax
341 (when (eq comment-use-syntax 'undecided)
342 (set (make-local-variable 'comment-use-syntax)
343 (let ((st (syntax-table))
344 (cs comment-start)
345 (ce (if (string= "" comment-end) "\n" comment-end)))
346 ;; Try to skip over a comment using forward-comment
347 ;; to see if the syntax tables properly recognize it.
348 (with-temp-buffer
349 (set-syntax-table st)
350 (insert cs " hello " ce)
351 (goto-char (point-min))
352 (and (forward-comment 1) (eobp))))))
353 ;; comment-padding
354 (unless comment-padding (setq comment-padding 0))
355 (when (integerp comment-padding)
356 (setq comment-padding (make-string comment-padding ? )))
357 ;; comment markers
358 ;;(setq comment-start (comment-string-strip comment-start t nil))
359 ;;(setq comment-end (comment-string-strip comment-end nil t))
360 ;; comment-continue
361 (unless (or comment-continue (string= comment-end ""))
362 (set (make-local-variable 'comment-continue)
363 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
364 (substring comment-start 1)))
365 ;; Hasn't been necessary yet.
366 ;; (unless (string-match comment-start-skip comment-continue)
367 ;; (kill-local-variable 'comment-continue))
369 ;; comment-skip regexps
370 (unless (and comment-start-skip
371 ;; In case comment-start has changed since last time.
372 (string-match comment-start-skip comment-start))
373 (set (make-local-variable 'comment-start-skip)
374 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
375 (regexp-quote (comment-string-strip comment-start t t))
376 ;; Let's not allow any \s- but only [ \t] since \n
377 ;; might be both a comment-end marker and \s-.
378 "+\\)[ \t]*")))
379 (unless (and comment-end-skip
380 ;; In case comment-end has changed since last time.
381 (string-match comment-end-skip
382 (if (string= "" comment-end) "\n" comment-end)))
383 (let ((ce (if (string= "" comment-end) "\n"
384 (comment-string-strip comment-end t t))))
385 (set (make-local-variable 'comment-end-skip)
386 ;; We use [ \t] rather than \s- because we don't want to
387 ;; remove ^L in C mode when uncommenting.
388 (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
389 "\\|" (regexp-quote (substring ce 0 1))
390 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
391 (regexp-quote (substring ce 1))
392 "\\)"))))))
394 (defun comment-quote-re (str unp)
395 (concat (regexp-quote (substring str 0 1))
396 "\\\\" (if unp "+" "*")
397 (regexp-quote (substring str 1))))
399 (defun comment-quote-nested (cs ce unp)
400 "Quote or unquote nested comments.
401 If UNP is non-nil, unquote nested comment markers."
402 (setq cs (comment-string-strip cs t t))
403 (setq ce (comment-string-strip ce t t))
404 (when (and comment-quote-nested (> (length ce) 0))
405 (let ((re (concat (comment-quote-re ce unp)
406 "\\|" (comment-quote-re cs unp))))
407 (goto-char (point-min))
408 (while (re-search-forward re nil t)
409 (goto-char (match-beginning 0))
410 (forward-char 1)
411 (if unp (delete-char 1) (insert "\\"))
412 (when (= (length ce) 1)
413 ;; If the comment-end is a single char, adding a \ after that
414 ;; "first" char won't deactivate it, so we turn such a CE
415 ;; into !CS. I.e. for pascal, we turn } into !{
416 (if (not unp)
417 (when (string= (match-string 0) ce)
418 (replace-match (concat "!" cs) t t))
419 (when (and (< (point-min) (match-beginning 0))
420 (string= (buffer-substring (1- (match-beginning 0))
421 (1- (match-end 0)))
422 (concat "!" cs)))
423 (backward-char 2)
424 (delete-char (- (match-end 0) (match-beginning 0)))
425 (insert ce))))))))
427 ;;;;
428 ;;;; Navigation
429 ;;;;
431 (defvar comment-use-global-state nil
432 "Non-nil means that the global syntactic context is used.
433 More specifically, it means that `syntax-ppss' is used to find out whether
434 point is within a string or not. Major modes whose syntax is faithfully
435 described by the syntax-tables can set this to non-nil so comment markers
436 in strings will not confuse Emacs.")
438 (defun comment-search-forward (limit &optional noerror)
439 "Find a comment start between point and LIMIT.
440 Moves point to inside the comment and returns the position of the
441 comment-starter. If no comment is found, moves point to LIMIT
442 and raises an error or returns nil if NOERROR is non-nil."
443 (if (not comment-use-syntax)
444 (if (re-search-forward comment-start-skip limit noerror)
445 (or (match-end 1) (match-beginning 0))
446 (goto-char limit)
447 (unless noerror (error "No comment")))
448 (let* ((pt (point))
449 ;; Assume (at first) that pt is outside of any string.
450 (s (parse-partial-sexp pt (or limit (point-max)) nil nil
451 (if comment-use-global-state (syntax-ppss pt))
452 t)))
453 (when (and (nth 8 s) (nth 3 s) (not comment-use-global-state))
454 ;; The search ended at eol inside a string. Try to see if it
455 ;; works better when we assume that pt is inside a string.
456 (setq s (parse-partial-sexp
457 pt (or limit (point-max)) nil nil
458 (list nil nil nil (nth 3 s) nil nil nil nil)
459 t)))
460 (if (or (not (and (nth 8 s) (not (nth 3 s))))
461 ;; Make sure the comment starts after PT.
462 (< (nth 8 s) pt))
463 (unless noerror (error "No comment"))
464 ;; We found the comment.
465 (let ((pos (point))
466 (start (nth 8 s))
467 (bol (line-beginning-position))
468 (end nil))
469 (while (and (null end) (>= (point) bol))
470 (if (looking-at comment-start-skip)
471 (setq end (min (or limit (point-max)) (match-end 0)))
472 (backward-char)))
473 (goto-char (or end pos))
474 start)))))
476 (defun comment-search-backward (&optional limit noerror)
477 "Find a comment start between LIMIT and point.
478 Moves point to inside the comment and returns the position of the
479 comment-starter. If no comment is found, moves point to LIMIT
480 and raises an error or returns nil if NOERROR is non-nil."
481 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
482 ;; stop there. This can be rather bad in general, but since
483 ;; comment-search-backward is only used to find the comment-column (in
484 ;; comment-set-column) and to find the comment-start string (via
485 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
486 (if (not (re-search-backward comment-start-skip limit t))
487 (unless noerror (error "No comment"))
488 (beginning-of-line)
489 (let* ((end (match-end 0))
490 (cs (comment-search-forward end t))
491 (pt (point)))
492 (if (not cs)
493 (progn (beginning-of-line)
494 (comment-search-backward limit noerror))
495 (while (progn (goto-char cs)
496 (comment-forward)
497 (and (< (point) end)
498 (setq cs (comment-search-forward end t))))
499 (setq pt (point)))
500 (goto-char pt)
501 cs))))
503 (defun comment-beginning ()
504 "Find the beginning of the enclosing comment.
505 Returns nil if not inside a comment, else moves point and returns
506 the same as `comment-search-backward'."
507 ;; HACK ATTACK!
508 ;; We should really test `in-string-p' but that can be expensive.
509 (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
510 (let ((pt (point))
511 (cs (comment-search-backward nil t)))
512 (when cs
513 (if (save-excursion
514 (goto-char cs)
515 (and
516 ;; For modes where comment-start and comment-end are the same,
517 ;; the search above may have found a `ce' rather than a `cs'.
518 (or (if comment-end-skip (not (looking-at comment-end-skip)))
519 ;; Maybe font-lock knows that it's a `cs'?
520 (eq (get-text-property (match-end 0) 'face)
521 'font-lock-comment-face)
522 (unless (eq (get-text-property (point) 'face)
523 'font-lock-comment-face)
524 ;; Let's assume it's a `cs' if we're on the same line.
525 (>= (line-end-position) pt)))
526 ;; Make sure that PT is not past the end of the comment.
527 (if (comment-forward 1) (> (point) pt) (eobp))))
529 (goto-char pt)
530 nil)))))
532 (defun comment-forward (&optional n)
533 "Skip forward over N comments.
534 Just like `forward-comment' but only for positive N
535 and can use regexps instead of syntax."
536 (setq n (or n 1))
537 (if (< n 0) (error "No comment-backward")
538 (if comment-use-syntax (forward-comment n)
539 (while (> n 0)
540 (setq n
541 (if (or (forward-comment 1)
542 (and (looking-at comment-start-skip)
543 (goto-char (match-end 0))
544 (re-search-forward comment-end-skip nil 'move)))
545 (1- n) -1)))
546 (= n 0))))
548 (defun comment-enter-backward ()
549 "Move from the end of a comment to the end of its content.
550 Point is assumed to be just at the end of a comment."
551 (if (bolp)
552 ;; comment-end = ""
553 (progn (backward-char) (skip-syntax-backward " "))
554 (cond
555 ((save-excursion
556 (save-restriction
557 (narrow-to-region (line-beginning-position) (point))
558 (goto-char (point-min))
559 (re-search-forward (concat comment-end-skip "\\'") nil t)))
560 (goto-char (match-beginning 0)))
561 ;; comment-end-skip not found probably because it was not set
562 ;; right. Since \\s> should catch the single-char case, let's
563 ;; check that we're looking at a two-char comment ender.
564 ((not (or (<= (- (point-max) (line-beginning-position)) 1)
565 (zerop (logand (car (syntax-after (- (point) 1)))
566 ;; Here we take advantage of the fact that
567 ;; the syntax class " " is encoded to 0,
568 ;; so " 4" gives us just the 4 bit.
569 (car (string-to-syntax " 4"))))
570 (zerop (logand (car (syntax-after (- (point) 2)))
571 (car (string-to-syntax " 3"))))))
572 (backward-char 2)
573 (skip-chars-backward (string (char-after)))
574 (skip-syntax-backward " "))
575 ;; No clue what's going on: maybe we're really not right after the
576 ;; end of a comment. Maybe we're at the "end" because of EOB rather
577 ;; than because of a marker.
578 (t (skip-syntax-backward " ")))))
580 ;;;;
581 ;;;; Commands
582 ;;;;
584 ;;;###autoload
585 (defun comment-indent-default ()
586 "Default for `comment-indent-function'."
587 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
588 (or (match-end 1) (/= (current-column) (current-indentation))))
590 (when (or (/= (current-column) (current-indentation))
591 (and (> comment-add 0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
592 comment-column)))
594 (defun comment-choose-indent (&optional indent)
595 "Choose the indentation to use for a right-hand-side comment.
596 The criteria are (in this order):
597 - try to keep the comment's text within `comment-fill-column'.
598 - try to align with surrounding comments.
599 - prefer INDENT (or `comment-column' if nil).
600 Point is expected to be at the start of the comment."
601 (unless indent (setq indent comment-column))
602 ;; Avoid moving comments past the fill-column.
603 (let ((max (+ (current-column)
604 (- (or comment-fill-column fill-column)
605 (save-excursion (end-of-line) (current-column)))))
606 (other nil)
607 (min (save-excursion (skip-chars-backward " \t")
608 (if (bolp) 0 (+ comment-inline-offset (current-column))))))
609 ;; Fix up the range.
610 (if (< max min) (setq max min))
611 ;; Don't move past the fill column.
612 (if (<= max indent) (setq indent max))
613 ;; We can choose anywhere between min..max.
614 ;; Let's try to align to a comment on the previous line.
615 (save-excursion
616 (when (and (zerop (forward-line -1))
617 (setq other (comment-search-forward
618 (line-end-position) t)))
619 (goto-char other) (setq other (current-column))))
620 (if (and other (<= other max) (>= other min))
621 ;; There is a comment and it's in the range: bingo!
622 other
623 ;; Can't align to a previous comment: let's try to align to comments
624 ;; on the following lines, then. These have not been re-indented yet,
625 ;; so we can't directly align ourselves with them. All we do is to try
626 ;; and choose an indentation point with which they will be able to
627 ;; align themselves.
628 (save-excursion
629 (while (and (zerop (forward-line 1))
630 (setq other (comment-search-forward
631 (line-end-position) t)))
632 (goto-char other)
633 (let ((omax (+ (current-column)
634 (- (or comment-fill-column fill-column)
635 (save-excursion (end-of-line) (current-column)))))
636 (omin (save-excursion (skip-chars-backward " \t")
637 (1+ (current-column)))))
638 (if (and (>= omax min) (<= omin max))
639 (progn (setq min (max omin min))
640 (setq max (min omax max)))
641 ;; Can't align with this anyway, so exit the loop.
642 (goto-char (point-max))))))
643 ;; Return the closest point to indent within min..max.
644 (max min (min max indent)))))
646 ;;;###autoload
647 (defun comment-indent (&optional continue)
648 "Indent this line's comment to `comment-column', or insert an empty comment.
649 If CONTINUE is non-nil, use the `comment-continue' markers if any."
650 (interactive "*")
651 (comment-normalize-vars)
652 (let* ((empty (save-excursion (beginning-of-line)
653 (looking-at "[ \t]*$")))
654 (starter (or (and continue comment-continue)
655 (and empty block-comment-start) comment-start))
656 (ender (or (and continue comment-continue "")
657 (and empty block-comment-end) comment-end)))
658 (unless starter (error "No comment syntax defined"))
659 (beginning-of-line)
660 (let* ((eolpos (line-end-position))
661 (begpos (comment-search-forward eolpos t))
662 cpos indent)
663 (if (and comment-insert-comment-function (not begpos))
664 ;; If no comment and c-i-c-f is set, let it do everything.
665 (funcall comment-insert-comment-function)
666 ;; An existing comment?
667 (if begpos
668 (progn
669 (if (and (not (looking-at "[\t\n ]"))
670 (looking-at comment-end-skip))
671 ;; The comment is empty and we have skipped all its space
672 ;; and landed right before the comment-ender:
673 ;; Go back to the middle of the space.
674 (forward-char (/ (skip-chars-backward " \t") -2)))
675 (setq cpos (point-marker)))
676 ;; If none, insert one.
677 (save-excursion
678 ;; Some `comment-indent-function's insist on not moving
679 ;; comments that are in column 0, so we first go to the
680 ;; likely target column.
681 (indent-to comment-column)
682 ;; Ensure there's a space before the comment for things
683 ;; like sh where it matters (as well as being neater).
684 (unless (memq (char-before) '(nil ?\n ?\t ?\s))
685 (insert ?\s))
686 (setq begpos (point))
687 (insert starter)
688 (setq cpos (point-marker))
689 (insert ender)))
690 (goto-char begpos)
691 ;; Compute desired indent.
692 (setq indent (save-excursion (funcall comment-indent-function)))
693 ;; If `indent' is nil and there's code before the comment, we can't
694 ;; use `indent-according-to-mode', so we default to comment-column.
695 (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
696 (setq indent comment-column))
697 (if (not indent)
698 ;; comment-indent-function refuses: delegate to line-indent.
699 (indent-according-to-mode)
700 ;; If the comment is at the right of code, adjust the indentation.
701 (unless (save-excursion (skip-chars-backward " \t") (bolp))
702 (setq indent (comment-choose-indent indent)))
703 ;; Update INDENT to leave at least one space
704 ;; after other nonwhite text on the line.
705 (save-excursion
706 (skip-chars-backward " \t")
707 (unless (bolp)
708 (setq indent (max indent
709 (+ (current-column) comment-inline-offset)))))
710 ;; If that's different from comment's current position, change it.
711 (unless (= (current-column) indent)
712 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
713 (indent-to indent)))
714 (goto-char cpos)
715 (set-marker cpos nil)))))
717 ;;;###autoload
718 (defun comment-set-column (arg)
719 "Set the comment column based on point.
720 With no ARG, set the comment column to the current column.
721 With just minus as arg, kill any comment on this line.
722 With any other arg, set comment column to indentation of the previous comment
723 and then align or create a comment on this line at that column."
724 (interactive "P")
725 (cond
726 ((eq arg '-) (comment-kill nil))
727 (arg
728 (comment-normalize-vars)
729 (save-excursion
730 (beginning-of-line)
731 (comment-search-backward)
732 (beginning-of-line)
733 (goto-char (comment-search-forward (line-end-position)))
734 (setq comment-column (current-column))
735 (message "Comment column set to %d" comment-column))
736 (comment-indent))
737 (t (setq comment-column (current-column))
738 (message "Comment column set to %d" comment-column))))
740 ;;;###autoload
741 (defun comment-kill (arg)
742 "Kill the first comment on this line, if any.
743 With prefix ARG, kill comments on that many lines starting with this one."
744 (interactive "P")
745 (comment-normalize-vars)
746 (dotimes (_i (prefix-numeric-value arg))
747 (save-excursion
748 (beginning-of-line)
749 (let ((cs (comment-search-forward (line-end-position) t)))
750 (when cs
751 (goto-char cs)
752 (skip-syntax-backward " ")
753 (setq cs (point))
754 (comment-forward)
755 (kill-region cs (if (bolp) (1- (point)) (point)))
756 (indent-according-to-mode))))
757 (if arg (forward-line 1))))
759 (defun comment-padright (str &optional n)
760 "Construct a string composed of STR plus `comment-padding'.
761 It also adds N copies of the last non-whitespace chars of STR.
762 If STR already contains padding, the corresponding amount is
763 ignored from `comment-padding'.
764 N defaults to 0.
765 If N is `re', a regexp is returned instead, that would match
766 the string for any N."
767 (setq n (or n 0))
768 (when (and (stringp str) (not (string= "" str)))
769 ;; Separate the actual string from any leading/trailing padding
770 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
771 (let ((s (match-string 1 str)) ;actual string
772 (lpad (substring str 0 (match-beginning 1))) ;left padding
773 (rpad (concat (substring str (match-end 1)) ;original right padding
774 (substring comment-padding ;additional right padding
775 (min (- (match-end 0) (match-end 1))
776 (length comment-padding)))))
777 ;; We can only duplicate C if the comment-end has multiple chars
778 ;; or if comments can be nested, else the comment-end `}' would
779 ;; be turned into `}}}' where only the first ends the comment
780 ;; and the rest becomes bogus junk.
781 (multi (not (and comment-quote-nested
782 ;; comment-end is a single char
783 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
784 (if (not (symbolp n))
785 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
786 ;; construct a regexp that would match anything from just S
787 ;; to any possible output of this function for any N.
788 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
789 lpad "") ;padding is not required
790 (regexp-quote s)
791 (when multi "+") ;the last char of S might be repeated
792 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
793 rpad "")))))) ;padding is not required
795 (defun comment-padleft (str &optional n)
796 "Construct a string composed of `comment-padding' plus STR.
797 It also adds N copies of the first non-whitespace chars of STR.
798 If STR already contains padding, the corresponding amount is
799 ignored from `comment-padding'.
800 N defaults to 0.
801 If N is `re', a regexp is returned instead, that would match
802 the string for any N."
803 (setq n (or n 0))
804 (when (and (stringp str) (not (string= "" str)))
805 ;; Only separate the left pad because we assume there is no right pad.
806 (string-match "\\`\\s-*" str)
807 (let ((s (substring str (match-end 0)))
808 (pad (concat (substring comment-padding
809 (min (- (match-end 0) (match-beginning 0))
810 (length comment-padding)))
811 (match-string 0 str)))
812 (c (aref str (match-end 0))) ;the first non-space char of STR
813 ;; We can only duplicate C if the comment-end has multiple chars
814 ;; or if comments can be nested, else the comment-end `}' would
815 ;; be turned into `}}}' where only the first ends the comment
816 ;; and the rest becomes bogus junk.
817 (multi (not (and comment-quote-nested
818 ;; comment-end is a single char
819 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
820 (if (not (symbolp n))
821 (concat pad (when multi (make-string n c)) s)
822 ;; Construct a regexp that would match anything from just S
823 ;; to any possible output of this function for any N.
824 ;; We match any number of leading spaces because this regexp will
825 ;; be used for uncommenting where we might want to remove
826 ;; uncomment markers with arbitrary leading space (because
827 ;; they were aligned).
828 (concat "\\s-*"
829 (if multi (concat (regexp-quote (string c)) "*"))
830 (regexp-quote s))))))
832 ;;;###autoload
833 (defun uncomment-region (beg end &optional arg)
834 "Uncomment each line in the BEG .. END region.
835 The numeric prefix ARG can specify a number of chars to remove from the
836 comment markers."
837 (interactive "*r\nP")
838 (comment-normalize-vars)
839 (when (> beg end) (setq beg (prog1 end (setq end beg))))
840 ;; Bind `comment-use-global-state' to nil. While uncommenting a region
841 ;; (which works a line at a time), a comment can appear to be
842 ;; included in a mult-line string, but it is actually not.
843 (let ((comment-use-global-state nil))
844 (save-excursion
845 (funcall uncomment-region-function beg end arg))))
847 (defun uncomment-region-default (beg end &optional arg)
848 "Uncomment each line in the BEG .. END region.
849 The numeric prefix ARG can specify a number of chars to remove from the
850 comment markers."
851 (goto-char beg)
852 (setq end (copy-marker end))
853 (let* ((numarg (prefix-numeric-value arg))
854 (ccs comment-continue)
855 (srei (comment-padright ccs 're))
856 (csre (comment-padright comment-start 're))
857 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
858 spt)
859 (while (and (< (point) end)
860 (setq spt (comment-search-forward end t)))
861 (let ((ipt (point))
862 ;; Find the end of the comment.
863 (ept (progn
864 (goto-char spt)
865 (unless (or (comment-forward)
866 ;; Allow non-terminated comments.
867 (eobp))
868 (error "Can't find the comment end"))
869 (point)))
870 (box nil)
871 (box-equal nil)) ;Whether we might be using `=' for boxes.
872 (save-restriction
873 (narrow-to-region spt ept)
875 ;; Remove the comment-start.
876 (goto-char ipt)
877 (skip-syntax-backward " ")
878 ;; A box-comment starts with a looong comment-start marker.
879 (when (and (or (and (= (- (point) (point-min)) 1)
880 (setq box-equal t)
881 (looking-at "=\\{7\\}")
882 (not (eq (char-before (point-max)) ?\n))
883 (skip-chars-forward "="))
884 (> (- (point) (point-min) (length comment-start)) 7))
885 (> (count-lines (point-min) (point-max)) 2))
886 (setq box t))
887 ;; Skip the padding. Padding can come from comment-padding and/or
888 ;; from comment-start, so we first check comment-start.
889 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
890 (looking-at (regexp-quote comment-padding)))
891 (goto-char (match-end 0)))
892 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
893 (goto-char (match-end 0)))
894 (if (null arg) (delete-region (point-min) (point))
895 (let ((opoint (point-marker)))
896 (skip-syntax-backward " ")
897 (delete-char (- numarg))
898 (unless (and (not (bobp))
899 (save-excursion (goto-char (point-min))
900 (looking-at comment-start-skip)))
901 ;; If there's something left but it doesn't look like
902 ;; a comment-start any more, just remove it.
903 (delete-region (point-min) opoint))))
905 ;; Remove the end-comment (and leading padding and such).
906 (goto-char (point-max)) (comment-enter-backward)
907 ;; Check for special `=' used sometimes in comment-box.
908 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
909 (let ((pos (point)))
910 ;; skip `=' but only if there are at least 7.
911 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
912 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
913 (when (and (bolp) (not (bobp))) (backward-char))
914 (if (null arg) (delete-region (point) (point-max))
915 (skip-syntax-forward " ")
916 (delete-char numarg)
917 (unless (or (eobp) (looking-at comment-end-skip))
918 ;; If there's something left but it doesn't look like
919 ;; a comment-end any more, just remove it.
920 (delete-region (point) (point-max)))))
922 ;; Unquote any nested end-comment.
923 (comment-quote-nested comment-start comment-end t)
925 ;; Eliminate continuation markers as well.
926 (when sre
927 (let* ((cce (comment-string-reverse (or comment-continue
928 comment-start)))
929 (erei (and box (comment-padleft cce 're)))
930 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
931 (goto-char (point-min))
932 (while (progn
933 (if (and ere (re-search-forward
934 ere (line-end-position) t))
935 (replace-match "" t t nil (if (match-end 2) 2 1))
936 (setq ere nil))
937 (forward-line 1)
938 (re-search-forward sre (line-end-position) t))
939 (replace-match "" t t nil (if (match-end 2) 2 1)))))
940 ;; Go to the end for the next comment.
941 (goto-char (point-max))))))
942 (set-marker end nil))
944 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
945 "Make the leading and trailing extra lines.
946 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
947 (let ((eindent 0))
948 (if (not block)
949 ;; Try to match CS and CE's content so they align aesthetically.
950 (progn
951 (setq ce (comment-string-strip ce t t))
952 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
953 (setq eindent
954 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
955 0))))
956 ;; box comment
957 (let* ((width (- max-indent min-indent))
958 (s (concat cs "a=m" cce))
959 (e (concat ccs "a=m" ce))
960 (c (if (string-match ".*\\S-\\S-" cs)
961 (aref cs (1- (match-end 0)))
962 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
963 (aref cs (1- (match-end 0))) ?=)))
964 (re "\\s-*a=m\\s-*")
965 (_ (string-match re s))
966 (lcs (length cs))
967 (fill
968 (make-string (+ width (- (match-end 0)
969 (match-beginning 0) lcs 3)) c)))
970 (setq cs (replace-match fill t t s))
971 (when (and (not (string-match comment-start-skip cs))
972 (string-match "a=m" s))
973 ;; The whitespace around CS cannot be ignored: put it back.
974 (setq re "a=m")
975 (setq fill (make-string (- width lcs) c))
976 (setq cs (replace-match fill t t s)))
977 (string-match re e)
978 (setq ce (replace-match fill t t e))))
979 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
980 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
982 (defmacro comment-with-narrowing (beg end &rest body)
983 "Execute BODY with BEG..END narrowing.
984 Space is added (and then removed) at the beginning for the text's
985 indentation to be kept as it was before narrowing."
986 (declare (debug t) (indent 2))
987 (let ((bindent (make-symbol "bindent")))
988 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
989 (save-restriction
990 (narrow-to-region ,beg ,end)
991 (goto-char (point-min))
992 (insert (make-string ,bindent ? ))
993 (prog1
994 (progn ,@body)
995 ;; remove the bindent
996 (save-excursion
997 (goto-char (point-min))
998 (when (looking-at " *")
999 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
1000 (delete-char n)
1001 (setq ,bindent (- ,bindent n))))
1002 (end-of-line)
1003 (let ((e (point)))
1004 (beginning-of-line)
1005 (while (and (> ,bindent 0) (re-search-forward " *" e t))
1006 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
1007 (goto-char (match-beginning 0))
1008 (delete-char n)
1009 (setq ,bindent (- ,bindent n)))))))))))
1011 (defun comment-add (arg)
1012 "Compute the number of extra comment starter characters.
1013 \(Extra semicolons in Lisp mode, extra stars in C mode, etc.)
1014 If ARG is non-nil, just follow ARG.
1015 If the comment starter is multi-char, just follow ARG.
1016 Otherwise obey `comment-add'."
1017 (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
1018 (* comment-add 1)
1019 (1- (prefix-numeric-value arg))))
1021 (defun comment-region-internal (beg end cs ce
1022 &optional ccs cce block lines indent)
1023 "Comment region BEG .. END.
1024 CS and CE are the comment start string and comment end string,
1025 respectively. CCS and CCE are the comment continuation strings
1026 for the start and end of lines, respectively (default to CS and CE).
1027 BLOCK indicates that end of lines should be marked with either CCE,
1028 CE or CS \(if CE is empty) and that those markers should be aligned.
1029 LINES indicates that an extra lines will be used at the beginning
1030 and end of the region for CE and CS.
1031 INDENT indicates to put CS and CCS at the current indentation of
1032 the region rather than at left margin."
1033 ;;(assert (< beg end))
1034 (let ((no-empty (not (or (eq comment-empty-lines t)
1035 (and comment-empty-lines (zerop (length ce))))))
1036 ce-sanitized)
1037 ;; Sanitize CE and CCE.
1038 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
1039 (setq ce-sanitized ce)
1040 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
1041 ;; If CE is empty, multiline cannot be used.
1042 (unless ce (setq ccs nil cce nil))
1043 ;; Should we mark empty lines as well ?
1044 (if (or ccs block lines) (setq no-empty nil))
1045 ;; Make sure we have end-markers for BLOCK mode.
1046 (when block (unless ce (setq ce (comment-string-reverse cs))))
1047 ;; If BLOCK is not requested, we don't need CCE.
1048 (unless block (setq cce nil))
1049 ;; Continuation defaults to the same as CS and CE.
1050 (unless ccs (setq ccs cs cce ce))
1052 (save-excursion
1053 (goto-char end)
1054 ;; If the end is not at the end of a line and the comment-end
1055 ;; is implicit (i.e. a newline), explicitly insert a newline.
1056 (unless (or ce-sanitized (eolp)) (insert "\n") (indent-according-to-mode))
1057 (comment-with-narrowing beg end
1058 (let ((min-indent (point-max))
1059 (max-indent 0))
1060 (goto-char (point-min))
1061 ;; Quote any nested comment marker
1062 (comment-quote-nested comment-start comment-end nil)
1064 ;; Loop over all lines to find the needed indentations.
1065 (goto-char (point-min))
1066 (while
1067 (progn
1068 (unless (looking-at "[ \t]*$")
1069 (setq min-indent (min min-indent (current-indentation))))
1070 (end-of-line)
1071 (setq max-indent (max max-indent (current-column)))
1072 (not (or (eobp) (progn (forward-line) nil)))))
1074 (setq max-indent
1075 (+ max-indent (max (length cs) (length ccs))
1076 ;; Inserting ccs can change max-indent by (1- tab-width)
1077 ;; but only if there are TABs in the boxed text, of course.
1078 (if (save-excursion (goto-char beg)
1079 (search-forward "\t" end t))
1080 (1- tab-width) 0)))
1081 (unless indent (setq min-indent 0))
1083 ;; make the leading and trailing lines if requested
1084 (when lines
1085 (let ((csce
1086 (comment-make-extra-lines
1087 cs ce ccs cce min-indent max-indent block)))
1088 (setq cs (car csce))
1089 (setq ce (cdr csce))))
1091 (goto-char (point-min))
1092 ;; Loop over all lines from BEG to END.
1093 (while
1094 (progn
1095 (unless (and no-empty (looking-at "[ \t]*$"))
1096 (move-to-column min-indent t)
1097 (insert cs) (setq cs ccs) ;switch to CCS after the first line
1098 (end-of-line)
1099 (if (eobp) (setq cce ce))
1100 (when cce
1101 (when block (move-to-column max-indent t))
1102 (insert cce)))
1103 (end-of-line)
1104 (not (or (eobp) (progn (forward-line) nil))))))))))
1106 ;;;###autoload
1107 (defun comment-region (beg end &optional arg)
1108 "Comment or uncomment each line in the region.
1109 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
1110 Numeric prefix ARG means use ARG comment characters.
1111 If ARG is negative, delete that many comment characters instead.
1113 The strings used as comment starts are built from `comment-start'
1114 and `comment-padding'; the strings used as comment ends are built
1115 from `comment-end' and `comment-padding'.
1117 By default, the `comment-start' markers are inserted at the
1118 current indentation of the region, and comments are terminated on
1119 each line (even for syntaxes in which newline does not end the
1120 comment and blank lines do not get comments). This can be
1121 changed with `comment-style'."
1122 (interactive "*r\nP")
1123 (comment-normalize-vars)
1124 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
1125 (save-excursion
1126 ;; FIXME: maybe we should call uncomment depending on ARG.
1127 (funcall comment-region-function beg end arg)))
1129 (defun comment-region-default (beg end &optional arg)
1130 (let* ((numarg (prefix-numeric-value arg))
1131 (style (cdr (assoc comment-style comment-styles)))
1132 (lines (nth 2 style))
1133 (block (nth 1 style))
1134 (multi (nth 0 style)))
1136 ;; We use `chars' instead of `syntax' because `\n' might be
1137 ;; of end-comment syntax rather than of whitespace syntax.
1138 ;; sanitize BEG and END
1139 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
1140 (setq beg (max beg (point)))
1141 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
1142 (setq end (min end (point)))
1143 (if (>= beg end) (error "Nothing to comment"))
1145 ;; sanitize LINES
1146 (setq lines
1147 (and
1148 lines ;; multi
1149 (progn (goto-char beg) (beginning-of-line)
1150 (skip-syntax-forward " ")
1151 (>= (point) beg))
1152 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
1153 (<= (point) end))
1154 (or block (not (string= "" comment-end)))
1155 (or block (progn (goto-char beg) (search-forward "\n" end t)))))
1157 ;; don't add end-markers just because the user asked for `block'
1158 (unless (or lines (string= "" comment-end)) (setq block nil))
1160 (cond
1161 ((consp arg) (uncomment-region beg end))
1162 ((< numarg 0) (uncomment-region beg end (- numarg)))
1164 (let ((multi-char (/= (string-match "[ \t]*\\'" comment-start) 1))
1165 indent triple)
1166 (if (eq (nth 3 style) 'multi-char)
1167 (save-excursion
1168 (goto-char beg)
1169 (setq indent multi-char
1170 ;; Triple if we will put the comment starter at the margin
1171 ;; and the first line of the region isn't indented
1172 ;; at least two spaces.
1173 triple (and (not multi-char) (looking-at "\t\\| "))))
1174 (setq indent (nth 3 style)))
1176 ;; In Lisp and similar modes with one-character comment starters,
1177 ;; double it by default if `comment-add' says so.
1178 ;; If it isn't indented, triple it.
1179 (if (and (null arg) (not multi-char))
1180 (setq numarg (* comment-add (if triple 2 1)))
1181 (setq numarg (1- (prefix-numeric-value arg))))
1183 (comment-region-internal
1184 beg end
1185 (let ((s (comment-padright comment-start numarg)))
1186 (if (string-match comment-start-skip s) s
1187 (comment-padright comment-start)))
1188 (let ((s (comment-padleft comment-end numarg)))
1189 (and s (if (string-match comment-end-skip s) s
1190 (comment-padright comment-end))))
1191 (if multi (comment-padright comment-continue numarg))
1192 (if multi
1193 (comment-padleft (comment-string-reverse comment-continue) numarg))
1194 block
1195 lines
1196 indent))))))
1198 ;;;###autoload
1199 (defun comment-box (beg end &optional arg)
1200 "Comment out the BEG .. END region, putting it inside a box.
1201 The numeric prefix ARG specifies how many characters to add to begin- and
1202 end- comment markers additionally to what `comment-add' already specifies."
1203 (interactive "*r\np")
1204 (comment-normalize-vars)
1205 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
1206 'box-multi 'box)))
1207 (comment-region beg end (+ comment-add arg))))
1209 (defun comment-only-p (beg end)
1210 "Return non-nil if the text between BEG and END is all comments."
1211 (save-excursion
1212 (goto-char beg)
1213 (comment-forward (point-max))
1214 (<= end (point))))
1216 ;;;###autoload
1217 (defun comment-or-uncomment-region (beg end &optional arg)
1218 "Call `comment-region', unless the region only consists of comments,
1219 in which case call `uncomment-region'. If a prefix arg is given, it
1220 is passed on to the respective function."
1221 (interactive "*r\nP")
1222 (comment-normalize-vars)
1223 (funcall (if (comment-only-p beg end)
1224 'uncomment-region 'comment-region)
1225 beg end arg))
1227 ;;;###autoload
1228 (defun comment-dwim (arg)
1229 "Call the comment command you want (Do What I Mean).
1230 If the region is active and `transient-mark-mode' is on, call
1231 `comment-region' (unless it only consists of comments, in which
1232 case it calls `uncomment-region').
1233 Else, if the current line is empty, call `comment-insert-comment-function'
1234 if it is defined, otherwise insert a comment and indent it.
1235 Else if a prefix ARG is specified, call `comment-kill'.
1236 Else, call `comment-indent'.
1237 You can configure `comment-style' to change the way regions are commented."
1238 (interactive "*P")
1239 (comment-normalize-vars)
1240 (if (and mark-active transient-mark-mode)
1241 (comment-or-uncomment-region (region-beginning) (region-end) arg)
1242 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
1243 ;; FIXME: If there's no comment to kill on this line and ARG is
1244 ;; specified, calling comment-kill is not very clever.
1245 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
1246 ;; Inserting a comment on a blank line. comment-indent calls
1247 ;; c-i-c-f if needed in the non-blank case.
1248 (if comment-insert-comment-function
1249 (funcall comment-insert-comment-function)
1250 (let ((add (comment-add arg)))
1251 ;; Some modes insist on keeping column 0 comment in column 0
1252 ;; so we need to move away from it before inserting the comment.
1253 (indent-according-to-mode)
1254 (insert (comment-padright comment-start add))
1255 (save-excursion
1256 (unless (string= "" comment-end)
1257 (insert (comment-padleft comment-end add)))
1258 (indent-according-to-mode)))))))
1260 ;;;###autoload
1261 (defcustom comment-auto-fill-only-comments nil
1262 "Non-nil means to only auto-fill inside comments.
1263 This has no effect in modes that do not define a comment syntax."
1264 :type 'boolean
1265 :group 'comment)
1267 (defun comment-valid-prefix-p (prefix compos)
1268 "Check that the adaptive fill prefix is consistent with the context.
1269 PREFIX is the prefix (presumably guessed by `adaptive-fill-mode').
1270 COMPOS is the position of the beginning of the comment we're in, or nil
1271 if we're not inside a comment."
1272 ;; This consistency checking is mostly needed to workaround the limitation
1273 ;; of auto-fill-mode whose paragraph-determination doesn't pay attention
1274 ;; to comment boundaries.
1275 (if (null compos)
1276 ;; We're not inside a comment: the prefix shouldn't match
1277 ;; a comment-starter.
1278 (not (and comment-start comment-start-skip
1279 (string-match comment-start-skip prefix)))
1281 ;; Accept any prefix if the current comment is not EOL-terminated.
1282 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1283 ;; Accept any prefix that starts with the same comment-start marker
1284 ;; as the current one.
1285 (when (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1286 prefix)
1287 (let ((prefix-com (comment-string-strip (match-string 0 prefix) nil t)))
1288 (string-match "\\`[ \t]*" prefix-com)
1289 (let* ((prefix-space (match-string 0 prefix-com))
1290 (prefix-indent (string-width prefix-space))
1291 (prefix-comstart (substring prefix-com (match-end 0))))
1292 (save-excursion
1293 (goto-char compos)
1294 ;; The comstart marker is the same.
1295 (and (looking-at (regexp-quote prefix-comstart))
1296 ;; The indentation as well.
1297 (or (= prefix-indent
1298 (- (current-column) (current-left-margin)))
1299 ;; Check the indentation in two different ways, just
1300 ;; to try and avoid most of the potential funny cases.
1301 (equal prefix-space
1302 (buffer-substring (point)
1303 (progn (move-to-left-margin)
1304 (point)))))))))))))
1307 ;;;###autoload
1308 (defun comment-indent-new-line (&optional soft)
1309 "Break line at point and indent, continuing comment if within one.
1310 This indents the body of the continued comment
1311 under the previous comment line.
1313 This command is intended for styles where you write a comment per line,
1314 starting a new comment (and terminating it if necessary) on each line.
1315 If you want to continue one comment across several lines, use \\[newline-and-indent].
1317 If a fill column is specified, it overrides the use of the comment column
1318 or comment indentation.
1320 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1321 unless optional argument SOFT is non-nil."
1322 (interactive)
1323 (comment-normalize-vars t)
1324 (let (compos comin)
1325 ;; If we are not inside a comment and we only auto-fill comments,
1326 ;; don't do anything (unless no comment syntax is defined).
1327 (unless (and comment-start
1328 comment-auto-fill-only-comments
1329 (not (called-interactively-p 'interactive))
1330 (not (save-excursion
1331 (prog1 (setq compos (comment-beginning))
1332 (setq comin (point))))))
1334 ;; Now we know we should auto-fill.
1335 ;; Insert the newline before removing empty space so that markers
1336 ;; get preserved better.
1337 (if soft (insert-and-inherit ?\n) (newline 1))
1338 (save-excursion (forward-char -1) (delete-horizontal-space))
1339 (delete-horizontal-space)
1341 (if (and fill-prefix (not adaptive-fill-mode))
1342 ;; Blindly trust a non-adaptive fill-prefix.
1343 (progn
1344 (indent-to-left-margin)
1345 (insert-before-markers-and-inherit fill-prefix))
1347 ;; If necessary check whether we're inside a comment.
1348 (unless (or compos (null comment-start))
1349 (save-excursion
1350 (backward-char)
1351 (setq compos (comment-beginning))
1352 (setq comin (point))))
1354 (cond
1355 ;; If there's an adaptive prefix, use it unless we're inside
1356 ;; a comment and the prefix is not a comment starter.
1357 ((and fill-prefix
1358 (comment-valid-prefix-p fill-prefix compos))
1359 (indent-to-left-margin)
1360 (insert-and-inherit fill-prefix))
1361 ;; If we're not inside a comment, just try to indent.
1362 ((not compos) (indent-according-to-mode))
1364 (let* ((comment-column
1365 ;; The continuation indentation should be somewhere between
1366 ;; the current line's indentation (plus 2 for good measure)
1367 ;; and the current comment's indentation, with a preference
1368 ;; for comment-column.
1369 (save-excursion
1370 ;; FIXME: use prev line's info rather than first line's.
1371 (goto-char compos)
1372 (min (current-column) (max comment-column
1373 (+ 2 (current-indentation))))))
1374 (comstart (buffer-substring compos comin))
1375 (normalp
1376 (string-match (regexp-quote (comment-string-strip
1377 comment-start t t))
1378 comstart))
1379 (comment-end
1380 (if normalp comment-end
1381 ;; The comment starter is not the normal comment-start
1382 ;; so we can't just use comment-end.
1383 (save-excursion
1384 (goto-char compos)
1385 (if (not (comment-forward)) comment-end
1386 (comment-string-strip
1387 (buffer-substring
1388 (save-excursion (comment-enter-backward) (point))
1389 (point))
1390 nil t)))))
1391 (comment-start comstart)
1392 (continuep (or comment-multi-line
1393 (cadr (assoc comment-style comment-styles))))
1394 ;; Force comment-continue to be recreated from comment-start.
1395 ;; FIXME: wrong if comment-continue was set explicitly!
1396 ;; FIXME: use prev line's continuation if available.
1397 (comment-continue nil))
1398 (if (and comment-multi-line (> (length comment-end) 0))
1399 (indent-according-to-mode)
1400 (insert-and-inherit ?\n)
1401 (forward-char -1)
1402 (comment-indent continuep)
1403 (save-excursion
1404 (let ((pt (point)))
1405 (end-of-line)
1406 (let ((comend (buffer-substring pt (point))))
1407 ;; The 1+ is to make sure we delete the \n inserted above.
1408 (delete-region pt (1+ (point)))
1409 (end-of-line 0)
1410 (insert comend))))))))))))
1412 (provide 'newcomment)
1414 ;;; newcomment.el ends here