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