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