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