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