(insert-directory): Preserve CR in a file name.
[emacs.git] / lisp / newcomment.el
blobd7067184539481c68928d2be09e3c9b73607dea9
1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999,2000,2003 Free Software Foundation Inc.
5 ;; Author: code extracted from Emacs-20's simple.el
6 ;; Maintainer: Stefan Monnier <monnier@cs.yale.edu>
7 ;; Keywords: comment uncomment
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;; A replacement for simple.el's comment-related functions.
30 ;;; Bugs:
32 ;; - boxed comments in Perl are not properly uncommented because they are
33 ;; uncommented one-line at a time.
34 ;; - nested comments in sgml-mode are not properly quoted.
35 ;; - single-char nestable comment-start can only do the "\\s<+" stuff
36 ;; if the corresponding closing marker happens to be right.
37 ;; - uncomment-region with a numeric argument can render multichar
38 ;; comment markers invalid.
39 ;; - comment-indent or comment-region when called inside a comment
40 ;; will happily break the surrounding comment.
41 ;; - comment-quote-nested will not (un)quote properly all nested comment
42 ;; markers if there are more than just comment-start and comment-end.
43 ;; For example, in Pascal where {...*) and (*...} are possible.
45 ;;; Todo:
47 ;; - rebox.el-style refill.
48 ;; - quantized steps in comment-alignment.
49 ;; - try to align tail comments.
50 ;; - check what c-comment-line-break-function has to say.
51 ;; - spill auto-fill of comments onto the end of the next line.
52 ;; - uncomment-region with a consp (for blocks) or somehow make the
53 ;; deletion of continuation markers less dangerous.
54 ;; - drop block-comment-<foo> unless it's really used.
55 ;; - uncomment-region on a subpart of a comment.
56 ;; - support gnu-style "multi-line with space in continue".
57 ;; - somehow allow comment-dwim to use the region even if transient-mark-mode
58 ;; is not turned on.
60 ;; - when auto-filling a comment, try to move the comment to the left
61 ;; rather than break it (if possible).
62 ;; - sometimes default the comment-column to the same
63 ;; one used on the preceding line(s).
65 ;;; Code:
67 ;;;###autoload
68 (defalias 'indent-for-comment 'comment-indent)
69 ;;;###autoload
70 (defalias 'set-comment-column 'comment-set-column)
71 ;;;###autoload
72 (defalias 'kill-comment 'comment-kill)
73 ;;;###autoload
74 (defalias 'indent-new-comment-line 'comment-indent-new-line)
76 (defgroup comment nil
77 "Indenting and filling of comments."
78 :prefix "comment-"
79 :version "21.1"
80 :group 'fill)
82 ;; Autoload this to avoid warnings, since some major modes define it.
83 ;;;###autoload
84 (defvar comment-use-syntax 'undecided
85 "Non-nil if syntax-tables can be used instead of regexps.
86 Can also be `undecided' which means that a somewhat expensive test will
87 be used to try to determine whether syntax-tables should be trusted
88 to understand comments or not in the given buffer.
89 Major modes should set this variable.")
91 (defcustom comment-fill-column nil
92 "Column to use for `comment-indent'. If nil, use `fill-column' instead."
93 :type '(choice (const nil) integer))
95 ;;;###autoload
96 (defcustom comment-column 32
97 "*Column to indent right-margin comments to.
98 Each mode establishes 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 value smaller than this in order
101 not to go beyond `comment-fill-column'."
102 :type 'integer)
103 (make-variable-buffer-local 'comment-column)
105 ;;;###autoload
106 (defvar comment-start nil
107 "*String to insert to start a new comment, or nil if no comment syntax.")
109 ;;;###autoload
110 (defvar comment-start-skip nil
111 "*Regexp to match the start of a comment plus everything up to its body.
112 If there are any \\(...\\) pairs, the comment delimiter text is held to begin
113 at the place matched by the close of the first pair.")
115 ;;;###autoload
116 (defvar comment-end-skip nil
117 "Regexp to match the end of a comment plus everything up to its body.")
119 ;;;###autoload
120 (defvar comment-end ""
121 "*String to insert to end a new comment.
122 Should be an empty string if comments are terminated by end-of-line.")
124 ;;;###autoload
125 (defvar comment-indent-function 'comment-indent-default
126 "Function to compute desired indentation for a comment.
127 This function is called with no args with point at the beginning of
128 the comment's starting delimiter and should return either the desired
129 column indentation or nil.
130 If nil is returned, indentation is delegated to `indent-according-to-mode'.")
132 (defvar block-comment-start nil)
133 (defvar block-comment-end nil)
135 (defvar comment-quote-nested t
136 "Non-nil if nested comments should be quoted.
137 This should be locally set by each major mode if needed.")
139 (defvar comment-continue nil
140 "Continuation string to insert for multiline comments.
141 This string will be added at the beginning of each line except the very
142 first one when commenting a region with a commenting style that allows
143 comments to span several lines.
144 It should generally have the same length as `comment-start' in order to
145 preserve indentation.
146 If it is nil a value will be automatically derived from `comment-start'
147 by replacing its first character with a space.")
149 (defvar comment-add 0
150 "How many more comment chars should be inserted by `comment-region'.
151 This determines the default value of the numeric argument of `comment-region'.
152 This should generally stay 0, except for a few modes like Lisp where
153 it can be convenient to set it to 1 so that regions are commented with
154 two semi-colons.")
156 (defconst comment-styles
157 '((plain . (nil nil nil nil))
158 (indent . (nil nil nil t))
159 (aligned . (nil t nil t))
160 (multi-line . (t nil nil t))
161 (extra-line . (t nil t t))
162 (box . (nil t t t))
163 (box-multi . (t t t t)))
164 "Possible comment styles of the form (STYLE . (MULTI ALIGN EXTRA INDENT)).
165 STYLE should be a mnemonic symbol.
166 MULTI specifies that comments are allowed to span multiple lines.
167 ALIGN specifies that the `comment-end' markers should be aligned.
168 EXTRA specifies that an extra line should be used before and after the
169 region to comment (to put the `comment-end' and `comment-start').
170 INDENT specifies that the `comment-start' markers should not be put at the
171 left margin but at the current indentation of the region to comment.")
173 ;;;###autoload
174 (defcustom comment-style 'plain
175 "*Style to be used for `comment-region'.
176 See `comment-styles' for a list of available styles."
177 :type (if (boundp 'comment-styles)
178 `(choice ,@(mapcar (lambda (s) `(const ,(car s))) comment-styles))
179 'symbol))
181 ;;;###autoload
182 (defcustom comment-padding " "
183 "Padding string that `comment-region' puts between comment chars and text.
184 Can also be an integer which will be automatically turned into a string
185 of the corresponding number of spaces.
187 Extra spacing between the comment characters and the comment text
188 makes the comment easier to read. Default is 1. nil means 0."
189 :type '(choice string integer (const nil)))
191 ;;;###autoload
192 (defcustom comment-multi-line nil
193 "*Non-nil means \\[comment-indent-new-line] continues comments, with no new terminator or starter.
194 This is obsolete because you might as well use \\[newline-and-indent]."
195 :type 'boolean)
197 ;;;;
198 ;;;; Helpers
199 ;;;;
201 (defun comment-string-strip (str beforep afterp)
202 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
203 (string-match (concat "\\`" (if beforep "\\s-*")
204 "\\(.*?\\)" (if afterp "\\s-*\n?")
205 "\\'") str)
206 (match-string 1 str))
208 (defun comment-string-reverse (s)
209 "Return the mirror image of string S, without any trailing space."
210 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
212 ;;;###autoload
213 (defun comment-normalize-vars (&optional noerror)
214 "Check and setup the variables needed by other commenting functions.
215 Functions autoloaded from newcomment.el, being entry points, should call
216 this function before any other, so the rest of the code can assume that
217 the variables are properly set."
218 (if (not comment-start)
219 (unless noerror
220 (set (make-local-variable 'comment-start)
221 (read-string "No comment syntax is defined. Use: ")))
222 ;; comment-use-syntax
223 (when (eq comment-use-syntax 'undecided)
224 (set (make-local-variable 'comment-use-syntax)
225 (let ((st (syntax-table))
226 (cs comment-start)
227 (ce (if (string= "" comment-end) "\n" comment-end)))
228 ;; Try to skip over a comment using forward-comment
229 ;; to see if the syntax tables properly recognize it.
230 (with-temp-buffer
231 (set-syntax-table st)
232 (insert cs " hello " ce)
233 (goto-char (point-min))
234 (and (forward-comment 1) (eobp))))))
235 ;; comment-padding
236 (unless comment-padding (setq comment-padding 0))
237 (when (integerp comment-padding)
238 (setq comment-padding (make-string comment-padding ? )))
239 ;; comment markers
240 ;;(setq comment-start (comment-string-strip comment-start t nil))
241 ;;(setq comment-end (comment-string-strip comment-end nil t))
242 ;; comment-continue
243 (unless (or comment-continue (string= comment-end ""))
244 (set (make-local-variable 'comment-continue)
245 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
246 (substring comment-start 1)))
247 ;; Hasn't been necessary yet.
248 ;; (unless (string-match comment-start-skip comment-continue)
249 ;; (kill-local-variable 'comment-continue))
251 ;; comment-skip regexps
252 (unless (and comment-start-skip
253 ;; In case comment-start has changed since last time.
254 (string-match comment-start-skip comment-start))
255 (set (make-local-variable 'comment-start-skip)
256 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
257 (regexp-quote (comment-string-strip comment-start t t))
258 ;; Let's not allow any \s- but only [ \t] since \n
259 ;; might be both a comment-end marker and \s-.
260 "+\\)[ \t]*")))
261 (unless (and comment-end-skip
262 ;; In case comment-end has changed since last time.
263 (string-match comment-end-skip comment-end))
264 (let ((ce (if (string= "" comment-end) "\n"
265 (comment-string-strip comment-end t t))))
266 (set (make-local-variable 'comment-end-skip)
267 ;; We use [ \t] rather than \s- because we don't want to
268 ;; remove ^L in C mode when uncommenting.
269 (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
270 "\\|" (regexp-quote (substring ce 0 1))
271 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
272 (regexp-quote (substring ce 1))
273 "\\)"))))))
275 (defun comment-quote-re (str unp)
276 (concat (regexp-quote (substring str 0 1))
277 "\\\\" (if unp "+" "*")
278 (regexp-quote (substring str 1))))
280 (defun comment-quote-nested (cs ce unp)
281 "Quote or unquote nested comments.
282 If UNP is non-nil, unquote nested comment markers."
283 (setq cs (comment-string-strip cs t t))
284 (setq ce (comment-string-strip ce t t))
285 (when (and comment-quote-nested (> (length ce) 0))
286 (let ((re (concat (comment-quote-re ce unp)
287 "\\|" (comment-quote-re cs unp))))
288 (goto-char (point-min))
289 (while (re-search-forward re nil t)
290 (goto-char (match-beginning 0))
291 (forward-char 1)
292 (if unp (delete-char 1) (insert "\\"))
293 (when (= (length ce) 1)
294 ;; If the comment-end is a single char, adding a \ after that
295 ;; "first" char won't deactivate it, so we turn such a CE
296 ;; into !CS. I.e. for pascal, we turn } into !{
297 (if (not unp)
298 (when (string= (match-string 0) ce)
299 (replace-match (concat "!" cs) t t))
300 (when (and (< (point-min) (match-beginning 0))
301 (string= (buffer-substring (1- (match-beginning 0))
302 (1- (match-end 0)))
303 (concat "!" cs)))
304 (backward-char 2)
305 (delete-char (- (match-end 0) (match-beginning 0)))
306 (insert ce))))))))
308 ;;;;
309 ;;;; Navigation
310 ;;;;
312 (defun comment-search-forward (limit &optional noerror)
313 "Find a comment start between point and LIMIT.
314 Moves point to inside the comment and returns the position of the
315 comment-starter. If no comment is found, moves point to LIMIT
316 and raises an error or returns nil of NOERROR is non-nil."
317 (if (not comment-use-syntax)
318 (if (re-search-forward comment-start-skip limit noerror)
319 (or (match-end 1) (match-beginning 0))
320 (goto-char limit)
321 (unless noerror (error "No comment")))
322 (let* ((pt (point))
323 ;; Assume (at first) that pt is outside of any string.
324 (s (parse-partial-sexp pt (or limit (point-max)) nil nil nil t)))
325 (when (and (nth 8 s) (nth 3 s))
326 ;; The search ended inside a string. Try to see if it
327 ;; works better when we assume that pt is inside a string.
328 (setq s (parse-partial-sexp
329 pt (or limit (point-max)) nil nil
330 (list nil nil nil (nth 3 s) nil nil nil nil)
331 t)))
332 (if (not (and (nth 8 s) (not (nth 3 s))))
333 (unless noerror (error "No comment"))
334 ;; We found the comment.
335 (let ((pos (point))
336 (start (nth 8 s))
337 (bol (line-beginning-position))
338 (end nil))
339 (while (and (null end) (>= (point) bol))
340 (if (looking-at comment-start-skip)
341 (setq end (min (or limit (point-max)) (match-end 0)))
342 (backward-char)))
343 (goto-char (or end pos))
344 start)))))
346 (defun comment-search-backward (&optional limit noerror)
347 "Find a comment start between LIMIT and point.
348 Moves point to inside the comment and returns the position of the
349 comment-starter. If no comment is found, moves point to LIMIT
350 and raises an error or returns nil of NOERROR is non-nil."
351 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
352 ;; stop there. This can be rather bad in general, but since
353 ;; comment-search-backward is only used to find the comment-column (in
354 ;; comment-set-column) and to find the comment-start string (via
355 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
356 (if (not (re-search-backward comment-start-skip limit t))
357 (unless noerror (error "No comment"))
358 (beginning-of-line)
359 (let* ((end (match-end 0))
360 (cs (comment-search-forward end t))
361 (pt (point)))
362 (if (not cs)
363 (progn (beginning-of-line)
364 (comment-search-backward limit noerror))
365 (while (progn (goto-char cs)
366 (comment-forward)
367 (and (< (point) end)
368 (setq cs (comment-search-forward end t))))
369 (setq pt (point)))
370 (goto-char pt)
371 cs))))
373 (defun comment-beginning ()
374 "Find the beginning of the enclosing comment.
375 Returns nil if not inside a comment, else moves point and returns
376 the same as `comment-search-forward'."
377 ;; HACK ATTACK!
378 ;; We should really test `in-string-p' but that can be expensive.
379 (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
380 (let ((pt (point))
381 (cs (comment-search-backward nil t)))
382 (when cs
383 (if (save-excursion
384 (goto-char cs)
385 (and
386 ;; For modes where comment-start and comment-end are the same,
387 ;; the search above may have found a `ce' rather than a `cs'.
388 (or (not (looking-at comment-end-skip))
389 ;; Maybe font-lock knows that it's a `cs'?
390 (eq (get-text-property (match-end 0) 'face)
391 'font-lock-comment-face)
392 (unless (eq (get-text-property (point) 'face)
393 'font-lock-comment-face)
394 ;; Let's assume it's a `cs' if we're on the same line.
395 (>= (line-end-position) pt)))
396 ;; Make sure that PT is not past the end of the comment.
397 (if (comment-forward 1) (> (point) pt) (eobp))))
399 (goto-char pt)
400 nil)))))
402 (defun comment-forward (&optional n)
403 "Skip forward over N comments.
404 Just like `forward-comment' but only for positive N
405 and can use regexps instead of syntax."
406 (setq n (or n 1))
407 (if (< n 0) (error "No comment-backward")
408 (if comment-use-syntax (forward-comment n)
409 (while (> n 0)
410 (setq n
411 (if (or (forward-comment 1)
412 (and (looking-at comment-start-skip)
413 (goto-char (match-end 0))
414 (re-search-forward comment-end-skip nil 'move)))
415 (1- n) -1)))
416 (= n 0))))
418 (defun comment-enter-backward ()
419 "Move from the end of a comment to the end of its content.
420 Point is assumed to be just at the end of a comment."
421 (if (bolp)
422 ;; comment-end = ""
423 (progn (backward-char) (skip-syntax-backward " "))
424 (let ((end (point)))
425 (beginning-of-line)
426 (save-restriction
427 (narrow-to-region (point) end)
428 (if (re-search-forward (concat comment-end-skip "\\'") nil t)
429 (goto-char (match-beginning 0))
430 ;; comment-end-skip not found probably because it was not set right.
431 ;; Since \\s> should catch the single-char case, we'll blindly
432 ;; assume we're at the end of a two-char comment-end.
433 (goto-char (point-max))
434 (backward-char 2)
435 (skip-chars-backward (string (char-after)))
436 (skip-syntax-backward " "))))))
438 ;;;;
439 ;;;; Commands
440 ;;;;
442 ;;;###autoload
443 (defun comment-indent-default ()
444 "Default for `comment-indent-function'."
445 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
446 (or (match-end 1) (/= (current-column) (current-indentation))))
448 (when (or (/= (current-column) (current-indentation))
449 (and (> comment-add 0) (looking-at "\\s<\\S<")))
450 comment-column)))
452 ;;;###autoload
453 (defun comment-indent (&optional continue)
454 "Indent this line's comment to comment column, or insert an empty comment.
455 If CONTINUE is non-nil, use the `comment-continue' markers if any."
456 (interactive "*")
457 (comment-normalize-vars)
458 (let* ((empty (save-excursion (beginning-of-line)
459 (looking-at "[ \t]*$")))
460 (starter (or (and continue comment-continue)
461 (and empty block-comment-start) comment-start))
462 (ender (or (and continue comment-continue "")
463 (and empty block-comment-end) comment-end)))
464 (unless starter (error "No comment syntax defined"))
465 (beginning-of-line)
466 (let* ((eolpos (line-end-position))
467 (begpos (comment-search-forward eolpos t))
468 cpos indent)
469 ;; An existing comment?
470 (if begpos
471 (progn
472 (if (and (not (looking-at "[\t\n ]"))
473 (looking-at comment-end-skip))
474 ;; The comment is empty and we have skipped all its space
475 ;; and landed right before the comment-ender:
476 ;; Go back to the middle of the space.
477 (forward-char (/ (skip-chars-backward " \t") -2)))
478 (setq cpos (point-marker)))
479 ;; If none, insert one.
480 (save-excursion
481 ;; Some comment-indent-function insist on not moving comments that
482 ;; are in column 0, so we first go to the likely target column.
483 (indent-to comment-column)
484 ;; Ensure there's a space before the comment for things
485 ;; like sh where it matters (as well as being neater).
486 (unless (memq (char-before) '(nil ?\n ?\t ?\ ))
487 (insert ?\ ))
488 (setq begpos (point))
489 (insert starter)
490 (setq cpos (point-marker))
491 (insert ender)))
492 (goto-char begpos)
493 ;; Compute desired indent.
494 (setq indent (save-excursion (funcall comment-indent-function)))
495 (if (not indent)
496 ;; comment-indent-function refuses: delegate to line-indent.
497 (indent-according-to-mode)
498 ;; Avoid moving comments past the fill-column.
499 (unless (save-excursion (skip-chars-backward " \t") (bolp))
500 (let ((max (+ (current-column)
501 (- (or comment-fill-column fill-column)
502 (save-excursion (end-of-line) (current-column))))))
503 (if (<= max indent)
504 (setq indent max) ;Don't move past the fill column.
505 ;; We can choose anywhere between indent..max.
506 ;; Let's try to align to a comment on the previous line.
507 (let ((other nil))
508 (save-excursion
509 (when (and (zerop (forward-line -1))
510 (setq other (comment-search-forward
511 (line-end-position) t)))
512 (goto-char other) (setq other (current-column))))
513 (if (and other (<= other max) (> other indent))
514 ;; There is a comment and it's in the range: bingo.
515 (setq indent other)
516 ;; Let's try to align to a comment on the next line, then.
517 (let ((other nil))
518 (save-excursion
519 (when (and (zerop (forward-line 1))
520 (setq other (comment-search-forward
521 (line-end-position) t)))
522 (goto-char other) (setq other (current-column))))
523 (if (and other (<= other max) (> other indent))
524 ;; There is a comment and it's in the range: bingo.
525 (setq indent other))))))))
526 (unless (= (current-column) indent)
527 ;; If that's different from current, change it.
528 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
529 (indent-to (if (bolp) indent
530 (max indent (1+ (current-column)))))))
531 (goto-char cpos)
532 (set-marker cpos nil))))
534 ;;;###autoload
535 (defun comment-set-column (arg)
536 "Set the comment column based on point.
537 With no ARG, set the comment column to the current column.
538 With just minus as arg, kill any comment on this line.
539 With any other arg, set comment column to indentation of the previous comment
540 and then align or create a comment on this line at that column."
541 (interactive "P")
542 (cond
543 ((eq arg '-) (comment-kill nil))
544 (arg
545 (comment-normalize-vars)
546 (save-excursion
547 (beginning-of-line)
548 (comment-search-backward)
549 (beginning-of-line)
550 (goto-char (comment-search-forward (line-end-position)))
551 (setq comment-column (current-column))
552 (message "Comment column set to %d" comment-column))
553 (comment-indent))
554 (t (setq comment-column (current-column))
555 (message "Comment column set to %d" comment-column))))
557 ;;;###autoload
558 (defun comment-kill (arg)
559 "Kill the comment on this line, if any.
560 With prefix ARG, kill comments on that many lines starting with this one."
561 (interactive "P")
562 (comment-normalize-vars)
563 (dotimes (_ (prefix-numeric-value arg))
564 (save-excursion
565 (beginning-of-line)
566 (let ((cs (comment-search-forward (line-end-position) t)))
567 (when cs
568 (goto-char cs)
569 (skip-syntax-backward " ")
570 (setq cs (point))
571 (comment-forward)
572 (kill-region cs (if (bolp) (1- (point)) (point)))
573 (indent-according-to-mode))))
574 (if arg (forward-line 1))))
576 (defun comment-padright (str &optional n)
577 "Construct a string composed of STR plus `comment-padding'.
578 It also adds N copies of the last non-whitespace chars of STR.
579 If STR already contains padding, the corresponding amount is
580 ignored from `comment-padding'.
581 N defaults to 0.
582 If N is `re', a regexp is returned instead, that would match
583 the string for any N."
584 (setq n (or n 0))
585 (when (and (stringp str) (not (string= "" str)))
586 ;; Separate the actual string from any leading/trailing padding
587 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
588 (let ((s (match-string 1 str)) ;actual string
589 (lpad (substring str 0 (match-beginning 1))) ;left padding
590 (rpad (concat (substring str (match-end 1)) ;original right padding
591 (substring comment-padding ;additional right padding
592 (min (- (match-end 0) (match-end 1))
593 (length comment-padding)))))
594 ;; We can only duplicate C if the comment-end has multiple chars
595 ;; or if comments can be nested, else the comment-end `}' would
596 ;; be turned into `}}}' where only the first ends the comment
597 ;; and the rest becomes bogus junk.
598 (multi (not (and comment-quote-nested
599 ;; comment-end is a single char
600 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
601 (if (not (symbolp n))
602 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
603 ;; construct a regexp that would match anything from just S
604 ;; to any possible output of this function for any N.
605 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
606 lpad "") ;padding is not required
607 (regexp-quote s)
608 (when multi "+") ;the last char of S might be repeated
609 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
610 rpad "")))))) ;padding is not required
612 (defun comment-padleft (str &optional n)
613 "Construct a string composed of `comment-padding' plus STR.
614 It also adds N copies of the first non-whitespace chars of STR.
615 If STR already contains padding, the corresponding amount is
616 ignored from `comment-padding'.
617 N defaults to 0.
618 If N is `re', a regexp is returned instead, that would match
619 the string for any N."
620 (setq n (or n 0))
621 (when (and (stringp str) (not (string= "" str)))
622 ;; Only separate the left pad because we assume there is no right pad.
623 (string-match "\\`\\s-*" str)
624 (let ((s (substring str (match-end 0)))
625 (pad (concat (substring comment-padding
626 (min (- (match-end 0) (match-beginning 0))
627 (length comment-padding)))
628 (match-string 0 str)))
629 (c (aref str (match-end 0))) ;the first non-space char of STR
630 ;; We can only duplicate C if the comment-end has multiple chars
631 ;; or if comments can be nested, else the comment-end `}' would
632 ;; be turned into `}}}' where only the first ends the comment
633 ;; and the rest becomes bogus junk.
634 (multi (not (and comment-quote-nested
635 ;; comment-end is a single char
636 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
637 (if (not (symbolp n))
638 (concat pad (when multi (make-string n c)) s)
639 ;; Construct a regexp that would match anything from just S
640 ;; to any possible output of this function for any N.
641 ;; We match any number of leading spaces because this regexp will
642 ;; be used for uncommenting where we might want to remove
643 ;; uncomment markers with arbitrary leading space (because
644 ;; they were aligned).
645 (concat "\\s-*"
646 (if multi (concat (regexp-quote (string c)) "*"))
647 (regexp-quote s))))))
649 ;;;###autoload
650 (defun uncomment-region (beg end &optional arg)
651 "Uncomment each line in the BEG .. END region.
652 The numeric prefix ARG can specify a number of chars to remove from the
653 comment markers."
654 (interactive "*r\nP")
655 (comment-normalize-vars)
656 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
657 (save-excursion
658 (goto-char beg)
659 (setq end (copy-marker end))
660 (let* ((numarg (prefix-numeric-value arg))
661 (ccs comment-continue)
662 (srei (comment-padright ccs 're))
663 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
664 spt)
665 (while (and (< (point) end)
666 (setq spt (comment-search-forward end t)))
667 (let ((ipt (point))
668 ;; Find the end of the comment.
669 (ept (progn
670 (goto-char spt)
671 (unless (comment-forward)
672 (error "Can't find the comment end"))
673 (point)))
674 (box nil)
675 (box-equal nil)) ;Whether we might be using `=' for boxes.
676 (save-restriction
677 (narrow-to-region spt ept)
679 ;; Remove the comment-start.
680 (goto-char ipt)
681 (skip-syntax-backward " ")
682 ;; A box-comment starts with a looong comment-start marker.
683 (when (and (or (and (= (- (point) (point-min)) 1)
684 (setq box-equal t)
685 (looking-at "=\\{7\\}")
686 (not (eq (char-before (point-max)) ?\n))
687 (skip-chars-forward "="))
688 (> (- (point) (point-min) (length comment-start)) 7))
689 (> (count-lines (point-min) (point-max)) 2))
690 (setq box t))
691 (when (looking-at (regexp-quote comment-padding))
692 (goto-char (match-end 0)))
693 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
694 (goto-char (match-end 0)))
695 (if (null arg) (delete-region (point-min) (point))
696 (skip-syntax-backward " ")
697 (delete-char (- numarg))
698 (unless (or (bobp)
699 (save-excursion (goto-char (point-min))
700 (looking-at comment-start-skip)))
701 ;; If there's something left but it doesn't look like
702 ;; a comment-start any more, just remove it.
703 (delete-region (point-min) (point))))
705 ;; Remove the end-comment (and leading padding and such).
706 (goto-char (point-max)) (comment-enter-backward)
707 ;; Check for special `=' used sometimes in comment-box.
708 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
709 (let ((pos (point)))
710 ;; skip `=' but only if there are at least 7.
711 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
712 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
713 (when (and (bolp) (not (bobp))) (backward-char))
714 (if (null arg) (delete-region (point) (point-max))
715 (skip-syntax-forward " ")
716 (delete-char numarg)
717 (unless (or (eobp) (looking-at comment-end-skip))
718 ;; If there's something left but it doesn't look like
719 ;; a comment-end any more, just remove it.
720 (delete-region (point) (point-max)))))
722 ;; Unquote any nested end-comment.
723 (comment-quote-nested comment-start comment-end t)
725 ;; Eliminate continuation markers as well.
726 (when sre
727 (let* ((cce (comment-string-reverse (or comment-continue
728 comment-start)))
729 (erei (and box (comment-padleft cce 're)))
730 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
731 (goto-char (point-min))
732 (while (progn
733 (if (and ere (re-search-forward
734 ere (line-end-position) t))
735 (replace-match "" t t nil (if (match-end 2) 2 1))
736 (setq ere nil))
737 (forward-line 1)
738 (re-search-forward sre (line-end-position) t))
739 (replace-match "" t t nil (if (match-end 2) 2 1)))))
740 ;; Go to the end for the next comment.
741 (goto-char (point-max)))))
742 (set-marker end nil))))
744 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
745 "Make the leading and trailing extra lines.
746 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
747 (let ((eindent 0))
748 (if (not block)
749 ;; Try to match CS and CE's content so they align aesthetically.
750 (progn
751 (setq ce (comment-string-strip ce t t))
752 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
753 (setq eindent
754 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
755 0))))
756 ;; box comment
757 (let* ((width (- max-indent min-indent))
758 (s (concat cs "a=m" cce))
759 (e (concat ccs "a=m" ce))
760 (c (if (string-match ".*\\S-\\S-" cs)
761 (aref cs (1- (match-end 0)))
762 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
763 (aref cs (1- (match-end 0))) ?=)))
764 (re "\\s-*a=m\\s-*")
765 (_ (string-match re s))
766 (lcs (length cs))
767 (fill
768 (make-string (+ width (- (match-end 0)
769 (match-beginning 0) lcs 3)) c)))
770 (setq cs (replace-match fill t t s))
771 (when (and (not (string-match comment-start-skip cs))
772 (string-match "a=m" s))
773 ;; The whitespace around CS cannot be ignored: put it back.
774 (setq re "a=m")
775 (setq fill (make-string (- width lcs) c))
776 (setq cs (replace-match fill t t s)))
777 (string-match re e)
778 (setq ce (replace-match fill t t e))))
779 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
780 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
782 (defmacro comment-with-narrowing (beg end &rest body)
783 "Execute BODY with BEG..END narrowing.
784 Space is added (and then removed) at the beginning for the text's
785 indentation to be kept as it was before narrowing."
786 (declare (debug t) (indent 2))
787 (let ((bindent (make-symbol "bindent")))
788 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
789 (save-restriction
790 (narrow-to-region ,beg ,end)
791 (goto-char (point-min))
792 (insert (make-string ,bindent ? ))
793 (prog1
794 (progn ,@body)
795 ;; remove the bindent
796 (save-excursion
797 (goto-char (point-min))
798 (when (looking-at " *")
799 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
800 (delete-char n)
801 (setq ,bindent (- ,bindent n))))
802 (end-of-line)
803 (let ((e (point)))
804 (beginning-of-line)
805 (while (and (> ,bindent 0) (re-search-forward " *" e t))
806 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
807 (goto-char (match-beginning 0))
808 (delete-char n)
809 (setq ,bindent (- ,bindent n)))))))))))
811 (defun comment-region-internal (beg end cs ce
812 &optional ccs cce block lines indent)
813 "Comment region BEG .. END.
814 CS and CE are the comment start resp end string.
815 CCS and CCE are the comment continuation strings for the start resp end
816 of lines (default to CS and CE).
817 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
818 \(if CE is empty) and that those markers should be aligned.
819 LINES indicates that an extra lines will be used at the beginning and end
820 of the region for CE and CS.
821 INDENT indicates to put CS and CCS at the current indentation of the region
822 rather than at left margin."
823 ;;(assert (< beg end))
824 (let ((no-empty t))
825 ;; Sanitize CE and CCE.
826 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
827 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
828 ;; If CE is empty, multiline cannot be used.
829 (unless ce (setq ccs nil cce nil))
830 ;; Should we mark empty lines as well ?
831 (if (or ccs block lines) (setq no-empty nil))
832 ;; Make sure we have end-markers for BLOCK mode.
833 (when block (unless ce (setq ce (comment-string-reverse cs))))
834 ;; If BLOCK is not requested, we don't need CCE.
835 (unless block (setq cce nil))
836 ;; Continuation defaults to the same as CS and CE.
837 (unless ccs (setq ccs cs cce ce))
839 (save-excursion
840 (goto-char end)
841 ;; If the end is not at the end of a line and the comment-end
842 ;; is implicit (i.e. a newline), explicitly insert a newline.
843 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
844 (comment-with-narrowing beg end
845 (let ((min-indent (point-max))
846 (max-indent 0))
847 (goto-char (point-min))
848 ;; Quote any nested comment marker
849 (comment-quote-nested comment-start comment-end nil)
851 ;; Loop over all lines to find the needed indentations.
852 (goto-char (point-min))
853 (while
854 (progn
855 (unless (looking-at "[ \t]*$")
856 (setq min-indent (min min-indent (current-indentation))))
857 (end-of-line)
858 (setq max-indent (max max-indent (current-column)))
859 (not (or (eobp) (progn (forward-line) nil)))))
861 ;; Inserting ccs can change max-indent by (1- tab-width).
862 (setq max-indent
863 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
864 (unless indent (setq min-indent 0))
866 ;; make the leading and trailing lines if requested
867 (when lines
868 (let ((csce
869 (comment-make-extra-lines
870 cs ce ccs cce min-indent max-indent block)))
871 (setq cs (car csce))
872 (setq ce (cdr csce))))
874 (goto-char (point-min))
875 ;; Loop over all lines from BEG to END.
876 (while
877 (progn
878 (unless (and no-empty (looking-at "[ \t]*$"))
879 (move-to-column min-indent t)
880 (insert cs) (setq cs ccs) ;switch to CCS after the first line
881 (end-of-line)
882 (if (eobp) (setq cce ce))
883 (when cce
884 (when block (move-to-column max-indent t))
885 (insert cce)))
886 (end-of-line)
887 (not (or (eobp) (progn (forward-line) nil))))))))))
889 ;;;###autoload
890 (defun comment-region (beg end &optional arg)
891 "Comment or uncomment each line in the region.
892 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
893 Numeric prefix arg ARG means use ARG comment characters.
894 If ARG is negative, delete that many comment characters instead.
895 By default, comments start at the left margin, are terminated on each line,
896 even for syntax in which newline does not end the comment and blank lines
897 do not get comments. This can be changed with `comment-style'.
899 The strings used as comment starts are built from
900 `comment-start' without trailing spaces and `comment-padding'."
901 (interactive "*r\nP")
902 (comment-normalize-vars)
903 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
904 (let* ((numarg (prefix-numeric-value arg))
905 (add comment-add)
906 (style (cdr (assoc comment-style comment-styles)))
907 (lines (nth 2 style))
908 (block (nth 1 style))
909 (multi (nth 0 style)))
910 (save-excursion
911 ;; we use `chars' instead of `syntax' because `\n' might be
912 ;; of end-comment syntax rather than of whitespace syntax.
913 ;; sanitize BEG and END
914 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
915 (setq beg (max beg (point)))
916 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
917 (setq end (min end (point)))
918 (if (>= beg end) (error "Nothing to comment"))
920 ;; sanitize LINES
921 (setq lines
922 (and
923 lines ;; multi
924 (progn (goto-char beg) (beginning-of-line)
925 (skip-syntax-forward " ")
926 (>= (point) beg))
927 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
928 (<= (point) end))
929 (or block (not (string= "" comment-end)))
930 (or block (progn (goto-char beg) (search-forward "\n" end t))))))
932 ;; don't add end-markers just because the user asked for `block'
933 (unless (or lines (string= "" comment-end)) (setq block nil))
935 (cond
936 ((consp arg) (uncomment-region beg end))
937 ((< numarg 0) (uncomment-region beg end (- numarg)))
939 (setq numarg (if (and (null arg) (= (length comment-start) 1))
940 add (1- numarg)))
941 (comment-region-internal
942 beg end
943 (let ((s (comment-padright comment-start numarg)))
944 (if (string-match comment-start-skip s) s
945 (comment-padright comment-start)))
946 (let ((s (comment-padleft comment-end numarg)))
947 (and s (if (string-match comment-end-skip s) s
948 (comment-padright comment-end))))
949 (if multi (comment-padright comment-continue numarg))
950 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
951 block
952 lines
953 (nth 3 style))))))
955 (defun comment-box (beg end &optional arg)
956 "Comment out the BEG .. END region, putting it inside a box.
957 The numeric prefix ARG specifies how many characters to add to begin- and
958 end- comment markers additionally to what `comment-add' already specifies."
959 (interactive "*r\np")
960 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
961 'box-multi 'box)))
962 (comment-region beg end (+ comment-add arg))))
965 ;;;###autoload
966 (defun comment-or-uncomment-region (beg end &optional arg)
967 "Call `comment-region', unless the region only consists of comments,
968 in which case call `uncomment-region'. If a prefix arg is given, it
969 is passed on to the respective function."
970 (interactive "*r\nP")
971 (comment-normalize-vars)
972 (funcall (if (save-excursion ;; check for already commented region
973 (goto-char beg)
974 (comment-forward (point-max))
975 (<= end (point)))
976 'uncomment-region 'comment-region)
977 beg end arg))
979 ;;;###autoload
980 (defun comment-dwim (arg)
981 "Call the comment command you want (Do What I Mean).
982 If the region is active and `transient-mark-mode' is on, call
983 `comment-region' (unless it only consists of comments, in which
984 case it calls `uncomment-region').
985 Else, if the current line is empty, insert a comment and indent it.
986 Else if a prefix ARG is specified, call `comment-kill'.
987 Else, call `comment-indent'."
988 (interactive "*P")
989 (comment-normalize-vars)
990 (if (and mark-active transient-mark-mode)
991 (comment-or-uncomment-region (region-beginning) (region-end) arg)
992 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
993 ;; FIXME: If there's no comment to kill on this line and ARG is
994 ;; specified, calling comment-kill is not very clever.
995 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
996 (let ((add (if arg (prefix-numeric-value arg)
997 (if (= (length comment-start) 1) comment-add 0))))
998 ;; Some modes insist on keeping column 0 comment in column 0
999 ;; so we need to move away from it before inserting the comment.
1000 (indent-according-to-mode)
1001 (insert (comment-padright comment-start add))
1002 (save-excursion
1003 (unless (string= "" comment-end)
1004 (insert (comment-padleft comment-end add)))
1005 (indent-according-to-mode))))))
1007 (defcustom comment-auto-fill-only-comments nil
1008 "Non-nil means to only auto-fill inside comments.
1009 This has no effect in modes that do not define a comment syntax."
1010 :type 'boolean)
1012 (defun comment-valid-prefix-p (prefix compos)
1014 ;; Accept any prefix if the current comment is not EOL-terminated.
1015 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1016 ;; Accept any prefix that starts with a comment-start marker.
1017 (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1018 prefix)))
1020 ;;;###autoload
1021 (defun comment-indent-new-line (&optional soft)
1022 "Break line at point and indent, continuing comment if within one.
1023 This indents the body of the continued comment
1024 under the previous comment line.
1026 This command is intended for styles where you write a comment per line,
1027 starting a new comment (and terminating it if necessary) on each line.
1028 If you want to continue one comment across several lines, use \\[newline-and-indent].
1030 If a fill column is specified, it overrides the use of the comment column
1031 or comment indentation.
1033 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1034 unless optional argument SOFT is non-nil."
1035 (interactive)
1036 (comment-normalize-vars t)
1037 (let (compos comin)
1038 ;; If we are not inside a comment and we only auto-fill comments,
1039 ;; don't do anything (unless no comment syntax is defined).
1040 (unless (and comment-start
1041 comment-auto-fill-only-comments
1042 (not (interactive-p))
1043 (not (save-excursion
1044 (prog1 (setq compos (comment-beginning))
1045 (setq comin (point))))))
1047 ;; Now we know we should auto-fill.
1048 ;; Insert the newline before removing empty space so that markers
1049 ;; get preserved better.
1050 (if soft (insert-and-inherit ?\n) (newline 1))
1051 (save-excursion (forward-char -1) (delete-horizontal-space))
1052 (delete-horizontal-space)
1054 (if (and fill-prefix (not adaptive-fill-mode))
1055 ;; Blindly trust a non-adaptive fill-prefix.
1056 (progn
1057 (indent-to-left-margin)
1058 (insert-before-markers-and-inherit fill-prefix))
1060 ;; If necessary check whether we're inside a comment.
1061 (unless (or compos (null comment-start))
1062 (save-excursion
1063 (backward-char)
1064 (setq compos (comment-beginning))
1065 (setq comin (point))))
1067 (cond
1068 ;; If there's an adaptive prefix, use it unless we're inside
1069 ;; a comment and the prefix is not a comment starter.
1070 ((and fill-prefix
1071 (or (not compos)
1072 (comment-valid-prefix-p fill-prefix compos)))
1073 (indent-to-left-margin)
1074 (insert-and-inherit fill-prefix))
1075 ;; If we're not inside a comment, just try to indent.
1076 ((not compos) (indent-according-to-mode))
1078 (let* ((comment-column
1079 ;; The continuation indentation should be somewhere between
1080 ;; the current line's indentation (plus 2 for good measure)
1081 ;; and the current comment's indentation, with a preference
1082 ;; for comment-column.
1083 (save-excursion
1084 ;; FIXME: use prev line's info rather than first line's.
1085 (goto-char compos)
1086 (min (current-column) (max comment-column
1087 (+ 2 (current-indentation))))))
1088 (comstart (buffer-substring compos comin))
1089 (normalp
1090 (string-match (regexp-quote (comment-string-strip
1091 comment-start t t))
1092 comstart))
1093 (comment-end
1094 (if normalp comment-end
1095 ;; The comment starter is not the normal comment-start
1096 ;; so we can't just use comment-end.
1097 (save-excursion
1098 (goto-char compos)
1099 (if (not (comment-forward)) comment-end
1100 (comment-string-strip
1101 (buffer-substring
1102 (save-excursion (comment-enter-backward) (point))
1103 (point))
1104 nil t)))))
1105 (comment-start comstart)
1106 (continuep (or comment-multi-line
1107 (cadr (assoc comment-style comment-styles))))
1108 ;; Force comment-continue to be recreated from comment-start.
1109 ;; FIXME: wrong if comment-continue was set explicitly!
1110 ;; FIXME: use prev line's continuation if available.
1111 (comment-continue nil))
1112 (if (and comment-multi-line (> (length comment-end) 0))
1113 (indent-according-to-mode)
1114 (insert-and-inherit ?\n)
1115 (forward-char -1)
1116 (comment-indent continuep)
1117 (save-excursion
1118 (let ((pt (point)))
1119 (end-of-line)
1120 (let ((comend (buffer-substring pt (point))))
1121 ;; The 1+ is to make sure we delete the \n inserted above.
1122 (delete-region pt (1+ (point)))
1123 (end-of-line 0)
1124 (insert comend))))))))))))
1126 (provide 'newcomment)
1128 ;;; newcomment.el ends here