(frame-parameter) <defsetf>: Make it return the assigned value.
[emacs.git] / lisp / newcomment.el
blob565b5e39137d27192425b227810071293f718eaf
1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 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, or (at your option)
15 ;; 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; A replacement for simple.el's comment-related functions.
31 ;;; Bugs:
33 ;; - boxed comments in Perl are not properly uncommented because they are
34 ;; uncommented one-line at a time.
35 ;; - nested comments in sgml-mode are not properly quoted.
36 ;; - single-char nestable comment-start can only do the "\\s<+" stuff
37 ;; if the corresponding closing marker happens to be right.
38 ;; - uncomment-region with a numeric argument can render multichar
39 ;; comment markers invalid.
40 ;; - comment-indent or comment-region when called inside a comment
41 ;; will happily break the surrounding comment.
42 ;; - comment-quote-nested will not (un)quote properly all nested comment
43 ;; markers if there are more than just comment-start and comment-end.
44 ;; For example, in Pascal where {...*) and (*...} are possible.
46 ;;; Todo:
48 ;; - rebox.el-style refill.
49 ;; - quantized steps in comment-alignment.
50 ;; - try to align tail comments.
51 ;; - check what c-comment-line-break-function has to say.
52 ;; - spill auto-fill of comments onto the end of the next line.
53 ;; - uncomment-region with a consp (for blocks) or somehow make the
54 ;; deletion of continuation markers less dangerous.
55 ;; - drop block-comment-<foo> unless it's really used.
56 ;; - uncomment-region on a subpart of a comment.
57 ;; - support gnu-style "multi-line with space in continue".
58 ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
59 ;; is not turned on.
61 ;; - when auto-filling a comment, try to move the comment to the left
62 ;; rather than break it (if possible).
63 ;; - sometimes default the comment-column to the same
64 ;; one used on the preceding line(s).
66 ;;; Code:
68 ;;;###autoload
69 (defalias 'indent-for-comment 'comment-indent)
70 ;;;###autoload
71 (defalias 'set-comment-column 'comment-set-column)
72 ;;;###autoload
73 (defalias 'kill-comment 'comment-kill)
74 ;;;###autoload
75 (defalias 'indent-new-comment-line 'comment-indent-new-line)
77 (defgroup comment nil
78 "Indenting and filling of comments."
79 :prefix "comment-"
80 :version "21.1"
81 :group 'fill)
83 ;; Autoload this to avoid warnings, since some major modes define it.
84 ;;;###autoload
85 (defvar comment-use-syntax 'undecided
86 "Non-nil if syntax-tables can be used instead of regexps.
87 Can also be `undecided' which means that a somewhat expensive test will
88 be used to try to determine whether syntax-tables should be trusted
89 to understand comments or not in the given buffer.
90 Major modes should set this variable.")
92 (defcustom comment-fill-column nil
93 "Column to use for `comment-indent'. If nil, use `fill-column' instead."
94 :type '(choice (const nil) integer)
95 :group 'comment)
97 ;;;###autoload
98 (defcustom comment-column 32
99 "Column to indent right-margin comments to.
100 Each mode may establish a different default value for this variable; you
101 can set the value for a particular mode using that mode's hook.
102 Comments might be indented to a different value in order not to go beyond
103 `comment-fill-column' or in order to align them with surrounding comments."
104 :type 'integer
105 :group 'comment)
106 (make-variable-buffer-local 'comment-column)
107 ;;;###autoload(put 'comment-column 'safe-local-variable 'integerp)
109 ;;;###autoload
110 (defvar comment-start nil
111 "*String to insert to start a new comment, or nil if no comment syntax.")
112 ;;;###autoload(put 'comment-start 'safe-local-variable 'string-or-null-p)
114 ;;;###autoload
115 (defvar comment-start-skip nil
116 "*Regexp to match the start of a comment plus everything up to its body.
117 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
118 at the place matched by the close of the first pair.")
119 ;;;###autoload(put 'comment-start-skip 'safe-local-variable 'string-or-null-p)
121 ;;;###autoload
122 (defvar comment-end-skip nil
123 "Regexp to match the end of a comment plus everything up to its body.")
124 ;;;###autoload(put 'comment-end-skip 'safe-local-variable 'string-or-null-p)
126 ;;;###autoload
127 (defvar comment-end ""
128 "*String to insert to end a new comment.
129 Should be an empty string if comments are terminated by end-of-line.")
130 ;;;###autoload(put 'comment-end 'safe-local-variable 'string-or-null-p)
132 ;;;###autoload
133 (defvar comment-indent-function 'comment-indent-default
134 "Function to compute desired indentation for a comment.
135 This function is called with no args with point at the beginning of
136 the comment's starting delimiter and should return either the desired
137 column indentation or nil.
138 If nil is returned, indentation is delegated to `indent-according-to-mode'.")
140 ;;;###autoload
141 (defvar comment-insert-comment-function nil
142 "Function to insert a comment when a line doesn't contain one.
143 The function has no args.
145 Applicable at least in modes for languages like fixed-format Fortran where
146 comments always start in column zero.")
148 (defvar comment-region-function 'comment-region-default
149 "Function to comment a region.
150 Its args are the same as those of `comment-region', but BEG and END are
151 guaranteed to be correctly ordered. It is called within `save-excursion'.
153 Applicable at least in modes for languages like fixed-format Fortran where
154 comments always start in column zero.")
156 (defvar uncomment-region-function 'uncomment-region-default
157 "Function to uncomment a region.
158 Its args are the same as those of `uncomment-region', but BEG and END are
159 guaranteed to be correctly ordered. It is called within `save-excursion'.
161 Applicable at least in modes for languages like fixed-format Fortran where
162 comments always start in column zero.")
164 ;; ?? never set
165 (defvar block-comment-start nil)
166 (defvar block-comment-end nil)
168 (defvar comment-quote-nested t
169 "Non-nil if nested comments should be quoted.
170 This should be locally set by each major mode if needed.")
172 (defvar comment-continue nil
173 "Continuation string to insert for multiline comments.
174 This string will be added at the beginning of each line except the very
175 first one when commenting a region with a commenting style that allows
176 comments to span several lines.
177 It should generally have the same length as `comment-start' in order to
178 preserve indentation.
179 If it is nil a value will be automatically derived from `comment-start'
180 by replacing its first character with a space.")
182 (defvar comment-add 0
183 "How many more comment chars should be inserted by `comment-region'.
184 This determines the default value of the numeric argument of `comment-region'.
185 The `plain' comment style doubles this value.
187 This should generally stay 0, except for a few modes like Lisp where
188 it is 1 so that regions are commented with two or three semi-colons.")
190 (defconst comment-styles
191 '((plain . (nil nil nil nil))
192 (indent . (nil nil nil t))
193 (indent-or-triple
194 . (nil nil nil multi-char))
195 (aligned . (nil t nil t))
196 (multi-line . (t nil nil t))
197 (extra-line . (t nil t t))
198 (box . (nil t t t))
199 (box-multi . (t t t t)))
200 "Comment region styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
201 STYLE should be a mnemonic symbol.
202 MULTI specifies that comments are allowed to span multiple lines.
203 ALIGN specifies that the `comment-end' markers should be aligned.
204 EXTRA specifies that an extra line should be used before and after the
205 region to comment (to put the `comment-end' and `comment-start').
206 INDENT specifies that the `comment-start' markers should not be put at the
207 left margin but at the current indentation of the region to comment.
208 If INDENT is `multi-char', that means indent multi-character
209 comment starters, but not one-character comment starters.")
211 ;;;###autoload
212 (defcustom comment-style 'indent-or-triple
213 "Style to be used for `comment-region'.
214 See `comment-styles' for a list of available styles."
215 :type (if (boundp 'comment-styles)
216 `(choice ,@(mapcar (lambda (s) `(const ,(car s)))
217 comment-styles))
218 'symbol)
219 :group 'comment)
221 ;;;###autoload
222 (defcustom comment-padding " "
223 "Padding string that `comment-region' puts between comment chars and text.
224 Can also be an integer which will be automatically turned into a string
225 of the corresponding number of spaces.
227 Extra spacing between the comment characters and the comment text
228 makes the comment easier to read. Default is 1. nil means 0."
229 :type '(choice string integer (const nil))
230 :group 'comment)
232 ;;;###autoload
233 (defcustom comment-multi-line nil
234 "Non-nil means `comment-indent-new-line' continues comments.
235 That is, it inserts no new terminator or starter.
236 This affects `auto-fill-mode', which is the main reason to
237 customize this variable.
239 It also affects \\[indent-new-comment-line]. However, if you want this
240 behavior for explicit filling, you might as well use \\[newline-and-indent]."
241 :type 'boolean
242 :group 'comment)
244 (defcustom comment-empty-lines nil
245 "If nil, `comment-region' does not comment out empty lines.
246 If t, it always comments out empty lines.
247 If `eol' it only comments out empty lines if comments are
248 terminated by the end of line (i.e. `comment-end' is empty)."
249 :type '(choice (const :tag "Never" nil)
250 (const :tag "Always" t)
251 (const :tag "EOl-terminated" 'eol))
252 :group 'comment)
254 ;;;;
255 ;;;; Helpers
256 ;;;;
258 (defun comment-string-strip (str beforep afterp)
259 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
260 (string-match (concat "\\`" (if beforep "\\s-*")
261 "\\(.*?\\)" (if afterp "\\s-*\n?")
262 "\\'") str)
263 (match-string 1 str))
265 (defun comment-string-reverse (s)
266 "Return the mirror image of string S, without any trailing space."
267 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
269 ;;;###autoload
270 (defun comment-normalize-vars (&optional noerror)
271 "Check and setup the variables needed by other commenting functions.
272 Functions autoloaded from newcomment.el, being entry points, should call
273 this function before any other, so the rest of the code can assume that
274 the variables are properly set."
275 (unless (and (not comment-start) noerror)
276 (unless comment-start
277 (let ((cs (read-string "No comment syntax is defined. Use: ")))
278 (if (zerop (length cs))
279 (error "No comment syntax defined")
280 (set (make-local-variable 'comment-start) cs))))
281 ;; comment-use-syntax
282 (when (eq comment-use-syntax 'undecided)
283 (set (make-local-variable 'comment-use-syntax)
284 (let ((st (syntax-table))
285 (cs comment-start)
286 (ce (if (string= "" comment-end) "\n" comment-end)))
287 ;; Try to skip over a comment using forward-comment
288 ;; to see if the syntax tables properly recognize it.
289 (with-temp-buffer
290 (set-syntax-table st)
291 (insert cs " hello " ce)
292 (goto-char (point-min))
293 (and (forward-comment 1) (eobp))))))
294 ;; comment-padding
295 (unless comment-padding (setq comment-padding 0))
296 (when (integerp comment-padding)
297 (setq comment-padding (make-string comment-padding ? )))
298 ;; comment markers
299 ;;(setq comment-start (comment-string-strip comment-start t nil))
300 ;;(setq comment-end (comment-string-strip comment-end nil t))
301 ;; comment-continue
302 (unless (or comment-continue (string= comment-end ""))
303 (set (make-local-variable 'comment-continue)
304 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
305 (substring comment-start 1)))
306 ;; Hasn't been necessary yet.
307 ;; (unless (string-match comment-start-skip comment-continue)
308 ;; (kill-local-variable 'comment-continue))
310 ;; comment-skip regexps
311 (unless (and comment-start-skip
312 ;; In case comment-start has changed since last time.
313 (string-match comment-start-skip comment-start))
314 (set (make-local-variable 'comment-start-skip)
315 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
316 (regexp-quote (comment-string-strip comment-start t t))
317 ;; Let's not allow any \s- but only [ \t] since \n
318 ;; might be both a comment-end marker and \s-.
319 "+\\)[ \t]*")))
320 (unless (and comment-end-skip
321 ;; In case comment-end has changed since last time.
322 (string-match comment-end-skip 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-restriction
496 (narrow-to-region (line-beginning-position) (point))
497 (goto-char (point-min))
498 (re-search-forward (concat comment-end-skip "\\'") nil t))
499 (goto-char (match-beginning 0)))
500 ;; comment-end-skip not found probably because it was not set
501 ;; right. Since \\s> should catch the single-char case, let's
502 ;; check that we're looking at a two-char comment ender.
503 ((not (or (<= (- (point-max) (line-beginning-position)) 1)
504 (zerop (logand (car (syntax-after (- (point) 1)))
505 ;; Here we take advantage of the fact that
506 ;; the syntax class " " is encoded to 0,
507 ;; so " 4" gives us just the 4 bit.
508 (car (string-to-syntax " 4"))))
509 (zerop (logand (car (syntax-after (- (point) 2)))
510 (car (string-to-syntax " 3"))))))
511 (backward-char 2)
512 (skip-chars-backward (string (char-after)))
513 (skip-syntax-backward " "))
514 ;; No clue what's going on: maybe we're really not right after the
515 ;; end of a comment. Maybe we're at the "end" because of EOB rather
516 ;; than because of a marker.
517 (t (skip-syntax-backward " ")))))
519 ;;;;
520 ;;;; Commands
521 ;;;;
523 ;;;###autoload
524 (defun comment-indent-default ()
525 "Default for `comment-indent-function'."
526 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
527 (or (match-end 1) (/= (current-column) (current-indentation))))
529 (when (or (/= (current-column) (current-indentation))
530 (and (> comment-add 0) (looking-at "\\s<\\(\\S<\\|\\'\\)")))
531 comment-column)))
533 (defun comment-choose-indent (&optional indent)
534 "Choose the indentation to use for a right-hand-side comment.
535 The criteria are (in this order):
536 - try to keep the comment's text within `comment-fill-column'.
537 - try to align with surrounding comments.
538 - prefer INDENT (or `comment-column' if nil).
539 Point is expected to be at the start of the comment."
540 (unless indent (setq indent comment-column))
541 ;; Avoid moving comments past the fill-column.
542 (let ((max (+ (current-column)
543 (- (or comment-fill-column fill-column)
544 (save-excursion (end-of-line) (current-column)))))
545 (other nil)
546 (min (save-excursion (skip-chars-backward " \t")
547 (1+ (current-column)))))
548 ;; Fix up the range.
549 (if (< max min) (setq max min))
550 ;; Don't move past the fill column.
551 (if (<= max indent) (setq indent max))
552 ;; We can choose anywhere between min..max.
553 ;; Let's try to align to a comment on the previous line.
554 (save-excursion
555 (when (and (zerop (forward-line -1))
556 (setq other (comment-search-forward
557 (line-end-position) t)))
558 (goto-char other) (setq other (current-column))))
559 (if (and other (<= other max) (>= other min))
560 ;; There is a comment and it's in the range: bingo!
561 other
562 ;; Can't align to a previous comment: let's try to align to comments
563 ;; on the following lines, then. These have not been re-indented yet,
564 ;; so we can't directly align ourselves with them. All we do is to try
565 ;; and choose an indentation point with which they will be able to
566 ;; align themselves.
567 (save-excursion
568 (while (and (zerop (forward-line 1))
569 (setq other (comment-search-forward
570 (line-end-position) t)))
571 (goto-char other)
572 (let ((omax (+ (current-column)
573 (- (or comment-fill-column fill-column)
574 (save-excursion (end-of-line) (current-column)))))
575 (omin (save-excursion (skip-chars-backward " \t")
576 (1+ (current-column)))))
577 (if (and (>= omax min) (<= omin max))
578 (progn (setq min (max omin min))
579 (setq max (min omax max)))
580 ;; Can't align with this anyway, so exit the loop.
581 (goto-char (point-max))))))
582 ;; Return the closest point to indent within min..max.
583 (max min (min max indent)))))
585 ;;;###autoload
586 (defun comment-indent (&optional continue)
587 "Indent this line's comment to `comment-column', or insert an empty comment.
588 If CONTINUE is non-nil, use the `comment-continue' markers if any."
589 (interactive "*")
590 (comment-normalize-vars)
591 (let* ((empty (save-excursion (beginning-of-line)
592 (looking-at "[ \t]*$")))
593 (starter (or (and continue comment-continue)
594 (and empty block-comment-start) comment-start))
595 (ender (or (and continue comment-continue "")
596 (and empty block-comment-end) comment-end)))
597 (unless starter (error "No comment syntax defined"))
598 (beginning-of-line)
599 (let* ((eolpos (line-end-position))
600 (begpos (comment-search-forward eolpos t))
601 cpos indent)
602 (if (and comment-insert-comment-function (not begpos))
603 ;; If no comment and c-i-c-f is set, let it do everything.
604 (funcall comment-insert-comment-function)
605 ;; An existing comment?
606 (if begpos
607 (progn
608 (if (and (not (looking-at "[\t\n ]"))
609 (looking-at comment-end-skip))
610 ;; The comment is empty and we have skipped all its space
611 ;; and landed right before the comment-ender:
612 ;; Go back to the middle of the space.
613 (forward-char (/ (skip-chars-backward " \t") -2)))
614 (setq cpos (point-marker)))
615 ;; If none, insert one.
616 (save-excursion
617 ;; Some `comment-indent-function's insist on not moving
618 ;; comments that are in column 0, so we first go to the
619 ;; likely target column.
620 (indent-to comment-column)
621 ;; Ensure there's a space before the comment for things
622 ;; like sh where it matters (as well as being neater).
623 (unless (memq (char-before) '(nil ?\n ?\t ?\s))
624 (insert ?\s))
625 (setq begpos (point))
626 (insert starter)
627 (setq cpos (point-marker))
628 (insert ender)))
629 (goto-char begpos)
630 ;; Compute desired indent.
631 (setq indent (save-excursion (funcall comment-indent-function)))
632 ;; If `indent' is nil and there's code before the comment, we can't
633 ;; use `indent-according-to-mode', so we default to comment-column.
634 (unless (or indent (save-excursion (skip-chars-backward " \t") (bolp)))
635 (setq indent comment-column))
636 (if (not indent)
637 ;; comment-indent-function refuses: delegate to line-indent.
638 (indent-according-to-mode)
639 ;; If the comment is at the right of code, adjust the indentation.
640 (unless (save-excursion (skip-chars-backward " \t") (bolp))
641 (setq indent (comment-choose-indent indent)))
642 ;; Update INDENT to leave at least one space
643 ;; after other nonwhite text on the line.
644 (save-excursion
645 (skip-chars-backward " \t")
646 (unless (bolp)
647 (setq indent (max indent (1+ (current-column))))))
648 ;; If that's different from comment's current position, change it.
649 (unless (= (current-column) indent)
650 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
651 (indent-to indent)))
652 (goto-char cpos)
653 (set-marker cpos nil)))))
655 ;;;###autoload
656 (defun comment-set-column (arg)
657 "Set the comment column based on point.
658 With no ARG, set the comment column to the current column.
659 With just minus as arg, kill any comment on this line.
660 With any other arg, set comment column to indentation of the previous comment
661 and then align or create a comment on this line at that column."
662 (interactive "P")
663 (cond
664 ((eq arg '-) (comment-kill nil))
665 (arg
666 (comment-normalize-vars)
667 (save-excursion
668 (beginning-of-line)
669 (comment-search-backward)
670 (beginning-of-line)
671 (goto-char (comment-search-forward (line-end-position)))
672 (setq comment-column (current-column))
673 (message "Comment column set to %d" comment-column))
674 (comment-indent))
675 (t (setq comment-column (current-column))
676 (message "Comment column set to %d" comment-column))))
678 ;;;###autoload
679 (defun comment-kill (arg)
680 "Kill the first comment on this line, if any.
681 With prefix ARG, kill comments on that many lines starting with this one."
682 (interactive "P")
683 (comment-normalize-vars)
684 (dotimes (_ (prefix-numeric-value arg))
685 (save-excursion
686 (beginning-of-line)
687 (let ((cs (comment-search-forward (line-end-position) t)))
688 (when cs
689 (goto-char cs)
690 (skip-syntax-backward " ")
691 (setq cs (point))
692 (comment-forward)
693 (kill-region cs (if (bolp) (1- (point)) (point)))
694 (indent-according-to-mode))))
695 (if arg (forward-line 1))))
697 (defun comment-padright (str &optional n)
698 "Construct a string composed of STR plus `comment-padding'.
699 It also adds N copies of the last non-whitespace chars of STR.
700 If STR already contains padding, the corresponding amount is
701 ignored from `comment-padding'.
702 N defaults to 0.
703 If N is `re', a regexp is returned instead, that would match
704 the string for any N."
705 (setq n (or n 0))
706 (when (and (stringp str) (not (string= "" str)))
707 ;; Separate the actual string from any leading/trailing padding
708 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
709 (let ((s (match-string 1 str)) ;actual string
710 (lpad (substring str 0 (match-beginning 1))) ;left padding
711 (rpad (concat (substring str (match-end 1)) ;original right padding
712 (substring comment-padding ;additional right padding
713 (min (- (match-end 0) (match-end 1))
714 (length comment-padding)))))
715 ;; We can only duplicate C if the comment-end has multiple chars
716 ;; or if comments can be nested, else the comment-end `}' would
717 ;; be turned into `}}}' where only the first ends the comment
718 ;; and the rest becomes bogus junk.
719 (multi (not (and comment-quote-nested
720 ;; comment-end is a single char
721 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
722 (if (not (symbolp n))
723 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
724 ;; construct a regexp that would match anything from just S
725 ;; to any possible output of this function for any N.
726 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
727 lpad "") ;padding is not required
728 (regexp-quote s)
729 (when multi "+") ;the last char of S might be repeated
730 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
731 rpad "")))))) ;padding is not required
733 (defun comment-padleft (str &optional n)
734 "Construct a string composed of `comment-padding' plus STR.
735 It also adds N copies of the first non-whitespace chars of STR.
736 If STR already contains padding, the corresponding amount is
737 ignored from `comment-padding'.
738 N defaults to 0.
739 If N is `re', a regexp is returned instead, that would match
740 the string for any N."
741 (setq n (or n 0))
742 (when (and (stringp str) (not (string= "" str)))
743 ;; Only separate the left pad because we assume there is no right pad.
744 (string-match "\\`\\s-*" str)
745 (let ((s (substring str (match-end 0)))
746 (pad (concat (substring comment-padding
747 (min (- (match-end 0) (match-beginning 0))
748 (length comment-padding)))
749 (match-string 0 str)))
750 (c (aref str (match-end 0))) ;the first non-space char of STR
751 ;; We can only duplicate C if the comment-end has multiple chars
752 ;; or if comments can be nested, else the comment-end `}' would
753 ;; be turned into `}}}' where only the first ends the comment
754 ;; and the rest becomes bogus junk.
755 (multi (not (and comment-quote-nested
756 ;; comment-end is a single char
757 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
758 (if (not (symbolp n))
759 (concat pad (when multi (make-string n c)) s)
760 ;; Construct a regexp that would match anything from just S
761 ;; to any possible output of this function for any N.
762 ;; We match any number of leading spaces because this regexp will
763 ;; be used for uncommenting where we might want to remove
764 ;; uncomment markers with arbitrary leading space (because
765 ;; they were aligned).
766 (concat "\\s-*"
767 (if multi (concat (regexp-quote (string c)) "*"))
768 (regexp-quote s))))))
770 ;;;###autoload
771 (defun uncomment-region (beg end &optional arg)
772 "Uncomment each line in the BEG .. END region.
773 The numeric prefix ARG can specify a number of chars to remove from the
774 comment markers."
775 (interactive "*r\nP")
776 (comment-normalize-vars)
777 (when (> beg end) (setq beg (prog1 end (setq end beg))))
778 ;; Bind `comment-use-global-state' to nil. While uncommenting a region
779 ;; (which works a line at a time), a comment can appear to be
780 ;; included in a mult-line string, but it is actually not.
781 (let ((comment-use-global-state nil))
782 (save-excursion
783 (funcall uncomment-region-function beg end arg))))
785 (defun uncomment-region-default (beg end &optional arg)
786 "Uncomment each line in the BEG .. END region.
787 The numeric prefix ARG can specify a number of chars to remove from the
788 comment markers."
789 (goto-char beg)
790 (setq end (copy-marker end))
791 (let* ((numarg (prefix-numeric-value arg))
792 (ccs comment-continue)
793 (srei (comment-padright ccs 're))
794 (csre (comment-padright comment-start 're))
795 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
796 spt)
797 (while (and (< (point) end)
798 (setq spt (comment-search-forward end t)))
799 (let ((ipt (point))
800 ;; Find the end of the comment.
801 (ept (progn
802 (goto-char spt)
803 (unless (or (comment-forward)
804 ;; Allow non-terminated comments.
805 (eobp))
806 (error "Can't find the comment end"))
807 (point)))
808 (box nil)
809 (box-equal nil)) ;Whether we might be using `=' for boxes.
810 (save-restriction
811 (narrow-to-region spt ept)
813 ;; Remove the comment-start.
814 (goto-char ipt)
815 (skip-syntax-backward " ")
816 ;; A box-comment starts with a looong comment-start marker.
817 (when (and (or (and (= (- (point) (point-min)) 1)
818 (setq box-equal t)
819 (looking-at "=\\{7\\}")
820 (not (eq (char-before (point-max)) ?\n))
821 (skip-chars-forward "="))
822 (> (- (point) (point-min) (length comment-start)) 7))
823 (> (count-lines (point-min) (point-max)) 2))
824 (setq box t))
825 ;; Skip the padding. Padding can come from comment-padding and/or
826 ;; from comment-start, so we first check comment-start.
827 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
828 (looking-at (regexp-quote comment-padding)))
829 (goto-char (match-end 0)))
830 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
831 (goto-char (match-end 0)))
832 (if (null arg) (delete-region (point-min) (point))
833 (skip-syntax-backward " ")
834 (delete-char (- numarg))
835 (unless (or (bobp)
836 (save-excursion (goto-char (point-min))
837 (looking-at comment-start-skip)))
838 ;; If there's something left but it doesn't look like
839 ;; a comment-start any more, just remove it.
840 (delete-region (point-min) (point))))
842 ;; Remove the end-comment (and leading padding and such).
843 (goto-char (point-max)) (comment-enter-backward)
844 ;; Check for special `=' used sometimes in comment-box.
845 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
846 (let ((pos (point)))
847 ;; skip `=' but only if there are at least 7.
848 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
849 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
850 (when (and (bolp) (not (bobp))) (backward-char))
851 (if (null arg) (delete-region (point) (point-max))
852 (skip-syntax-forward " ")
853 (delete-char numarg)
854 (unless (or (eobp) (looking-at comment-end-skip))
855 ;; If there's something left but it doesn't look like
856 ;; a comment-end any more, just remove it.
857 (delete-region (point) (point-max)))))
859 ;; Unquote any nested end-comment.
860 (comment-quote-nested comment-start comment-end t)
862 ;; Eliminate continuation markers as well.
863 (when sre
864 (let* ((cce (comment-string-reverse (or comment-continue
865 comment-start)))
866 (erei (and box (comment-padleft cce 're)))
867 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
868 (goto-char (point-min))
869 (while (progn
870 (if (and ere (re-search-forward
871 ere (line-end-position) t))
872 (replace-match "" t t nil (if (match-end 2) 2 1))
873 (setq ere nil))
874 (forward-line 1)
875 (re-search-forward sre (line-end-position) t))
876 (replace-match "" t t nil (if (match-end 2) 2 1)))))
877 ;; Go to the end for the next comment.
878 (goto-char (point-max))))))
879 (set-marker end nil))
881 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
882 "Make the leading and trailing extra lines.
883 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
884 (let ((eindent 0))
885 (if (not block)
886 ;; Try to match CS and CE's content so they align aesthetically.
887 (progn
888 (setq ce (comment-string-strip ce t t))
889 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
890 (setq eindent
891 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
892 0))))
893 ;; box comment
894 (let* ((width (- max-indent min-indent))
895 (s (concat cs "a=m" cce))
896 (e (concat ccs "a=m" ce))
897 (c (if (string-match ".*\\S-\\S-" cs)
898 (aref cs (1- (match-end 0)))
899 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
900 (aref cs (1- (match-end 0))) ?=)))
901 (re "\\s-*a=m\\s-*")
902 (_ (string-match re s))
903 (lcs (length cs))
904 (fill
905 (make-string (+ width (- (match-end 0)
906 (match-beginning 0) lcs 3)) c)))
907 (setq cs (replace-match fill t t s))
908 (when (and (not (string-match comment-start-skip cs))
909 (string-match "a=m" s))
910 ;; The whitespace around CS cannot be ignored: put it back.
911 (setq re "a=m")
912 (setq fill (make-string (- width lcs) c))
913 (setq cs (replace-match fill t t s)))
914 (string-match re e)
915 (setq ce (replace-match fill t t e))))
916 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
917 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
919 (defmacro comment-with-narrowing (beg end &rest body)
920 "Execute BODY with BEG..END narrowing.
921 Space is added (and then removed) at the beginning for the text's
922 indentation to be kept as it was before narrowing."
923 (declare (debug t) (indent 2))
924 (let ((bindent (make-symbol "bindent")))
925 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
926 (save-restriction
927 (narrow-to-region ,beg ,end)
928 (goto-char (point-min))
929 (insert (make-string ,bindent ? ))
930 (prog1
931 (progn ,@body)
932 ;; remove the bindent
933 (save-excursion
934 (goto-char (point-min))
935 (when (looking-at " *")
936 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
937 (delete-char n)
938 (setq ,bindent (- ,bindent n))))
939 (end-of-line)
940 (let ((e (point)))
941 (beginning-of-line)
942 (while (and (> ,bindent 0) (re-search-forward " *" e t))
943 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
944 (goto-char (match-beginning 0))
945 (delete-char n)
946 (setq ,bindent (- ,bindent n)))))))))))
948 ;; Compute the number of extra comment starter characters
949 ;; (extra semicolons in Lisp mode, extra stars in C mode, etc.)
950 ;; If ARG is non-nil, just follow ARG.
951 ;; If the comment-starter is multi-char, just follow ARG.
952 ;; Otherwise obey comment-add, and double it if EXTRA is non-nil.
953 (defun comment-add (arg)
954 (if (and (null arg) (= (string-match "[ \t]*\\'" comment-start) 1))
955 (* comment-add 1)
956 (1- (prefix-numeric-value arg))))
958 (defun comment-region-internal (beg end cs ce
959 &optional ccs cce block lines indent)
960 "Comment region BEG .. END.
961 CS and CE are the comment start string and comment end string,
962 respectively. CCS and CCE are the comment continuation strings
963 for the start and end of lines, respectively (default to CS and CE).
964 BLOCK indicates that end of lines should be marked with either CCE,
965 CE or CS \(if CE is empty) and that those markers should be aligned.
966 LINES indicates that an extra lines will be used at the beginning
967 and end of the region for CE and CS.
968 INDENT indicates to put CS and CCS at the current indentation of
969 the region rather than at left margin."
970 ;;(assert (< beg end))
971 (let ((no-empty (not (or (eq comment-empty-lines t)
972 (and comment-empty-lines (zerop (length ce))))))
973 ce-sanitized)
974 ;; Sanitize CE and CCE.
975 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
976 (setq ce-sanitized ce)
977 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
978 ;; If CE is empty, multiline cannot be used.
979 (unless ce (setq ccs nil cce nil))
980 ;; Should we mark empty lines as well ?
981 (if (or ccs block lines) (setq no-empty nil))
982 ;; Make sure we have end-markers for BLOCK mode.
983 (when block (unless ce (setq ce (comment-string-reverse cs))))
984 ;; If BLOCK is not requested, we don't need CCE.
985 (unless block (setq cce nil))
986 ;; Continuation defaults to the same as CS and CE.
987 (unless ccs (setq ccs cs cce ce))
989 (save-excursion
990 (goto-char end)
991 ;; If the end is not at the end of a line and the comment-end
992 ;; is implicit (i.e. a newline), explicitly insert a newline.
993 (unless (or ce-sanitized (eolp)) (insert "\n") (indent-according-to-mode))
994 (comment-with-narrowing beg end
995 (let ((min-indent (point-max))
996 (max-indent 0))
997 (goto-char (point-min))
998 ;; Quote any nested comment marker
999 (comment-quote-nested comment-start comment-end nil)
1001 ;; Loop over all lines to find the needed indentations.
1002 (goto-char (point-min))
1003 (while
1004 (progn
1005 (unless (looking-at "[ \t]*$")
1006 (setq min-indent (min min-indent (current-indentation))))
1007 (end-of-line)
1008 (setq max-indent (max max-indent (current-column)))
1009 (not (or (eobp) (progn (forward-line) nil)))))
1011 (setq max-indent
1012 (+ max-indent (max (length cs) (length ccs))
1013 ;; Inserting ccs can change max-indent by (1- tab-width)
1014 ;; but only if there are TABs in the boxed text, of course.
1015 (if (save-excursion (goto-char beg)
1016 (search-forward "\t" end t))
1017 (1- tab-width) 0)))
1018 (unless indent (setq min-indent 0))
1020 ;; make the leading and trailing lines if requested
1021 (when lines
1022 (let ((csce
1023 (comment-make-extra-lines
1024 cs ce ccs cce min-indent max-indent block)))
1025 (setq cs (car csce))
1026 (setq ce (cdr csce))))
1028 (goto-char (point-min))
1029 ;; Loop over all lines from BEG to END.
1030 (while
1031 (progn
1032 (unless (and no-empty (looking-at "[ \t]*$"))
1033 (move-to-column min-indent t)
1034 (insert cs) (setq cs ccs) ;switch to CCS after the first line
1035 (end-of-line)
1036 (if (eobp) (setq cce ce))
1037 (when cce
1038 (when block (move-to-column max-indent t))
1039 (insert cce)))
1040 (end-of-line)
1041 (not (or (eobp) (progn (forward-line) nil))))))))))
1043 ;;;###autoload
1044 (defun comment-region (beg end &optional arg)
1045 "Comment or uncomment each line in the region.
1046 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
1047 Numeric prefix ARG means use ARG comment characters.
1048 If ARG is negative, delete that many comment characters instead.
1049 By default, comments start at the left margin, are terminated on each line,
1050 even for syntax in which newline does not end the comment and blank lines
1051 do not get comments. This can be changed with `comment-style'.
1053 The strings used as comment starts are built from
1054 `comment-start' without trailing spaces and `comment-padding'."
1055 (interactive "*r\nP")
1056 (comment-normalize-vars)
1057 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
1058 (save-excursion
1059 ;; FIXME: maybe we should call uncomment depending on ARG.
1060 (funcall comment-region-function beg end arg)))
1062 (defun comment-region-default (beg end &optional arg)
1063 (let* ((numarg (prefix-numeric-value arg))
1064 (style (cdr (assoc comment-style comment-styles)))
1065 (lines (nth 2 style))
1066 (block (nth 1 style))
1067 (multi (nth 0 style)))
1069 ;; We use `chars' instead of `syntax' because `\n' might be
1070 ;; of end-comment syntax rather than of whitespace syntax.
1071 ;; sanitize BEG and END
1072 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
1073 (setq beg (max beg (point)))
1074 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
1075 (setq end (min end (point)))
1076 (if (>= beg end) (error "Nothing to comment"))
1078 ;; sanitize LINES
1079 (setq lines
1080 (and
1081 lines ;; multi
1082 (progn (goto-char beg) (beginning-of-line)
1083 (skip-syntax-forward " ")
1084 (>= (point) beg))
1085 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
1086 (<= (point) end))
1087 (or block (not (string= "" comment-end)))
1088 (or block (progn (goto-char beg) (search-forward "\n" end t)))))
1090 ;; don't add end-markers just because the user asked for `block'
1091 (unless (or lines (string= "" comment-end)) (setq block nil))
1093 (cond
1094 ((consp arg) (uncomment-region beg end))
1095 ((< numarg 0) (uncomment-region beg end (- numarg)))
1097 (let ((multi-char (/= (string-match "[ \t]*\\'" comment-start) 1))
1098 indent triple)
1099 (if (eq (nth 3 style) 'multi-char)
1100 (save-excursion
1101 (goto-char beg)
1102 (setq indent multi-char
1103 ;; Triple if we will put the comment starter at the margin
1104 ;; and the first line of the region isn't indented
1105 ;; at least two spaces.
1106 triple (and (not multi-char) (looking-at "\t\\| "))))
1107 (setq indent (nth 3 style)))
1109 ;; In Lisp and similar modes with one-character comment starters,
1110 ;; double it by default if `comment-add' says so.
1111 ;; If it isn't indented, triple it.
1112 (if (and (null arg) (not multi-char))
1113 (setq numarg (* comment-add (if triple 2 1)))
1114 (setq numarg (1- (prefix-numeric-value arg))))
1116 (comment-region-internal
1117 beg end
1118 (let ((s (comment-padright comment-start numarg)))
1119 (if (string-match comment-start-skip s) s
1120 (comment-padright comment-start)))
1121 (let ((s (comment-padleft comment-end numarg)))
1122 (and s (if (string-match comment-end-skip s) s
1123 (comment-padright comment-end))))
1124 (if multi (comment-padright comment-continue numarg))
1125 (if multi
1126 (comment-padleft (comment-string-reverse comment-continue) numarg))
1127 block
1128 lines
1129 indent))))))
1131 ;;;###autoload
1132 (defun comment-box (beg end &optional arg)
1133 "Comment out the BEG .. END region, putting it inside a box.
1134 The numeric prefix ARG specifies how many characters to add to begin- and
1135 end- comment markers additionally to what `comment-add' already specifies."
1136 (interactive "*r\np")
1137 (comment-normalize-vars)
1138 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
1139 'box-multi 'box)))
1140 (comment-region beg end (+ comment-add arg))))
1143 ;;;###autoload
1144 (defun comment-or-uncomment-region (beg end &optional arg)
1145 "Call `comment-region', unless the region only consists of comments,
1146 in which case call `uncomment-region'. If a prefix arg is given, it
1147 is passed on to the respective function."
1148 (interactive "*r\nP")
1149 (comment-normalize-vars)
1150 (funcall (if (save-excursion ;; check for already commented region
1151 (goto-char beg)
1152 (comment-forward (point-max))
1153 (<= end (point)))
1154 'uncomment-region 'comment-region)
1155 beg end arg))
1157 ;;;###autoload
1158 (defun comment-dwim (arg)
1159 "Call the comment command you want (Do What I Mean).
1160 If the region is active and `transient-mark-mode' is on, call
1161 `comment-region' (unless it only consists of comments, in which
1162 case it calls `uncomment-region').
1163 Else, if the current line is empty, call `comment-insert-comment-function'
1164 if it is defined, otherwise insert a comment and indent it.
1165 Else if a prefix ARG is specified, call `comment-kill'.
1166 Else, call `comment-indent'.
1167 You can configure `comment-style' to change the way regions are commented."
1168 (interactive "*P")
1169 (comment-normalize-vars)
1170 (if (and mark-active transient-mark-mode)
1171 (comment-or-uncomment-region (region-beginning) (region-end) arg)
1172 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
1173 ;; FIXME: If there's no comment to kill on this line and ARG is
1174 ;; specified, calling comment-kill is not very clever.
1175 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
1176 ;; Inserting a comment on a blank line. comment-indent calls
1177 ;; c-i-c-f if needed in the non-blank case.
1178 (if comment-insert-comment-function
1179 (funcall comment-insert-comment-function)
1180 (let ((add (comment-add arg)))
1181 ;; Some modes insist on keeping column 0 comment in column 0
1182 ;; so we need to move away from it before inserting the comment.
1183 (indent-according-to-mode)
1184 (insert (comment-padright comment-start add))
1185 (save-excursion
1186 (unless (string= "" comment-end)
1187 (insert (comment-padleft comment-end add)))
1188 (indent-according-to-mode)))))))
1190 ;;;###autoload
1191 (defcustom comment-auto-fill-only-comments nil
1192 "Non-nil means to only auto-fill inside comments.
1193 This has no effect in modes that do not define a comment syntax."
1194 :type 'boolean
1195 :group 'comment)
1197 (defun comment-valid-prefix-p (prefix compos)
1198 "Check that the adaptive-fill-prefix is consistent with the context.
1199 PREFIX is the prefix (presumably guessed by `adaptive-fill-mode').
1200 COMPOS is the position of the beginning of the comment we're in, or nil
1201 if we're not inside a comment."
1202 ;; This consistency checking is mostly needed to workaround the limitation
1203 ;; of auto-fill-mode whose paragraph-determination doesn't pay attention
1204 ;; to comment boundaries.
1205 (if (null compos)
1206 ;; We're not inside a comment: the prefix shouldn't match
1207 ;; a comment-starter.
1208 (not (and comment-start comment-start-skip
1209 (string-match comment-start-skip prefix)))
1211 ;; Accept any prefix if the current comment is not EOL-terminated.
1212 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1213 ;; Accept any prefix that starts with the same comment-start marker
1214 ;; as the current one.
1215 (when (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1216 prefix)
1217 (let ((prefix-com (comment-string-strip (match-string 0 prefix) nil t)))
1218 (string-match "\\`[ \t]*" prefix-com)
1219 (let* ((prefix-space (match-string 0 prefix-com))
1220 (prefix-indent (string-width prefix-space))
1221 (prefix-comstart (substring prefix-com (match-end 0))))
1222 (save-excursion
1223 (goto-char compos)
1224 ;; The comstart marker is the same.
1225 (and (looking-at (regexp-quote prefix-comstart))
1226 ;; The indentation as well.
1227 (or (= prefix-indent
1228 (- (current-column) (current-left-margin)))
1229 ;; Check the indentation in two different ways, just
1230 ;; to try and avoid most of the potential funny cases.
1231 (equal prefix-space
1232 (buffer-substring (point)
1233 (progn (move-to-left-margin)
1234 (point)))))))))))))
1237 ;;;###autoload
1238 (defun comment-indent-new-line (&optional soft)
1239 "Break line at point and indent, continuing comment if within one.
1240 This indents the body of the continued comment
1241 under the previous comment line.
1243 This command is intended for styles where you write a comment per line,
1244 starting a new comment (and terminating it if necessary) on each line.
1245 If you want to continue one comment across several lines, use \\[newline-and-indent].
1247 If a fill column is specified, it overrides the use of the comment column
1248 or comment indentation.
1250 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1251 unless optional argument SOFT is non-nil."
1252 (interactive)
1253 (comment-normalize-vars t)
1254 (let (compos comin)
1255 ;; If we are not inside a comment and we only auto-fill comments,
1256 ;; don't do anything (unless no comment syntax is defined).
1257 (unless (and comment-start
1258 comment-auto-fill-only-comments
1259 (not (interactive-p))
1260 (not (save-excursion
1261 (prog1 (setq compos (comment-beginning))
1262 (setq comin (point))))))
1264 ;; Now we know we should auto-fill.
1265 ;; Insert the newline before removing empty space so that markers
1266 ;; get preserved better.
1267 (if soft (insert-and-inherit ?\n) (newline 1))
1268 (save-excursion (forward-char -1) (delete-horizontal-space))
1269 (delete-horizontal-space)
1271 (if (and fill-prefix (not adaptive-fill-mode))
1272 ;; Blindly trust a non-adaptive fill-prefix.
1273 (progn
1274 (indent-to-left-margin)
1275 (insert-before-markers-and-inherit fill-prefix))
1277 ;; If necessary check whether we're inside a comment.
1278 (unless (or compos (null comment-start))
1279 (save-excursion
1280 (backward-char)
1281 (setq compos (comment-beginning))
1282 (setq comin (point))))
1284 (cond
1285 ;; If there's an adaptive prefix, use it unless we're inside
1286 ;; a comment and the prefix is not a comment starter.
1287 ((and fill-prefix
1288 (comment-valid-prefix-p fill-prefix compos))
1289 (indent-to-left-margin)
1290 (insert-and-inherit fill-prefix))
1291 ;; If we're not inside a comment, just try to indent.
1292 ((not compos) (indent-according-to-mode))
1294 (let* ((comment-column
1295 ;; The continuation indentation should be somewhere between
1296 ;; the current line's indentation (plus 2 for good measure)
1297 ;; and the current comment's indentation, with a preference
1298 ;; for comment-column.
1299 (save-excursion
1300 ;; FIXME: use prev line's info rather than first line's.
1301 (goto-char compos)
1302 (min (current-column) (max comment-column
1303 (+ 2 (current-indentation))))))
1304 (comstart (buffer-substring compos comin))
1305 (normalp
1306 (string-match (regexp-quote (comment-string-strip
1307 comment-start t t))
1308 comstart))
1309 (comment-end
1310 (if normalp comment-end
1311 ;; The comment starter is not the normal comment-start
1312 ;; so we can't just use comment-end.
1313 (save-excursion
1314 (goto-char compos)
1315 (if (not (comment-forward)) comment-end
1316 (comment-string-strip
1317 (buffer-substring
1318 (save-excursion (comment-enter-backward) (point))
1319 (point))
1320 nil t)))))
1321 (comment-start comstart)
1322 (continuep (or comment-multi-line
1323 (cadr (assoc comment-style comment-styles))))
1324 ;; Force comment-continue to be recreated from comment-start.
1325 ;; FIXME: wrong if comment-continue was set explicitly!
1326 ;; FIXME: use prev line's continuation if available.
1327 (comment-continue nil))
1328 (if (and comment-multi-line (> (length comment-end) 0))
1329 (indent-according-to-mode)
1330 (insert-and-inherit ?\n)
1331 (forward-char -1)
1332 (comment-indent continuep)
1333 (save-excursion
1334 (let ((pt (point)))
1335 (end-of-line)
1336 (let ((comend (buffer-substring pt (point))))
1337 ;; The 1+ is to make sure we delete the \n inserted above.
1338 (delete-region pt (1+ (point)))
1339 (end-of-line 0)
1340 (insert comend))))))))))))
1342 (provide 'newcomment)
1344 ;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
1345 ;;; newcomment.el ends here