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