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