Use the original buffer-name as `base' in place of the
[emacs.git] / lisp / newcomment.el
blob6b6f2d0b0e8eb23166013c61702cd488423e1eba
1 ;;; newcomment.el --- (un)comment regions of buffers
3 ;; Copyright (C) 1999, 2000 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 (setq begpos (point))
485 ;; Ensure there's a space before the comment for things
486 ;; like sh where it matters (as well as being neater).
487 (unless (eq ?\ (char-syntax (char-before)))
488 (insert ?\ ))
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 indent.
497 (indent-according-to-mode)
498 ;; Avoid moving comments past the fill-column.
499 (unless (save-excursion (skip-chars-backward " \t") (bolp))
500 (setq indent
501 (min indent
502 (+ (current-column)
503 (- (or comment-fill-column fill-column)
504 (save-excursion (end-of-line) (current-column)))))))
505 (unless (= (current-column) indent)
506 ;; If that's different from current, change it.
507 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
508 (indent-to (if (bolp) indent
509 (max indent (1+ (current-column)))))))
510 (goto-char cpos)
511 (set-marker cpos nil))))
513 ;;;###autoload
514 (defun comment-set-column (arg)
515 "Set the comment column based on point.
516 With no ARG, set the comment column to the current column.
517 With just minus as arg, kill any comment on this line.
518 With any other arg, set comment column to indentation of the previous comment
519 and then align or create a comment on this line at that column."
520 (interactive "P")
521 (cond
522 ((eq arg '-) (comment-kill nil))
523 (arg
524 (comment-normalize-vars)
525 (save-excursion
526 (beginning-of-line)
527 (comment-search-backward)
528 (beginning-of-line)
529 (goto-char (comment-search-forward (line-end-position)))
530 (setq comment-column (current-column))
531 (message "Comment column set to %d" comment-column))
532 (comment-indent))
533 (t (setq comment-column (current-column))
534 (message "Comment column set to %d" comment-column))))
536 ;;;###autoload
537 (defun comment-kill (arg)
538 "Kill the comment on this line, if any.
539 With prefix ARG, kill comments on that many lines starting with this one."
540 (interactive "P")
541 (comment-normalize-vars)
542 (dotimes (_ (prefix-numeric-value arg))
543 (save-excursion
544 (beginning-of-line)
545 (let ((cs (comment-search-forward (line-end-position) t)))
546 (when cs
547 (goto-char cs)
548 (skip-syntax-backward " ")
549 (setq cs (point))
550 (comment-forward)
551 (kill-region cs (if (bolp) (1- (point)) (point)))
552 (indent-according-to-mode))))
553 (if arg (forward-line 1))))
555 (defun comment-padright (str &optional n)
556 "Construct a string composed of STR plus `comment-padding'.
557 It also adds N copies of the last non-whitespace chars of STR.
558 If STR already contains padding, the corresponding amount is
559 ignored from `comment-padding'.
560 N defaults to 0.
561 If N is `re', a regexp is returned instead, that would match
562 the string for any N."
563 (setq n (or n 0))
564 (when (and (stringp str) (not (string= "" str)))
565 ;; Separate the actual string from any leading/trailing padding
566 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
567 (let ((s (match-string 1 str)) ;actual string
568 (lpad (substring str 0 (match-beginning 1))) ;left padding
569 (rpad (concat (substring str (match-end 1)) ;original right padding
570 (substring comment-padding ;additional right padding
571 (min (- (match-end 0) (match-end 1))
572 (length comment-padding)))))
573 ;; We can only duplicate C if the comment-end has multiple chars
574 ;; or if comments can be nested, else the comment-end `}' would
575 ;; be turned into `}}}' where only the first ends the comment
576 ;; and the rest becomes bogus junk.
577 (multi (not (and comment-quote-nested
578 ;; comment-end is a single char
579 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
580 (if (not (symbolp n))
581 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
582 ;; construct a regexp that would match anything from just S
583 ;; to any possible output of this function for any N.
584 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
585 lpad "") ;padding is not required
586 (regexp-quote s)
587 (when multi "+") ;the last char of S might be repeated
588 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
589 rpad "")))))) ;padding is not required
591 (defun comment-padleft (str &optional n)
592 "Construct a string composed of `comment-padding' plus STR.
593 It also adds N copies of the first non-whitespace chars of STR.
594 If STR already contains padding, the corresponding amount is
595 ignored from `comment-padding'.
596 N defaults to 0.
597 If N is `re', a regexp is returned instead, that would match
598 the string for any N."
599 (setq n (or n 0))
600 (when (and (stringp str) (not (string= "" str)))
601 ;; Only separate the left pad because we assume there is no right pad.
602 (string-match "\\`\\s-*" str)
603 (let ((s (substring str (match-end 0)))
604 (pad (concat (substring comment-padding
605 (min (- (match-end 0) (match-beginning 0))
606 (length comment-padding)))
607 (match-string 0 str)))
608 (c (aref str (match-end 0))) ;the first non-space char of STR
609 ;; We can only duplicate C if the comment-end has multiple chars
610 ;; or if comments can be nested, else the comment-end `}' would
611 ;; be turned into `}}}' where only the first ends the comment
612 ;; and the rest becomes bogus junk.
613 (multi (not (and comment-quote-nested
614 ;; comment-end is a single char
615 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
616 (if (not (symbolp n))
617 (concat pad (when multi (make-string n c)) s)
618 ;; Construct a regexp that would match anything from just S
619 ;; to any possible output of this function for any N.
620 ;; We match any number of leading spaces because this regexp will
621 ;; be used for uncommenting where we might want to remove
622 ;; uncomment markers with arbitrary leading space (because
623 ;; they were aligned).
624 (concat "\\s-*"
625 (if multi (concat (regexp-quote (string c)) "*"))
626 (regexp-quote s))))))
628 ;;;###autoload
629 (defun uncomment-region (beg end &optional arg)
630 "Uncomment each line in the BEG .. END region.
631 The numeric prefix ARG can specify a number of chars to remove from the
632 comment markers."
633 (interactive "*r\nP")
634 (comment-normalize-vars)
635 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
636 (save-excursion
637 (goto-char beg)
638 (setq end (copy-marker end))
639 (let* ((numarg (prefix-numeric-value arg))
640 (ccs comment-continue)
641 (srei (comment-padright ccs 're))
642 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
643 spt)
644 (while (and (< (point) end)
645 (setq spt (comment-search-forward end t)))
646 (let ((ipt (point))
647 ;; Find the end of the comment.
648 (ept (progn
649 (goto-char spt)
650 (unless (comment-forward)
651 (error "Can't find the comment end"))
652 (point)))
653 (box nil)
654 (box-equal nil)) ;Whether we might be using `=' for boxes.
655 (save-restriction
656 (narrow-to-region spt ept)
658 ;; Remove the comment-start.
659 (goto-char ipt)
660 (skip-syntax-backward " ")
661 ;; A box-comment starts with a looong comment-start marker.
662 (when (and (or (and (= (- (point) (point-min)) 1)
663 (setq box-equal t)
664 (looking-at "=\\{7\\}")
665 (not (eq (char-before (point-max)) ?\n))
666 (skip-chars-forward "="))
667 (> (- (point) (point-min) (length comment-start)) 7))
668 (> (count-lines (point-min) (point-max)) 2))
669 (setq box t))
670 (when (looking-at (regexp-quote comment-padding))
671 (goto-char (match-end 0)))
672 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
673 (goto-char (match-end 0)))
674 (if (null arg) (delete-region (point-min) (point))
675 (skip-syntax-backward " ")
676 (delete-char (- numarg))
677 (unless (or (bobp)
678 (save-excursion (goto-char (point-min))
679 (looking-at comment-start-skip)))
680 ;; If there's something left but it doesn't look like
681 ;; a comment-start any more, just remove it.
682 (delete-region (point-min) (point))))
684 ;; Remove the end-comment (and leading padding and such).
685 (goto-char (point-max)) (comment-enter-backward)
686 ;; Check for special `=' used sometimes in comment-box.
687 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
688 (let ((pos (point)))
689 ;; skip `=' but only if there are at least 7.
690 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
691 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
692 (when (and (bolp) (not (bobp))) (backward-char))
693 (if (null arg) (delete-region (point) (point-max))
694 (skip-syntax-forward " ")
695 (delete-char numarg)
696 (unless (or (eobp) (looking-at comment-end-skip))
697 ;; If there's something left but it doesn't look like
698 ;; a comment-end any more, just remove it.
699 (delete-region (point) (point-max)))))
701 ;; Unquote any nested end-comment.
702 (comment-quote-nested comment-start comment-end t)
704 ;; Eliminate continuation markers as well.
705 (when sre
706 (let* ((cce (comment-string-reverse (or comment-continue
707 comment-start)))
708 (erei (and box (comment-padleft cce 're)))
709 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
710 (goto-char (point-min))
711 (while (progn
712 (if (and ere (re-search-forward
713 ere (line-end-position) t))
714 (replace-match "" t t nil (if (match-end 2) 2 1))
715 (setq ere nil))
716 (forward-line 1)
717 (re-search-forward sre (line-end-position) t))
718 (replace-match "" t t nil (if (match-end 2) 2 1)))))
719 ;; Go to the end for the next comment.
720 (goto-char (point-max)))))
721 (set-marker end nil))))
723 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
724 "Make the leading and trailing extra lines.
725 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
726 (let ((eindent 0))
727 (if (not block)
728 ;; Try to match CS and CE's content so they align aesthetically.
729 (progn
730 (setq ce (comment-string-strip ce t t))
731 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
732 (setq eindent
733 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
734 0))))
735 ;; box comment
736 (let* ((width (- max-indent min-indent))
737 (s (concat cs "a=m" cce))
738 (e (concat ccs "a=m" ce))
739 (c (if (string-match ".*\\S-\\S-" cs)
740 (aref cs (1- (match-end 0)))
741 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
742 (aref cs (1- (match-end 0))) ?=)))
743 (re "\\s-*a=m\\s-*")
744 (_ (string-match re s))
745 (lcs (length cs))
746 (fill
747 (make-string (+ width (- (match-end 0)
748 (match-beginning 0) lcs 3)) c)))
749 (setq cs (replace-match fill t t s))
750 (when (and (not (string-match comment-start-skip cs))
751 (string-match "a=m" s))
752 ;; The whitespace around CS cannot be ignored: put it back.
753 (setq re "a=m")
754 (setq fill (make-string (- width lcs) c))
755 (setq cs (replace-match fill t t s)))
756 (string-match re e)
757 (setq ce (replace-match fill t t e))))
758 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
759 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
761 (defmacro comment-with-narrowing (beg end &rest body)
762 "Execute BODY with BEG..END narrowing.
763 Space is added (and then removed) at the beginning for the text's
764 indentation to be kept as it was before narrowing."
765 (declare (debug t) (indent 2))
766 (let ((bindent (make-symbol "bindent")))
767 `(let ((,bindent (save-excursion (goto-char beg) (current-column))))
768 (save-restriction
769 (narrow-to-region beg end)
770 (goto-char (point-min))
771 (insert (make-string ,bindent ? ))
772 (prog1
773 (progn ,@body)
774 ;; remove the bindent
775 (save-excursion
776 (goto-char (point-min))
777 (when (looking-at " *")
778 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
779 (delete-char n)
780 (setq ,bindent (- ,bindent n))))
781 (end-of-line)
782 (let ((e (point)))
783 (beginning-of-line)
784 (while (and (> ,bindent 0) (re-search-forward " *" e t))
785 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
786 (goto-char (match-beginning 0))
787 (delete-char n)
788 (setq ,bindent (- ,bindent n)))))))))))
790 (defun comment-region-internal (beg end cs ce
791 &optional ccs cce block lines indent)
792 "Comment region BEG .. END.
793 CS and CE are the comment start resp end string.
794 CCS and CCE are the comment continuation strings for the start resp end
795 of lines (default to CS and CE).
796 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
797 \(if CE is empty) and that those markers should be aligned.
798 LINES indicates that an extra lines will be used at the beginning and end
799 of the region for CE and CS.
800 INDENT indicates to put CS and CCS at the current indentation of the region
801 rather than at left margin."
802 ;;(assert (< beg end))
803 (let ((no-empty t))
804 ;; Sanitize CE and CCE.
805 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
806 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
807 ;; If CE is empty, multiline cannot be used.
808 (unless ce (setq ccs nil cce nil))
809 ;; Should we mark empty lines as well ?
810 (if (or ccs block lines) (setq no-empty nil))
811 ;; Make sure we have end-markers for BLOCK mode.
812 (when block (unless ce (setq ce (comment-string-reverse cs))))
813 ;; If BLOCK is not requested, we don't need CCE.
814 (unless block (setq cce nil))
815 ;; Continuation defaults to the same as CS and CE.
816 (unless ccs (setq ccs cs cce ce))
818 (save-excursion
819 (goto-char end)
820 ;; If the end is not at the end of a line and the comment-end
821 ;; is implicit (i.e. a newline), explicitly insert a newline.
822 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
823 (comment-with-narrowing beg end
824 (let ((min-indent (point-max))
825 (max-indent 0))
826 (goto-char (point-min))
827 ;; Quote any nested comment marker
828 (comment-quote-nested comment-start comment-end nil)
830 ;; Loop over all lines to find the needed indentations.
831 (goto-char (point-min))
832 (while
833 (progn
834 (unless (looking-at "[ \t]*$")
835 (setq min-indent (min min-indent (current-indentation))))
836 (end-of-line)
837 (setq max-indent (max max-indent (current-column)))
838 (not (or (eobp) (progn (forward-line) nil)))))
840 ;; Inserting ccs can change max-indent by (1- tab-width).
841 (setq max-indent
842 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
843 (unless indent (setq min-indent 0))
845 ;; make the leading and trailing lines if requested
846 (when lines
847 (let ((csce
848 (comment-make-extra-lines
849 cs ce ccs cce min-indent max-indent block)))
850 (setq cs (car csce))
851 (setq ce (cdr csce))))
853 (goto-char (point-min))
854 ;; Loop over all lines from BEG to END.
855 (while
856 (progn
857 (unless (and no-empty (looking-at "[ \t]*$"))
858 (move-to-column min-indent t)
859 (insert cs) (setq cs ccs) ;switch to CCS after the first line
860 (end-of-line)
861 (if (eobp) (setq cce ce))
862 (when cce
863 (when block (move-to-column max-indent t))
864 (insert cce)))
865 (end-of-line)
866 (not (or (eobp) (progn (forward-line) nil))))))))))
868 ;;;###autoload
869 (defun comment-region (beg end &optional arg)
870 "Comment or uncomment each line in the region.
871 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
872 Numeric prefix arg ARG means use ARG comment characters.
873 If ARG is negative, delete that many comment characters instead.
874 By default, comments start at the left margin, are terminated on each line,
875 even for syntax in which newline does not end the comment and blank lines
876 do not get comments. This can be changed with `comment-style'.
878 The strings used as comment starts are built from
879 `comment-start' without trailing spaces and `comment-padding'."
880 (interactive "*r\nP")
881 (comment-normalize-vars)
882 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
883 (let* ((numarg (prefix-numeric-value arg))
884 (add comment-add)
885 (style (cdr (assoc comment-style comment-styles)))
886 (lines (nth 2 style))
887 (block (nth 1 style))
888 (multi (nth 0 style)))
889 (save-excursion
890 ;; we use `chars' instead of `syntax' because `\n' might be
891 ;; of end-comment syntax rather than of whitespace syntax.
892 ;; sanitize BEG and END
893 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
894 (setq beg (max beg (point)))
895 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
896 (setq end (min end (point)))
897 (if (>= beg end) (error "Nothing to comment"))
899 ;; sanitize LINES
900 (setq lines
901 (and
902 lines ;; multi
903 (progn (goto-char beg) (beginning-of-line)
904 (skip-syntax-forward " ")
905 (>= (point) beg))
906 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
907 (<= (point) end))
908 (or block (not (string= "" comment-end)))
909 (or block (progn (goto-char beg) (search-forward "\n" end t))))))
911 ;; don't add end-markers just because the user asked for `block'
912 (unless (or lines (string= "" comment-end)) (setq block nil))
914 (cond
915 ((consp arg) (uncomment-region beg end))
916 ((< numarg 0) (uncomment-region beg end (- numarg)))
918 (setq numarg (if (and (null arg) (= (length comment-start) 1))
919 add (1- numarg)))
920 (comment-region-internal
921 beg end
922 (let ((s (comment-padright comment-start numarg)))
923 (if (string-match comment-start-skip s) s
924 (comment-padright comment-start)))
925 (let ((s (comment-padleft comment-end numarg)))
926 (and s (if (string-match comment-end-skip s) s
927 (comment-padright comment-end))))
928 (if multi (comment-padright comment-continue numarg))
929 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
930 block
931 lines
932 (nth 3 style))))))
934 (defun comment-box (beg end &optional arg)
935 "Comment out the BEG .. END region, putting it inside a box.
936 The numeric prefix ARG specifies how many characters to add to begin- and
937 end- comment markers additionally to what `comment-add' already specifies."
938 (interactive "*r\np")
939 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
940 'box-multi 'box)))
941 (comment-region beg end (+ comment-add arg))))
944 ;;;###autoload
945 (defun comment-or-uncomment-region (beg end &optional arg)
946 "Call `comment-region', unless the region only consists of comments,
947 in which case call `uncomment-region'. If a prefix arg is given, it
948 is passed on to the respective function."
949 (interactive "*r\nP")
950 (comment-normalize-vars)
951 (funcall (if (save-excursion ;; check for already commented region
952 (goto-char beg)
953 (comment-forward (point-max))
954 (<= end (point)))
955 'uncomment-region 'comment-region)
956 beg end arg))
958 ;;;###autoload
959 (defun comment-dwim (arg)
960 "Call the comment command you want (Do What I Mean).
961 If the region is active and `transient-mark-mode' is on, call
962 `comment-region' (unless it only consists of comments, in which
963 case it calls `uncomment-region').
964 Else, if the current line is empty, insert a comment and indent it.
965 Else if a prefix ARG is specified, call `comment-kill'.
966 Else, call `comment-indent'."
967 (interactive "*P")
968 (comment-normalize-vars)
969 (if (and mark-active transient-mark-mode)
970 (comment-or-uncomment-region (region-beginning) (region-end) arg)
971 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
972 ;; FIXME: If there's no comment to kill on this line and ARG is
973 ;; specified, calling comment-kill is not very clever.
974 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
975 (let ((add (if arg (prefix-numeric-value arg)
976 (if (= (length comment-start) 1) comment-add 0))))
977 ;; Some modes insist on keeping column 0 comment in column 0
978 ;; so we need to move away from it before inserting the comment.
979 (indent-according-to-mode)
980 (insert (comment-padright comment-start add))
981 (save-excursion
982 (unless (string= "" comment-end)
983 (insert (comment-padleft comment-end add)))
984 (indent-according-to-mode))))))
986 (defcustom comment-auto-fill-only-comments nil
987 "Non-nil means to only auto-fill inside comments.
988 This has no effect in modes that do not define a comment syntax."
989 :type 'boolean)
991 (defun comment-valid-prefix (prefix compos)
993 ;; Accept any prefix if the current comment is not EOL-terminated.
994 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
995 ;; Accept any prefix that starts with a comment-start marker.
996 (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
997 fill-prefix)))
999 ;;;###autoload
1000 (defun comment-indent-new-line (&optional soft)
1001 "Break line at point and indent, continuing comment if within one.
1002 This indents the body of the continued comment
1003 under the previous comment line.
1005 This command is intended for styles where you write a comment per line,
1006 starting a new comment (and terminating it if necessary) on each line.
1007 If you want to continue one comment across several lines, use \\[newline-and-indent].
1009 If a fill column is specified, it overrides the use of the comment column
1010 or comment indentation.
1012 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1013 unless optional argument SOFT is non-nil."
1014 (interactive)
1015 (comment-normalize-vars t)
1016 (let (compos comin)
1017 ;; If we are not inside a comment and we only auto-fill comments,
1018 ;; don't do anything (unless no comment syntax is defined).
1019 (unless (and comment-start
1020 comment-auto-fill-only-comments
1021 (not (interactive-p))
1022 (not (save-excursion
1023 (prog1 (setq compos (comment-beginning))
1024 (setq comin (point))))))
1026 ;; Now we know we should auto-fill.
1027 ;; Insert the newline before removing empty space so that markers
1028 ;; get preserved better.
1029 (if soft (insert-and-inherit ?\n) (newline 1))
1030 (save-excursion (forward-char -1) (delete-horizontal-space))
1031 (delete-horizontal-space)
1033 (if (and fill-prefix (not adaptive-fill-mode))
1034 ;; Blindly trust a non-adaptive fill-prefix.
1035 (progn
1036 (indent-to-left-margin)
1037 (insert-before-markers-and-inherit fill-prefix))
1039 ;; If necessary check whether we're inside a comment.
1040 (unless (or compos (null comment-start))
1041 (save-excursion
1042 (backward-char)
1043 (setq compos (comment-beginning))
1044 (setq comin (point))))
1046 (cond
1047 ;; If there's an adaptive prefix, use it unless we're inside
1048 ;; a comment and the prefix is not a comment starter.
1049 ((and fill-prefix
1050 (or (not compos)
1051 (comment-valid-prefix fill-prefix compos)))
1052 (indent-to-left-margin)
1053 (insert-and-inherit fill-prefix))
1054 ;; If we're not inside a comment, just try to indent.
1055 ((not compos) (indent-according-to-mode))
1057 (let* ((comment-column
1058 ;; The continuation indentation should be somewhere between
1059 ;; the current line's indentation (plus 2 for good measure)
1060 ;; and the current comment's indentation, with a preference
1061 ;; for comment-column.
1062 (save-excursion
1063 ;; FIXME: use prev line's info rather than first line's.
1064 (goto-char compos)
1065 (min (current-column) (max comment-column
1066 (+ 2 (current-indentation))))))
1067 (comstart (buffer-substring compos comin))
1068 (normalp
1069 (string-match (regexp-quote (comment-string-strip
1070 comment-start t t))
1071 comstart))
1072 (comment-end
1073 (if normalp comment-end
1074 ;; The comment starter is not the normal comment-start
1075 ;; so we can't just use comment-end.
1076 (save-excursion
1077 (goto-char compos)
1078 (if (not (comment-forward)) comment-end
1079 (comment-string-strip
1080 (buffer-substring
1081 (save-excursion (comment-enter-backward) (point))
1082 (point))
1083 nil t)))))
1084 (comment-start comstart)
1085 (continuep (or comment-multi-line
1086 (cadr (assoc comment-style comment-styles))))
1087 ;; Force comment-continue to be recreated from comment-start.
1088 ;; FIXME: wrong if comment-continue was set explicitly!
1089 ;; FIXME: use prev line's continuation if available.
1090 (comment-continue nil))
1091 (if (and comment-multi-line (> (length comment-end) 0))
1092 (indent-according-to-mode)
1093 (insert-and-inherit ?\n)
1094 (forward-char -1)
1095 (comment-indent continuep)
1096 (save-excursion
1097 (let ((pt (point)))
1098 (end-of-line)
1099 (let ((comend (buffer-substring pt (point))))
1100 ;; The 1+ is to make sure we delete the \n inserted above.
1101 (delete-region pt (1+ (point)))
1102 (end-of-line 0)
1103 (insert comend))))))))))))
1105 (provide 'newcomment)
1107 ;;; newcomment.el ends here