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