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