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