Use make-temp-file in rst.el (Bug#7646).
[emacs.git] / lisp / newcomment.el
blob1e40317c9a148e1f5e038ee0cfef739301c33f94
1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: code extracted from Emacs-20's simple.el
7 ;; Maintainer: Stefan Monnier <monnier@iro.umontreal.ca>
8 ;; Keywords: comment uncomment
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 up 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 (defconst comment-styles
189 '((plain . (nil nil nil nil))
190 (indent . (nil nil nil t))
191 (indent-or-triple
192 . (nil nil nil multi-char))
193 (aligned . (nil t nil t))
194 (multi-line . (t nil nil t))
195 (extra-line . (t nil t t))
196 (box . (nil t t t))
197 (box-multi . (t t t t)))
198 "Comment region styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
199 STYLE should be a mnemonic symbol.
200 MULTI specifies that comments are allowed to span multiple lines.
201 ALIGN specifies that the `comment-end' markers should be aligned.
202 EXTRA specifies that an extra line should be used before and after the
203 region to comment (to put the `comment-end' and `comment-start').
204 INDENT specifies that the `comment-start' markers should not be put at the
205 left margin but at the current indentation of the region to comment.
206 If INDENT is `multi-char', that means indent multi-character
207 comment starters, but not one-character comment starters.")
209 ;;;###autoload
210 (defcustom comment-style 'indent
211 "Style to be used for `comment-region'.
212 See `comment-styles' for a list of available styles."
213 :type (if (boundp 'comment-styles)
214 `(choice ,@(mapcar (lambda (s) `(const ,(car s)))
215 comment-styles))
216 'symbol)
217 :version "23.1"
218 :group 'comment)
220 ;;;###autoload
221 (defcustom comment-padding (purecopy " ")
222 "Padding string that `comment-region' puts between comment chars and text.
223 Can also be an integer which will be automatically turned into a string
224 of the corresponding number of spaces.
226 Extra spacing between the comment characters and the comment text
227 makes the comment easier to read. Default is 1. nil means 0."
228 :type '(choice string integer (const nil))
229 :group 'comment)
231 ;;;###autoload
232 (defcustom comment-multi-line nil
233 "Non-nil means `comment-indent-new-line' continues comments.
234 That is, it inserts no new terminator or starter.
235 This affects `auto-fill-mode', which is the main reason to
236 customize this variable.
238 It also affects \\[indent-new-comment-line]. However, if you want this
239 behavior for explicit filling, you might as well use \\[newline-and-indent]."
240 :type 'boolean
241 :group 'comment)
243 (defcustom comment-empty-lines nil
244 "If nil, `comment-region' does not comment out empty lines.
245 If t, it always comments out empty lines.
246 If `eol' it only comments out empty lines if comments are
247 terminated by the end of line (i.e. `comment-end' is empty)."
248 :type '(choice (const :tag "Never" nil)
249 (const :tag "Always" t)
250 (const :tag "EOl-terminated" 'eol))
251 :group 'comment)
253 ;;;;
254 ;;;; Helpers
255 ;;;;
257 (defun comment-string-strip (str beforep afterp)
258 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
259 (string-match (concat "\\`" (if beforep "\\s-*")
260 "\\(.*?\\)" (if afterp "\\s-*\n?")
261 "\\'") str)
262 (match-string 1 str))
264 (defun comment-string-reverse (s)
265 "Return the mirror image of string S, without any trailing space."
266 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
268 ;;;###autoload
269 (defun comment-normalize-vars (&optional noerror)
270 "Check and setup the variables needed by other commenting functions.
271 Functions autoloaded from newcomment.el, being entry points, should call
272 this function before any other, so the rest of the code can assume that
273 the variables are properly set."
274 (unless (and (not comment-start) noerror)
275 (unless comment-start
276 (let ((cs (read-string "No comment syntax is defined. Use: ")))
277 (if (zerop (length cs))
278 (error "No comment syntax defined")
279 (set (make-local-variable 'comment-start) cs))))
280 ;; comment-use-syntax
281 (when (eq comment-use-syntax 'undecided)
282 (set (make-local-variable 'comment-use-syntax)
283 (let ((st (syntax-table))
284 (cs comment-start)
285 (ce (if (string= "" comment-end) "\n" comment-end)))
286 ;; Try to skip over a comment using forward-comment
287 ;; to see if the syntax tables properly recognize it.
288 (with-temp-buffer
289 (set-syntax-table st)
290 (insert cs " hello " ce)
291 (goto-char (point-min))
292 (and (forward-comment 1) (eobp))))))
293 ;; comment-padding
294 (unless comment-padding (setq comment-padding 0))
295 (when (integerp comment-padding)
296 (setq comment-padding (make-string comment-padding ? )))
297 ;; comment markers
298 ;;(setq comment-start (comment-string-strip comment-start t nil))
299 ;;(setq comment-end (comment-string-strip comment-end nil t))
300 ;; comment-continue
301 (unless (or comment-continue (string= comment-end ""))
302 (set (make-local-variable 'comment-continue)
303 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
304 (substring comment-start 1)))
305 ;; Hasn't been necessary yet.
306 ;; (unless (string-match comment-start-skip comment-continue)
307 ;; (kill-local-variable 'comment-continue))
309 ;; comment-skip regexps
310 (unless (and comment-start-skip
311 ;; In case comment-start has changed since last time.
312 (string-match comment-start-skip comment-start))
313 (set (make-local-variable 'comment-start-skip)
314 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
315 (regexp-quote (comment-string-strip comment-start t t))
316 ;; Let's not allow any \s- but only [ \t] since \n
317 ;; might be both a comment-end marker and \s-.
318 "+\\)[ \t]*")))
319 (unless (and comment-end-skip
320 ;; In case comment-end has changed since last time.
321 (string-match comment-end-skip
322 (if (string= "" comment-end) "\n" comment-end)))
323 (let ((ce (if (string= "" comment-end) "\n"
324 (comment-string-strip comment-end t t))))
325 (set (make-local-variable 'comment-end-skip)
326 ;; We use [ \t] rather than \s- because we don't want to
327 ;; remove ^L in C mode when uncommenting.
328 (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
329 "\\|" (regexp-quote (substring ce 0 1))
330 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
331 (regexp-quote (substring ce 1))
332 "\\)"))))))
334 (defun comment-quote-re (str unp)
335 (concat (regexp-quote (substring str 0 1))
336 "\\\\" (if unp "+" "*")
337 (regexp-quote (substring str 1))))
339 (defun comment-quote-nested (cs ce unp)
340 "Quote or unquote nested comments.
341 If UNP is non-nil, unquote nested comment markers."
342 (setq cs (comment-string-strip cs t t))
343 (setq ce (comment-string-strip ce t t))
344 (when (and comment-quote-nested (> (length ce) 0))
345 (let ((re (concat (comment-quote-re ce unp)
346 "\\|" (comment-quote-re cs unp))))
347 (goto-char (point-min))
348 (while (re-search-forward re nil t)
349 (goto-char (match-beginning 0))
350 (forward-char 1)
351 (if unp (delete-char 1) (insert "\\"))
352 (when (= (length ce) 1)
353 ;; If the comment-end is a single char, adding a \ after that
354 ;; "first" char won't deactivate it, so we turn such a CE
355 ;; into !CS. I.e. for pascal, we turn } into !{
356 (if (not unp)
357 (when (string= (match-string 0) ce)
358 (replace-match (concat "!" cs) t t))
359 (when (and (< (point-min) (match-beginning 0))
360 (string= (buffer-substring (1- (match-beginning 0))
361 (1- (match-end 0)))
362 (concat "!" cs)))
363 (backward-char 2)
364 (delete-char (- (match-end 0) (match-beginning 0)))
365 (insert ce))))))))
367 ;;;;
368 ;;;; Navigation
369 ;;;;
371 (defvar comment-use-global-state nil
372 "Non-nil means that the global syntactic context is used.
373 More specifically, it means that `syntax-ppss' is used to find out whether
374 point is within a string or not. Major modes whose syntax is faithfully
375 described by the syntax-tables can set this to non-nil so comment markers
376 in strings will not confuse Emacs.")
378 (defun comment-search-forward (limit &optional noerror)
379 "Find a comment start between point and LIMIT.
380 Moves point to inside the comment and returns the position of the
381 comment-starter. If no comment is found, moves point to LIMIT
382 and raises an error or returns nil if NOERROR is non-nil."
383 (if (not comment-use-syntax)
384 (if (re-search-forward comment-start-skip limit noerror)
385 (or (match-end 1) (match-beginning 0))
386 (goto-char limit)
387 (unless noerror (error "No comment")))
388 (let* ((pt (point))
389 ;; Assume (at first) that pt is outside of any string.
390 (s (parse-partial-sexp pt (or limit (point-max)) nil nil
391 (if comment-use-global-state (syntax-ppss pt))
392 t)))
393 (when (and (nth 8 s) (nth 3 s) (not comment-use-global-state))
394 ;; The search ended at eol inside a string. Try to see if it
395 ;; works better when we assume that pt is inside a string.
396 (setq s (parse-partial-sexp
397 pt (or limit (point-max)) nil nil
398 (list nil nil nil (nth 3 s) nil nil nil nil)
399 t)))
400 (if (or (not (and (nth 8 s) (not (nth 3 s))))
401 ;; Make sure the comment starts after PT.
402 (< (nth 8 s) pt))
403 (unless noerror (error "No comment"))
404 ;; We found the comment.
405 (let ((pos (point))
406 (start (nth 8 s))
407 (bol (line-beginning-position))
408 (end nil))
409 (while (and (null end) (>= (point) bol))
410 (if (looking-at comment-start-skip)
411 (setq end (min (or limit (point-max)) (match-end 0)))
412 (backward-char)))
413 (goto-char (or end pos))
414 start)))))
416 (defun comment-search-backward (&optional limit noerror)
417 "Find a comment start between LIMIT and point.
418 Moves point to inside the comment and returns the position of the
419 comment-starter. If no comment is found, moves point to LIMIT
420 and raises an error or returns nil if NOERROR is non-nil."
421 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
422 ;; stop there. This can be rather bad in general, but since
423 ;; comment-search-backward is only used to find the comment-column (in
424 ;; comment-set-column) and to find the comment-start string (via
425 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
426 (if (not (re-search-backward comment-start-skip limit t))
427 (unless noerror (error "No comment"))
428 (beginning-of-line)
429 (let* ((end (match-end 0))
430 (cs (comment-search-forward end t))
431 (pt (point)))
432 (if (not cs)
433 (progn (beginning-of-line)
434 (comment-search-backward limit noerror))
435 (while (progn (goto-char cs)
436 (comment-forward)
437 (and (< (point) end)
438 (setq cs (comment-search-forward end t))))
439 (setq pt (point)))
440 (goto-char pt)
441 cs))))
443 (defun comment-beginning ()
444 "Find the beginning of the enclosing comment.
445 Returns nil if not inside a comment, else moves point and returns
446 the same as `comment-search-backward'."
447 ;; HACK ATTACK!
448 ;; We should really test `in-string-p' but that can be expensive.
449 (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
450 (let ((pt (point))
451 (cs (comment-search-backward nil t)))
452 (when cs
453 (if (save-excursion
454 (goto-char cs)
455 (and
456 ;; For modes where comment-start and comment-end are the same,
457 ;; the search above may have found a `ce' rather than a `cs'.
458 (or (if comment-end-skip (not (looking-at comment-end-skip)))
459 ;; Maybe font-lock knows that it's a `cs'?
460 (eq (get-text-property (match-end 0) 'face)
461 'font-lock-comment-face)
462 (unless (eq (get-text-property (point) 'face)
463 'font-lock-comment-face)
464 ;; Let's assume it's a `cs' if we're on the same line.
465 (>= (line-end-position) pt)))
466 ;; Make sure that PT is not past the end of the comment.
467 (if (comment-forward 1) (> (point) pt) (eobp))))
469 (goto-char pt)
470 nil)))))
472 (defun comment-forward (&optional n)
473 "Skip forward over N comments.
474 Just like `forward-comment' but only for positive N
475 and can use regexps instead of syntax."
476 (setq n (or n 1))
477 (if (< n 0) (error "No comment-backward")
478 (if comment-use-syntax (forward-comment n)
479 (while (> n 0)
480 (setq n
481 (if (or (forward-comment 1)
482 (and (looking-at comment-start-skip)
483 (goto-char (match-end 0))
484 (re-search-forward comment-end-skip nil 'move)))
485 (1- n) -1)))
486 (= n 0))))
488 (defun comment-enter-backward ()
489 "Move from the end of a comment to the end of its content.
490 Point is assumed to be just at the end of a comment."
491 (if (bolp)
492 ;; comment-end = ""
493 (progn (backward-char) (skip-syntax-backward " "))
494 (cond
495 ((save-excursion
496 (save-restriction
497 (narrow-to-region (line-beginning-position) (point))
498 (goto-char (point-min))
499 (re-search-forward (concat comment-end-skip "\\'") nil t)))
500 (goto-char (match-beginning 0)))
501 ;; comment-end-skip not found probably because it was not set
502 ;; right. Since \\s> should catch the single-char case, let's
503 ;; check that we're looking at a two-char comment ender.
504 ((not (or (<= (- (point-max) (line-beginning-position)) 1)
505 (zerop (logand (car (syntax-after (- (point) 1)))
506 ;; Here we take advantage of the fact that
507 ;; the syntax class " " is encoded to 0,
508 ;; so " 4" gives us just the 4 bit.
509 (car (string-to-syntax " 4"))))
510 (zerop (logand (car (syntax-after (- (point) 2)))
511 (car (string-to-syntax " 3"))))))
512 (backward-char 2)
513 (skip-chars-backward (string (char-after)))
514 (skip-syntax-backward " "))
515 ;; No clue what's going on: maybe we're really not right after the
516 ;; end of a comment. Maybe we're at the "end" because of EOB rather
517 ;; than because of a marker.
518 (t (skip-syntax-backward " ")))))
520 ;;;;
521 ;;;; Commands
522 ;;;;
524 ;;;###autoload
525 (defun comment-indent-default ()
526 "Default for `comment-indent-function'."
527 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
528 (or (match-end 1) (/= (current-column) (current-indentation))))
530 (when (or (/= (current-column) (current-indentation))
531 (and (> comment-add 0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
532 comment-column)))
534 (defun comment-choose-indent (&optional indent)
535 "Choose the indentation to use for a right-hand-side comment.
536 The criteria are (in this order):
537 - try to keep the comment's text within `comment-fill-column'.
538 - try to align with surrounding comments.
539 - prefer INDENT (or `comment-column' if nil).
540 Point is expected to be at the start of the comment."
541 (unless indent (setq indent comment-column))
542 ;; Avoid moving comments past the fill-column.
543 (let ((max (+ (current-column)
544 (- (or comment-fill-column fill-column)
545 (save-excursion (end-of-line) (current-column)))))
546 (other nil)
547 (min (save-excursion (skip-chars-backward " \t")
548 (1+ (current-column)))))
549 ;; Fix up the range.
550 (if (< max min) (setq max min))
551 ;; Don't move past the fill column.
552 (if (<= max indent) (setq indent max))
553 ;; We can choose anywhere between min..max.
554 ;; Let's try to align to a comment on the previous line.
555 (save-excursion
556 (when (and (zerop (forward-line -1))
557 (setq other (comment-search-forward
558 (line-end-position) t)))
559 (goto-char other) (setq other (current-column))))
560 (if (and other (<= other max) (>= other min))
561 ;; There is a comment and it's in the range: bingo!
562 other
563 ;; Can't align to a previous comment: let's try to align to comments
564 ;; on the following lines, then. These have not been re-indented yet,
565 ;; so we can't directly align ourselves with them. All we do is to try
566 ;; and choose an indentation point with which they will be able to
567 ;; align themselves.
568 (save-excursion
569 (while (and (zerop (forward-line 1))
570 (setq other (comment-search-forward
571 (line-end-position) t)))
572 (goto-char other)
573 (let ((omax (+ (current-column)
574 (- (or comment-fill-column fill-column)
575 (save-excursion (end-of-line) (current-column)))))
576 (omin (save-excursion (skip-chars-backward " \t")
577 (1+ (current-column)))))
578 (if (and (>= omax min) (<= omin max))
579 (progn (setq min (max omin min))
580 (setq max (min omax max)))
581 ;; Can't align with this anyway, so exit the loop.
582 (goto-char (point-max))))))
583 ;; Return the closest point to indent within min..max.
584 (max min (min max indent)))))
586 ;;;###autoload
587 (defun comment-indent (&optional continue)
588 "Indent this line's comment to `comment-column', or insert an empty comment.
589 If CONTINUE is non-nil, use the `comment-continue' markers if any."
590 (interactive "*")
591 (comment-normalize-vars)
592 (let* ((empty (save-excursion (beginning-of-line)
593 (looking-at "[ \t]*$")))
594 (starter (or (and continue comment-continue)
595 (and empty block-comment-start) comment-start))
596 (ender (or (and continue comment-continue "")
597 (and empty block-comment-end) comment-end)))
598 (unless starter (error "No comment syntax defined"))
599 (beginning-of-line)
600 (let* ((eolpos (line-end-position))
601 (begpos (comment-search-forward eolpos t))
602 cpos indent)
603 (if (and comment-insert-comment-function (not begpos))
604 ;; If no comment and c-i-c-f is set, let it do everything.
605 (funcall comment-insert-comment-function)
606 ;; An existing comment?
607 (if begpos
608 (progn
609 (if (and (not (looking-at "[\t\n ]"))
610 (looking-at comment-end-skip))
611 ;; The comment is empty and we have skipped all its space
612 ;; and landed right before the comment-ender:
613 ;; Go back to the middle of the space.
614 (forward-char (/ (skip-chars-backward " \t") -2)))
615 (setq cpos (point-marker)))
616 ;; If none, insert one.
617 (save-excursion
618 ;; Some `comment-indent-function's insist on not moving
619 ;; comments that are in column 0, so we first go to the
620 ;; likely target column.
621 (indent-to comment-column)
622 ;; Ensure there's a space before the comment for things
623 ;; like sh where it matters (as well as being neater).
624 (unless (memq (char-before) '(nil ?\n ?\t ?\s))
625 (insert ?\s))
626 (setq begpos (point))
627 (insert starter)
628 (setq cpos (point-marker))
629 (insert ender)))
630 (goto-char begpos)
631 ;; Compute desired indent.
632 (setq indent (save-excursion (funcall comment-indent-function)))
633 ;; If `indent' is nil and there's code before the comment, we can't
634 ;; use `indent-according-to-mode', so we default to comment-column.
635 (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
636 (setq indent comment-column))
637 (if (not indent)
638 ;; comment-indent-function refuses: delegate to line-indent.
639 (indent-according-to-mode)
640 ;; If the comment is at the right of code, adjust the indentation.
641 (unless (save-excursion (skip-chars-backward " \t") (bolp))
642 (setq indent (comment-choose-indent indent)))
643 ;; Update INDENT to leave at least one space
644 ;; after other nonwhite text on the line.
645 (save-excursion
646 (skip-chars-backward " \t")
647 (unless (bolp)
648 (setq indent (max indent (1+ (current-column))))))
649 ;; If that's different from comment's current position, change it.
650 (unless (= (current-column) indent)
651 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
652 (indent-to indent)))
653 (goto-char cpos)
654 (set-marker cpos nil)))))
656 ;;;###autoload
657 (defun comment-set-column (arg)
658 "Set the comment column based on point.
659 With no ARG, set the comment column to the current column.
660 With just minus as arg, kill any comment on this line.
661 With any other arg, set comment column to indentation of the previous comment
662 and then align or create a comment on this line at that column."
663 (interactive "P")
664 (cond
665 ((eq arg '-) (comment-kill nil))
666 (arg
667 (comment-normalize-vars)
668 (save-excursion
669 (beginning-of-line)
670 (comment-search-backward)
671 (beginning-of-line)
672 (goto-char (comment-search-forward (line-end-position)))
673 (setq comment-column (current-column))
674 (message "Comment column set to %d" comment-column))
675 (comment-indent))
676 (t (setq comment-column (current-column))
677 (message "Comment column set to %d" comment-column))))
679 ;;;###autoload
680 (defun comment-kill (arg)
681 "Kill the first comment on this line, if any.
682 With prefix ARG, kill comments on that many lines starting with this one."
683 (interactive "P")
684 (comment-normalize-vars)
685 (dotimes (_ (prefix-numeric-value arg))
686 (save-excursion
687 (beginning-of-line)
688 (let ((cs (comment-search-forward (line-end-position) t)))
689 (when cs
690 (goto-char cs)
691 (skip-syntax-backward " ")
692 (setq cs (point))
693 (comment-forward)
694 (kill-region cs (if (bolp) (1- (point)) (point)))
695 (indent-according-to-mode))))
696 (if arg (forward-line 1))))
698 (defun comment-padright (str &optional n)
699 "Construct a string composed of STR plus `comment-padding'.
700 It also adds N copies of the last non-whitespace chars of STR.
701 If STR already contains padding, the corresponding amount is
702 ignored from `comment-padding'.
703 N defaults to 0.
704 If N is `re', a regexp is returned instead, that would match
705 the string for any N."
706 (setq n (or n 0))
707 (when (and (stringp str) (not (string= "" str)))
708 ;; Separate the actual string from any leading/trailing padding
709 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
710 (let ((s (match-string 1 str)) ;actual string
711 (lpad (substring str 0 (match-beginning 1))) ;left padding
712 (rpad (concat (substring str (match-end 1)) ;original right padding
713 (substring comment-padding ;additional right padding
714 (min (- (match-end 0) (match-end 1))
715 (length comment-padding)))))
716 ;; We can only duplicate C if the comment-end has multiple chars
717 ;; or if comments can be nested, else the comment-end `}' would
718 ;; be turned into `}}}' where only the first ends the comment
719 ;; and the rest becomes bogus junk.
720 (multi (not (and comment-quote-nested
721 ;; comment-end is a single char
722 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
723 (if (not (symbolp n))
724 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
725 ;; construct a regexp that would match anything from just S
726 ;; to any possible output of this function for any N.
727 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
728 lpad "") ;padding is not required
729 (regexp-quote s)
730 (when multi "+") ;the last char of S might be repeated
731 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
732 rpad "")))))) ;padding is not required
734 (defun comment-padleft (str &optional n)
735 "Construct a string composed of `comment-padding' plus STR.
736 It also adds N copies of the first non-whitespace chars of STR.
737 If STR already contains padding, the corresponding amount is
738 ignored from `comment-padding'.
739 N defaults to 0.
740 If N is `re', a regexp is returned instead, that would match
741 the string for any N."
742 (setq n (or n 0))
743 (when (and (stringp str) (not (string= "" str)))
744 ;; Only separate the left pad because we assume there is no right pad.
745 (string-match "\\`\\s-*" str)
746 (let ((s (substring str (match-end 0)))
747 (pad (concat (substring comment-padding
748 (min (- (match-end 0) (match-beginning 0))
749 (length comment-padding)))
750 (match-string 0 str)))
751 (c (aref str (match-end 0))) ;the first non-space char of STR
752 ;; We can only duplicate C if the comment-end has multiple chars
753 ;; or if comments can be nested, else the comment-end `}' would
754 ;; be turned into `}}}' where only the first ends the comment
755 ;; and the rest becomes bogus junk.
756 (multi (not (and comment-quote-nested
757 ;; comment-end is a single char
758 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
759 (if (not (symbolp n))
760 (concat pad (when multi (make-string n c)) s)
761 ;; Construct a regexp that would match anything from just S
762 ;; to any possible output of this function for any N.
763 ;; We match any number of leading spaces because this regexp will
764 ;; be used for uncommenting where we might want to remove
765 ;; uncomment markers with arbitrary leading space (because
766 ;; they were aligned).
767 (concat "\\s-*"
768 (if multi (concat (regexp-quote (string c)) "*"))
769 (regexp-quote s))))))
771 ;;;###autoload
772 (defun uncomment-region (beg end &optional arg)
773 "Uncomment each line in the BEG .. END region.
774 The numeric prefix ARG can specify a number of chars to remove from the
775 comment markers."
776 (interactive "*r\nP")
777 (comment-normalize-vars)
778 (when (> beg end) (setq beg (prog1 end (setq end beg))))
779 ;; Bind `comment-use-global-state' to nil. While uncommenting a region
780 ;; (which works a line at a time), a comment can appear to be
781 ;; included in a mult-line string, but it is actually not.
782 (let ((comment-use-global-state nil))
783 (save-excursion
784 (funcall uncomment-region-function beg end arg))))
786 (defun uncomment-region-default (beg end &optional arg)
787 "Uncomment each line in the BEG .. END region.
788 The numeric prefix ARG can specify a number of chars to remove from the
789 comment markers."
790 (goto-char beg)
791 (setq end (copy-marker end))
792 (let* ((numarg (prefix-numeric-value arg))
793 (ccs comment-continue)
794 (srei (comment-padright ccs 're))
795 (csre (comment-padright comment-start 're))
796 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
797 spt)
798 (while (and (< (point) end)
799 (setq spt (comment-search-forward end t)))
800 (let ((ipt (point))
801 ;; Find the end of the comment.
802 (ept (progn
803 (goto-char spt)
804 (unless (or (comment-forward)
805 ;; Allow non-terminated comments.
806 (eobp))
807 (error "Can't find the comment end"))
808 (point)))
809 (box nil)
810 (box-equal nil)) ;Whether we might be using `=' for boxes.
811 (save-restriction
812 (narrow-to-region spt ept)
814 ;; Remove the comment-start.
815 (goto-char ipt)
816 (skip-syntax-backward " ")
817 ;; A box-comment starts with a looong comment-start marker.
818 (when (and (or (and (= (- (point) (point-min)) 1)
819 (setq box-equal t)
820 (looking-at "=\\{7\\}")
821 (not (eq (char-before (point-max)) ?\n))
822 (skip-chars-forward "="))
823 (> (- (point) (point-min) (length comment-start)) 7))
824 (> (count-lines (point-min) (point-max)) 2))
825 (setq box t))
826 ;; Skip the padding. Padding can come from comment-padding and/or
827 ;; from comment-start, so we first check comment-start.
828 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
829 (looking-at (regexp-quote comment-padding)))
830 (goto-char (match-end 0)))
831 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
832 (goto-char (match-end 0)))
833 (if (null arg) (delete-region (point-min) (point))
834 (skip-syntax-backward " ")
835 (delete-char (- numarg))
836 (unless (or (bobp)
837 (save-excursion (goto-char (point-min))
838 (looking-at comment-start-skip)))
839 ;; If there's something left but it doesn't look like
840 ;; a comment-start any more, just remove it.
841 (delete-region (point-min) (point))))
843 ;; Remove the end-comment (and leading padding and such).
844 (goto-char (point-max)) (comment-enter-backward)
845 ;; Check for special `=' used sometimes in comment-box.
846 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
847 (let ((pos (point)))
848 ;; skip `=' but only if there are at least 7.
849 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
850 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
851 (when (and (bolp) (not (bobp))) (backward-char))
852 (if (null arg) (delete-region (point) (point-max))
853 (skip-syntax-forward " ")
854 (delete-char numarg)
855 (unless (or (eobp) (looking-at comment-end-skip))
856 ;; If there's something left but it doesn't look like
857 ;; a comment-end any more, just remove it.
858 (delete-region (point) (point-max)))))
860 ;; Unquote any nested end-comment.
861 (comment-quote-nested comment-start comment-end t)
863 ;; Eliminate continuation markers as well.
864 (when sre
865 (let* ((cce (comment-string-reverse (or comment-continue
866 comment-start)))
867 (erei (and box (comment-padleft cce 're)))
868 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
869 (goto-char (point-min))
870 (while (progn
871 (if (and ere (re-search-forward
872 ere (line-end-position) t))
873 (replace-match "" t t nil (if (match-end 2) 2 1))
874 (setq ere nil))
875 (forward-line 1)
876 (re-search-forward sre (line-end-position) t))
877 (replace-match "" t t nil (if (match-end 2) 2 1)))))
878 ;; Go to the end for the next comment.
879 (goto-char (point-max))))))
880 (set-marker end nil))
882 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
883 "Make the leading and trailing extra lines.
884 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
885 (let ((eindent 0))
886 (if (not block)
887 ;; Try to match CS and CE's content so they align aesthetically.
888 (progn
889 (setq ce (comment-string-strip ce t t))
890 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
891 (setq eindent
892 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
893 0))))
894 ;; box comment
895 (let* ((width (- max-indent min-indent))
896 (s (concat cs "a=m" cce))
897 (e (concat ccs "a=m" ce))
898 (c (if (string-match ".*\\S-\\S-" cs)
899 (aref cs (1- (match-end 0)))
900 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
901 (aref cs (1- (match-end 0))) ?=)))
902 (re "\\s-*a=m\\s-*")
903 (_ (string-match re s))
904 (lcs (length cs))
905 (fill
906 (make-string (+ width (- (match-end 0)
907 (match-beginning 0) lcs 3)) c)))
908 (setq cs (replace-match fill t t s))
909 (when (and (not (string-match comment-start-skip cs))
910 (string-match "a=m" s))
911 ;; The whitespace around CS cannot be ignored: put it back.
912 (setq re "a=m")
913 (setq fill (make-string (- width lcs) c))
914 (setq cs (replace-match fill t t s)))
915 (string-match re e)
916 (setq ce (replace-match fill t t e))))
917 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
918 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
920 (defmacro comment-with-narrowing (beg end &rest body)
921 "Execute BODY with BEG..END narrowing.
922 Space is added (and then removed) at the beginning for the text's
923 indentation to be kept as it was before narrowing."
924 (declare (debug t) (indent 2))
925 (let ((bindent (make-symbol "bindent")))
926 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
927 (save-restriction
928 (narrow-to-region ,beg ,end)
929 (goto-char (point-min))
930 (insert (make-string ,bindent ? ))
931 (prog1
932 (progn ,@body)
933 ;; remove the bindent
934 (save-excursion
935 (goto-char (point-min))
936 (when (looking-at " *")
937 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
938 (delete-char n)
939 (setq ,bindent (- ,bindent n))))
940 (end-of-line)
941 (let ((e (point)))
942 (beginning-of-line)
943 (while (and (> ,bindent 0) (re-search-forward " *" e t))
944 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
945 (goto-char (match-beginning 0))
946 (delete-char n)
947 (setq ,bindent (- ,bindent n)))))))))))
949 ;; Compute the number of extra comment starter characters
950 ;; (extra semicolons in Lisp mode, extra stars in C mode, etc.)
951 ;; If ARG is non-nil, just follow ARG.
952 ;; If the comment-starter is multi-char, just follow ARG.
953 ;; Otherwise obey comment-add, and double it if EXTRA is non-nil.
954 (defun comment-add (arg)
955 (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
956 (* comment-add 1)
957 (1- (prefix-numeric-value arg))))
959 (defun comment-region-internal (beg end cs ce
960 &optional ccs cce block lines indent)
961 "Comment region BEG .. END.
962 CS and CE are the comment start string and comment end string,
963 respectively. CCS and CCE are the comment continuation strings
964 for the start and end of lines, respectively (default to CS and CE).
965 BLOCK indicates that end of lines should be marked with either CCE,
966 CE or CS \(if CE is empty) and that those markers should be aligned.
967 LINES indicates that an extra lines will be used at the beginning
968 and end of the region for CE and CS.
969 INDENT indicates to put CS and CCS at the current indentation of
970 the region rather than at left margin."
971 ;;(assert (< beg end))
972 (let ((no-empty (not (or (eq comment-empty-lines t)
973 (and comment-empty-lines (zerop (length ce))))))
974 ce-sanitized)
975 ;; Sanitize CE and CCE.
976 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
977 (setq ce-sanitized ce)
978 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
979 ;; If CE is empty, multiline cannot be used.
980 (unless ce (setq ccs nil cce nil))
981 ;; Should we mark empty lines as well ?
982 (if (or ccs block lines) (setq no-empty nil))
983 ;; Make sure we have end-markers for BLOCK mode.
984 (when block (unless ce (setq ce (comment-string-reverse cs))))
985 ;; If BLOCK is not requested, we don't need CCE.
986 (unless block (setq cce nil))
987 ;; Continuation defaults to the same as CS and CE.
988 (unless ccs (setq ccs cs cce ce))
990 (save-excursion
991 (goto-char end)
992 ;; If the end is not at the end of a line and the comment-end
993 ;; is implicit (i.e. a newline), explicitly insert a newline.
994 (unless (or ce-sanitized (eolp)) (insert "\n") (indent-according-to-mode))
995 (comment-with-narrowing beg end
996 (let ((min-indent (point-max))
997 (max-indent 0))
998 (goto-char (point-min))
999 ;; Quote any nested comment marker
1000 (comment-quote-nested comment-start comment-end nil)
1002 ;; Loop over all lines to find the needed indentations.
1003 (goto-char (point-min))
1004 (while
1005 (progn
1006 (unless (looking-at "[ \t]*$")
1007 (setq min-indent (min min-indent (current-indentation))))
1008 (end-of-line)
1009 (setq max-indent (max max-indent (current-column)))
1010 (not (or (eobp) (progn (forward-line) nil)))))
1012 (setq max-indent
1013 (+ max-indent (max (length cs) (length ccs))
1014 ;; Inserting ccs can change max-indent by (1- tab-width)
1015 ;; but only if there are TABs in the boxed text, of course.
1016 (if (save-excursion (goto-char beg)
1017 (search-forward "\t" end t))
1018 (1- tab-width) 0)))
1019 (unless indent (setq min-indent 0))
1021 ;; make the leading and trailing lines if requested
1022 (when lines
1023 (let ((csce
1024 (comment-make-extra-lines
1025 cs ce ccs cce min-indent max-indent block)))
1026 (setq cs (car csce))
1027 (setq ce (cdr csce))))
1029 (goto-char (point-min))
1030 ;; Loop over all lines from BEG to END.
1031 (while
1032 (progn
1033 (unless (and no-empty (looking-at "[ \t]*$"))
1034 (move-to-column min-indent t)
1035 (insert cs) (setq cs ccs) ;switch to CCS after the first line
1036 (end-of-line)
1037 (if (eobp) (setq cce ce))
1038 (when cce
1039 (when block (move-to-column max-indent t))
1040 (insert cce)))
1041 (end-of-line)
1042 (not (or (eobp) (progn (forward-line) nil))))))))))
1044 ;;;###autoload
1045 (defun comment-region (beg end &optional arg)
1046 "Comment or uncomment each line in the region.
1047 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
1048 Numeric prefix ARG means use ARG comment characters.
1049 If ARG is negative, delete that many comment characters instead.
1051 The strings used as comment starts are built from `comment-start'
1052 and `comment-padding'; the strings used as comment ends are built
1053 from `comment-end' and `comment-padding'.
1055 By default, the `comment-start' markers are inserted at the
1056 current indentation of the region, and comments are terminated on
1057 each line (even for syntaxes in which newline does not end the
1058 comment and blank lines do not get comments). This can be
1059 changed with `comment-style'."
1060 (interactive "*r\nP")
1061 (comment-normalize-vars)
1062 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
1063 (save-excursion
1064 ;; FIXME: maybe we should call uncomment depending on ARG.
1065 (funcall comment-region-function beg end arg)))
1067 (defun comment-region-default (beg end &optional arg)
1068 (let* ((numarg (prefix-numeric-value arg))
1069 (style (cdr (assoc comment-style comment-styles)))
1070 (lines (nth 2 style))
1071 (block (nth 1 style))
1072 (multi (nth 0 style)))
1074 ;; We use `chars' instead of `syntax' because `\n' might be
1075 ;; of end-comment syntax rather than of whitespace syntax.
1076 ;; sanitize BEG and END
1077 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
1078 (setq beg (max beg (point)))
1079 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
1080 (setq end (min end (point)))
1081 (if (>= beg end) (error "Nothing to comment"))
1083 ;; sanitize LINES
1084 (setq lines
1085 (and
1086 lines ;; multi
1087 (progn (goto-char beg) (beginning-of-line)
1088 (skip-syntax-forward " ")
1089 (>= (point) beg))
1090 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
1091 (<= (point) end))
1092 (or block (not (string= "" comment-end)))
1093 (or block (progn (goto-char beg) (search-forward "\n" end t)))))
1095 ;; don't add end-markers just because the user asked for `block'
1096 (unless (or lines (string= "" comment-end)) (setq block nil))
1098 (cond
1099 ((consp arg) (uncomment-region beg end))
1100 ((< numarg 0) (uncomment-region beg end (- numarg)))
1102 (let ((multi-char (/= (string-match "[ \t]*\\'" comment-start) 1))
1103 indent triple)
1104 (if (eq (nth 3 style) 'multi-char)
1105 (save-excursion
1106 (goto-char beg)
1107 (setq indent multi-char
1108 ;; Triple if we will put the comment starter at the margin
1109 ;; and the first line of the region isn't indented
1110 ;; at least two spaces.
1111 triple (and (not multi-char) (looking-at "\t\\| "))))
1112 (setq indent (nth 3 style)))
1114 ;; In Lisp and similar modes with one-character comment starters,
1115 ;; double it by default if `comment-add' says so.
1116 ;; If it isn't indented, triple it.
1117 (if (and (null arg) (not multi-char))
1118 (setq numarg (* comment-add (if triple 2 1)))
1119 (setq numarg (1- (prefix-numeric-value arg))))
1121 (comment-region-internal
1122 beg end
1123 (let ((s (comment-padright comment-start numarg)))
1124 (if (string-match comment-start-skip s) s
1125 (comment-padright comment-start)))
1126 (let ((s (comment-padleft comment-end numarg)))
1127 (and s (if (string-match comment-end-skip s) s
1128 (comment-padright comment-end))))
1129 (if multi (comment-padright comment-continue numarg))
1130 (if multi
1131 (comment-padleft (comment-string-reverse comment-continue) numarg))
1132 block
1133 lines
1134 indent))))))
1136 ;;;###autoload
1137 (defun comment-box (beg end &optional arg)
1138 "Comment out the BEG .. END region, putting it inside a box.
1139 The numeric prefix ARG specifies how many characters to add to begin- and
1140 end- comment markers additionally to what `comment-add' already specifies."
1141 (interactive "*r\np")
1142 (comment-normalize-vars)
1143 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
1144 'box-multi 'box)))
1145 (comment-region beg end (+ comment-add arg))))
1148 ;;;###autoload
1149 (defun comment-or-uncomment-region (beg end &optional arg)
1150 "Call `comment-region', unless the region only consists of comments,
1151 in which case call `uncomment-region'. If a prefix arg is given, it
1152 is passed on to the respective function."
1153 (interactive "*r\nP")
1154 (comment-normalize-vars)
1155 (funcall (if (save-excursion ;; check for already commented region
1156 (goto-char beg)
1157 (comment-forward (point-max))
1158 (<= end (point)))
1159 'uncomment-region 'comment-region)
1160 beg end arg))
1162 ;;;###autoload
1163 (defun comment-dwim (arg)
1164 "Call the comment command you want (Do What I Mean).
1165 If the region is active and `transient-mark-mode' is on, call
1166 `comment-region' (unless it only consists of comments, in which
1167 case it calls `uncomment-region').
1168 Else, if the current line is empty, call `comment-insert-comment-function'
1169 if it is defined, otherwise insert a comment and indent it.
1170 Else if a prefix ARG is specified, call `comment-kill'.
1171 Else, call `comment-indent'.
1172 You can configure `comment-style' to change the way regions are commented."
1173 (interactive "*P")
1174 (comment-normalize-vars)
1175 (if (and mark-active transient-mark-mode)
1176 (comment-or-uncomment-region (region-beginning) (region-end) arg)
1177 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
1178 ;; FIXME: If there's no comment to kill on this line and ARG is
1179 ;; specified, calling comment-kill is not very clever.
1180 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
1181 ;; Inserting a comment on a blank line. comment-indent calls
1182 ;; c-i-c-f if needed in the non-blank case.
1183 (if comment-insert-comment-function
1184 (funcall comment-insert-comment-function)
1185 (let ((add (comment-add arg)))
1186 ;; Some modes insist on keeping column 0 comment in column 0
1187 ;; so we need to move away from it before inserting the comment.
1188 (indent-according-to-mode)
1189 (insert (comment-padright comment-start add))
1190 (save-excursion
1191 (unless (string= "" comment-end)
1192 (insert (comment-padleft comment-end add)))
1193 (indent-according-to-mode)))))))
1195 ;;;###autoload
1196 (defcustom comment-auto-fill-only-comments nil
1197 "Non-nil means to only auto-fill inside comments.
1198 This has no effect in modes that do not define a comment syntax."
1199 :type 'boolean
1200 :group 'comment)
1202 (defun comment-valid-prefix-p (prefix compos)
1203 "Check that the adaptive-fill-prefix is consistent with the context.
1204 PREFIX is the prefix (presumably guessed by `adaptive-fill-mode').
1205 COMPOS is the position of the beginning of the comment we're in, or nil
1206 if we're not inside a comment."
1207 ;; This consistency checking is mostly needed to workaround the limitation
1208 ;; of auto-fill-mode whose paragraph-determination doesn't pay attention
1209 ;; to comment boundaries.
1210 (if (null compos)
1211 ;; We're not inside a comment: the prefix shouldn't match
1212 ;; a comment-starter.
1213 (not (and comment-start comment-start-skip
1214 (string-match comment-start-skip prefix)))
1216 ;; Accept any prefix if the current comment is not EOL-terminated.
1217 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1218 ;; Accept any prefix that starts with the same comment-start marker
1219 ;; as the current one.
1220 (when (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1221 prefix)
1222 (let ((prefix-com (comment-string-strip (match-string 0 prefix) nil t)))
1223 (string-match "\\`[ \t]*" prefix-com)
1224 (let* ((prefix-space (match-string 0 prefix-com))
1225 (prefix-indent (string-width prefix-space))
1226 (prefix-comstart (substring prefix-com (match-end 0))))
1227 (save-excursion
1228 (goto-char compos)
1229 ;; The comstart marker is the same.
1230 (and (looking-at (regexp-quote prefix-comstart))
1231 ;; The indentation as well.
1232 (or (= prefix-indent
1233 (- (current-column) (current-left-margin)))
1234 ;; Check the indentation in two different ways, just
1235 ;; to try and avoid most of the potential funny cases.
1236 (equal prefix-space
1237 (buffer-substring (point)
1238 (progn (move-to-left-margin)
1239 (point)))))))))))))
1242 ;;;###autoload
1243 (defun comment-indent-new-line (&optional soft)
1244 "Break line at point and indent, continuing comment if within one.
1245 This indents the body of the continued comment
1246 under the previous comment line.
1248 This command is intended for styles where you write a comment per line,
1249 starting a new comment (and terminating it if necessary) on each line.
1250 If you want to continue one comment across several lines, use \\[newline-and-indent].
1252 If a fill column is specified, it overrides the use of the comment column
1253 or comment indentation.
1255 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1256 unless optional argument SOFT is non-nil."
1257 (interactive)
1258 (comment-normalize-vars t)
1259 (let (compos comin)
1260 ;; If we are not inside a comment and we only auto-fill comments,
1261 ;; don't do anything (unless no comment syntax is defined).
1262 (unless (and comment-start
1263 comment-auto-fill-only-comments
1264 (not (called-interactively-p 'interactive))
1265 (not (save-excursion
1266 (prog1 (setq compos (comment-beginning))
1267 (setq comin (point))))))
1269 ;; Now we know we should auto-fill.
1270 ;; Insert the newline before removing empty space so that markers
1271 ;; get preserved better.
1272 (if soft (insert-and-inherit ?\n) (newline 1))
1273 (save-excursion (forward-char -1) (delete-horizontal-space))
1274 (delete-horizontal-space)
1276 (if (and fill-prefix (not adaptive-fill-mode))
1277 ;; Blindly trust a non-adaptive fill-prefix.
1278 (progn
1279 (indent-to-left-margin)
1280 (insert-before-markers-and-inherit fill-prefix))
1282 ;; If necessary check whether we're inside a comment.
1283 (unless (or compos (null comment-start))
1284 (save-excursion
1285 (backward-char)
1286 (setq compos (comment-beginning))
1287 (setq comin (point))))
1289 (cond
1290 ;; If there's an adaptive prefix, use it unless we're inside
1291 ;; a comment and the prefix is not a comment starter.
1292 ((and fill-prefix
1293 (comment-valid-prefix-p fill-prefix compos))
1294 (indent-to-left-margin)
1295 (insert-and-inherit fill-prefix))
1296 ;; If we're not inside a comment, just try to indent.
1297 ((not compos) (indent-according-to-mode))
1299 (let* ((comment-column
1300 ;; The continuation indentation should be somewhere between
1301 ;; the current line's indentation (plus 2 for good measure)
1302 ;; and the current comment's indentation, with a preference
1303 ;; for comment-column.
1304 (save-excursion
1305 ;; FIXME: use prev line's info rather than first line's.
1306 (goto-char compos)
1307 (min (current-column) (max comment-column
1308 (+ 2 (current-indentation))))))
1309 (comstart (buffer-substring compos comin))
1310 (normalp
1311 (string-match (regexp-quote (comment-string-strip
1312 comment-start t t))
1313 comstart))
1314 (comment-end
1315 (if normalp comment-end
1316 ;; The comment starter is not the normal comment-start
1317 ;; so we can't just use comment-end.
1318 (save-excursion
1319 (goto-char compos)
1320 (if (not (comment-forward)) comment-end
1321 (comment-string-strip
1322 (buffer-substring
1323 (save-excursion (comment-enter-backward) (point))
1324 (point))
1325 nil t)))))
1326 (comment-start comstart)
1327 (continuep (or comment-multi-line
1328 (cadr (assoc comment-style comment-styles))))
1329 ;; Force comment-continue to be recreated from comment-start.
1330 ;; FIXME: wrong if comment-continue was set explicitly!
1331 ;; FIXME: use prev line's continuation if available.
1332 (comment-continue nil))
1333 (if (and comment-multi-line (> (length comment-end) 0))
1334 (indent-according-to-mode)
1335 (insert-and-inherit ?\n)
1336 (forward-char -1)
1337 (comment-indent continuep)
1338 (save-excursion
1339 (let ((pt (point)))
1340 (end-of-line)
1341 (let ((comend (buffer-substring pt (point))))
1342 ;; The 1+ is to make sure we delete the \n inserted above.
1343 (delete-region pt (1+ (point)))
1344 (end-of-line 0)
1345 (insert comend))))))))))))
1347 (provide 'newcomment)
1349 ;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
1350 ;;; newcomment.el ends here