Add arch taglines
[bpt/emacs.git] / lisp / newcomment.el
1 ;;; newcomment.el --- (un)comment regions of buffers
2
3 ;; Copyright (C) 1999,2000,2003 Free Software Foundation Inc.
4
5 ;; Author: code extracted from Emacs-20's simple.el
6 ;; Maintainer: Stefan Monnier <monnier@cs.yale.edu>
7 ;; Keywords: comment uncomment
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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.
25
26 ;;; Commentary:
27
28 ;; A replacement for simple.el's comment-related functions.
29
30 ;;; Bugs:
31
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.
44
45 ;;; Todo:
46
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.
59
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).
64
65 ;;; Code:
66
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)
75
76 (defgroup comment nil
77 "Indenting and filling of comments."
78 :prefix "comment-"
79 :version "21.1"
80 :group 'fill)
81
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.")
90
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))
94
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)
104
105 ;;;###autoload
106 (defvar comment-start nil
107 "*String to insert to start a new comment, or nil if no comment syntax.")
108
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.")
114
115 ;;;###autoload
116 (defvar comment-end-skip nil
117 "Regexp to match the end of a comment plus everything up to its body.")
118
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.")
123
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'.")
131
132 (defvar block-comment-start nil)
133 (defvar block-comment-end nil)
134
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.")
138
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.")
148
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.")
155
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.")
172
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))
180
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.
186
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)))
190
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)
196
197 (defcustom comment-empty-lines nil
198 "If nil, `comment-region' does not comment out empty lines.
199 If t, it always comments out empty lines.
200 if `eol' it only comments out empty lines if comments are
201 terminated by the end of line (i.e. `comment-end' is empty)."
202 :type '(choice (const :tag "Never" nil)
203 (const :tag "Always" t)
204 (const :tag "EOl-terminated" 'eol)))
205
206 ;;;;
207 ;;;; Helpers
208 ;;;;
209
210 (defun comment-string-strip (str beforep afterp)
211 "Strip STR of any leading (if BEFOREP) and/or trailing (if AFTERP) space."
212 (string-match (concat "\\`" (if beforep "\\s-*")
213 "\\(.*?\\)" (if afterp "\\s-*\n?")
214 "\\'") str)
215 (match-string 1 str))
216
217 (defun comment-string-reverse (s)
218 "Return the mirror image of string S, without any trailing space."
219 (comment-string-strip (concat (nreverse (string-to-list s))) nil t))
220
221 ;;;###autoload
222 (defun comment-normalize-vars (&optional noerror)
223 "Check and setup the variables needed by other commenting functions.
224 Functions autoloaded from newcomment.el, being entry points, should call
225 this function before any other, so the rest of the code can assume that
226 the variables are properly set."
227 (if (not comment-start)
228 (unless noerror
229 (set (make-local-variable 'comment-start)
230 (read-string "No comment syntax is defined. Use: ")))
231 ;; comment-use-syntax
232 (when (eq comment-use-syntax 'undecided)
233 (set (make-local-variable 'comment-use-syntax)
234 (let ((st (syntax-table))
235 (cs comment-start)
236 (ce (if (string= "" comment-end) "\n" comment-end)))
237 ;; Try to skip over a comment using forward-comment
238 ;; to see if the syntax tables properly recognize it.
239 (with-temp-buffer
240 (set-syntax-table st)
241 (insert cs " hello " ce)
242 (goto-char (point-min))
243 (and (forward-comment 1) (eobp))))))
244 ;; comment-padding
245 (unless comment-padding (setq comment-padding 0))
246 (when (integerp comment-padding)
247 (setq comment-padding (make-string comment-padding ? )))
248 ;; comment markers
249 ;;(setq comment-start (comment-string-strip comment-start t nil))
250 ;;(setq comment-end (comment-string-strip comment-end nil t))
251 ;; comment-continue
252 (unless (or comment-continue (string= comment-end ""))
253 (set (make-local-variable 'comment-continue)
254 (concat (if (string-match "\\S-\\S-" comment-start) " " "|")
255 (substring comment-start 1)))
256 ;; Hasn't been necessary yet.
257 ;; (unless (string-match comment-start-skip comment-continue)
258 ;; (kill-local-variable 'comment-continue))
259 )
260 ;; comment-skip regexps
261 (unless (and comment-start-skip
262 ;; In case comment-start has changed since last time.
263 (string-match comment-start-skip comment-start))
264 (set (make-local-variable 'comment-start-skip)
265 (concat "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(\\s<+\\|"
266 (regexp-quote (comment-string-strip comment-start t t))
267 ;; Let's not allow any \s- but only [ \t] since \n
268 ;; might be both a comment-end marker and \s-.
269 "+\\)[ \t]*")))
270 (unless (and comment-end-skip
271 ;; In case comment-end has changed since last time.
272 (string-match comment-end-skip comment-end))
273 (let ((ce (if (string= "" comment-end) "\n"
274 (comment-string-strip comment-end t t))))
275 (set (make-local-variable 'comment-end-skip)
276 ;; We use [ \t] rather than \s- because we don't want to
277 ;; remove ^L in C mode when uncommenting.
278 (concat "[ \t]*\\(\\s>" (if comment-quote-nested "" "+")
279 "\\|" (regexp-quote (substring ce 0 1))
280 (if (and comment-quote-nested (<= (length ce) 1)) "" "+")
281 (regexp-quote (substring ce 1))
282 "\\)"))))))
283
284 (defun comment-quote-re (str unp)
285 (concat (regexp-quote (substring str 0 1))
286 "\\\\" (if unp "+" "*")
287 (regexp-quote (substring str 1))))
288
289 (defun comment-quote-nested (cs ce unp)
290 "Quote or unquote nested comments.
291 If UNP is non-nil, unquote nested comment markers."
292 (setq cs (comment-string-strip cs t t))
293 (setq ce (comment-string-strip ce t t))
294 (when (and comment-quote-nested (> (length ce) 0))
295 (let ((re (concat (comment-quote-re ce unp)
296 "\\|" (comment-quote-re cs unp))))
297 (goto-char (point-min))
298 (while (re-search-forward re nil t)
299 (goto-char (match-beginning 0))
300 (forward-char 1)
301 (if unp (delete-char 1) (insert "\\"))
302 (when (= (length ce) 1)
303 ;; If the comment-end is a single char, adding a \ after that
304 ;; "first" char won't deactivate it, so we turn such a CE
305 ;; into !CS. I.e. for pascal, we turn } into !{
306 (if (not unp)
307 (when (string= (match-string 0) ce)
308 (replace-match (concat "!" cs) t t))
309 (when (and (< (point-min) (match-beginning 0))
310 (string= (buffer-substring (1- (match-beginning 0))
311 (1- (match-end 0)))
312 (concat "!" cs)))
313 (backward-char 2)
314 (delete-char (- (match-end 0) (match-beginning 0)))
315 (insert ce))))))))
316
317 ;;;;
318 ;;;; Navigation
319 ;;;;
320
321 (defun comment-search-forward (limit &optional noerror)
322 "Find a comment start between point and LIMIT.
323 Moves point to inside the comment and returns the position of the
324 comment-starter. If no comment is found, moves point to LIMIT
325 and raises an error or returns nil of NOERROR is non-nil."
326 (if (not comment-use-syntax)
327 (if (re-search-forward comment-start-skip limit noerror)
328 (or (match-end 1) (match-beginning 0))
329 (goto-char limit)
330 (unless noerror (error "No comment")))
331 (let* ((pt (point))
332 ;; Assume (at first) that pt is outside of any string.
333 (s (parse-partial-sexp pt (or limit (point-max)) nil nil nil t)))
334 (when (and (nth 8 s) (nth 3 s))
335 ;; The search ended inside a string. Try to see if it
336 ;; works better when we assume that pt is inside a string.
337 (setq s (parse-partial-sexp
338 pt (or limit (point-max)) nil nil
339 (list nil nil nil (nth 3 s) nil nil nil nil)
340 t)))
341 (if (not (and (nth 8 s) (not (nth 3 s))))
342 (unless noerror (error "No comment"))
343 ;; We found the comment.
344 (let ((pos (point))
345 (start (nth 8 s))
346 (bol (line-beginning-position))
347 (end nil))
348 (while (and (null end) (>= (point) bol))
349 (if (looking-at comment-start-skip)
350 (setq end (min (or limit (point-max)) (match-end 0)))
351 (backward-char)))
352 (goto-char (or end pos))
353 start)))))
354
355 (defun comment-search-backward (&optional limit noerror)
356 "Find a comment start between LIMIT and point.
357 Moves point to inside the comment and returns the position of the
358 comment-starter. If no comment is found, moves point to LIMIT
359 and raises an error or returns nil of NOERROR is non-nil."
360 ;; FIXME: If a comment-start appears inside a comment, we may erroneously
361 ;; stop there. This can be rather bad in general, but since
362 ;; comment-search-backward is only used to find the comment-column (in
363 ;; comment-set-column) and to find the comment-start string (via
364 ;; comment-beginning) in indent-new-comment-line, it should be harmless.
365 (if (not (re-search-backward comment-start-skip limit t))
366 (unless noerror (error "No comment"))
367 (beginning-of-line)
368 (let* ((end (match-end 0))
369 (cs (comment-search-forward end t))
370 (pt (point)))
371 (if (not cs)
372 (progn (beginning-of-line)
373 (comment-search-backward limit noerror))
374 (while (progn (goto-char cs)
375 (comment-forward)
376 (and (< (point) end)
377 (setq cs (comment-search-forward end t))))
378 (setq pt (point)))
379 (goto-char pt)
380 cs))))
381
382 (defun comment-beginning ()
383 "Find the beginning of the enclosing comment.
384 Returns nil if not inside a comment, else moves point and returns
385 the same as `comment-search-forward'."
386 ;; HACK ATTACK!
387 ;; We should really test `in-string-p' but that can be expensive.
388 (unless (eq (get-text-property (point) 'face) 'font-lock-string-face)
389 (let ((pt (point))
390 (cs (comment-search-backward nil t)))
391 (when cs
392 (if (save-excursion
393 (goto-char cs)
394 (and
395 ;; For modes where comment-start and comment-end are the same,
396 ;; the search above may have found a `ce' rather than a `cs'.
397 (or (not (looking-at comment-end-skip))
398 ;; Maybe font-lock knows that it's a `cs'?
399 (eq (get-text-property (match-end 0) 'face)
400 'font-lock-comment-face)
401 (unless (eq (get-text-property (point) 'face)
402 'font-lock-comment-face)
403 ;; Let's assume it's a `cs' if we're on the same line.
404 (>= (line-end-position) pt)))
405 ;; Make sure that PT is not past the end of the comment.
406 (if (comment-forward 1) (> (point) pt) (eobp))))
407 cs
408 (goto-char pt)
409 nil)))))
410
411 (defun comment-forward (&optional n)
412 "Skip forward over N comments.
413 Just like `forward-comment' but only for positive N
414 and can use regexps instead of syntax."
415 (setq n (or n 1))
416 (if (< n 0) (error "No comment-backward")
417 (if comment-use-syntax (forward-comment n)
418 (while (> n 0)
419 (setq n
420 (if (or (forward-comment 1)
421 (and (looking-at comment-start-skip)
422 (goto-char (match-end 0))
423 (re-search-forward comment-end-skip nil 'move)))
424 (1- n) -1)))
425 (= n 0))))
426
427 (defun comment-enter-backward ()
428 "Move from the end of a comment to the end of its content.
429 Point is assumed to be just at the end of a comment."
430 (if (bolp)
431 ;; comment-end = ""
432 (progn (backward-char) (skip-syntax-backward " "))
433 (let ((end (point)))
434 (beginning-of-line)
435 (save-restriction
436 (narrow-to-region (point) end)
437 (if (re-search-forward (concat comment-end-skip "\\'") nil t)
438 (goto-char (match-beginning 0))
439 ;; comment-end-skip not found probably because it was not set right.
440 ;; Since \\s> should catch the single-char case, we'll blindly
441 ;; assume we're at the end of a two-char comment-end.
442 (goto-char (point-max))
443 (backward-char 2)
444 (skip-chars-backward (string (char-after)))
445 (skip-syntax-backward " "))))))
446
447 ;;;;
448 ;;;; Commands
449 ;;;;
450
451 ;;;###autoload
452 (defun comment-indent-default ()
453 "Default for `comment-indent-function'."
454 (if (and (looking-at "\\s<\\s<\\(\\s<\\)?")
455 (or (match-end 1) (/= (current-column) (current-indentation))))
456 0
457 (when (or (/= (current-column) (current-indentation))
458 (and (> comment-add 0) (looking-at "\\s<\\S<")))
459 comment-column)))
460
461 ;;;###autoload
462 (defun comment-indent (&optional continue)
463 "Indent this line's comment to comment column, or insert an empty comment.
464 If CONTINUE is non-nil, use the `comment-continue' markers if any."
465 (interactive "*")
466 (comment-normalize-vars)
467 (let* ((empty (save-excursion (beginning-of-line)
468 (looking-at "[ \t]*$")))
469 (starter (or (and continue comment-continue)
470 (and empty block-comment-start) comment-start))
471 (ender (or (and continue comment-continue "")
472 (and empty block-comment-end) comment-end)))
473 (unless starter (error "No comment syntax defined"))
474 (beginning-of-line)
475 (let* ((eolpos (line-end-position))
476 (begpos (comment-search-forward eolpos t))
477 cpos indent)
478 ;; An existing comment?
479 (if begpos
480 (progn
481 (if (and (not (looking-at "[\t\n ]"))
482 (looking-at comment-end-skip))
483 ;; The comment is empty and we have skipped all its space
484 ;; and landed right before the comment-ender:
485 ;; Go back to the middle of the space.
486 (forward-char (/ (skip-chars-backward " \t") -2)))
487 (setq cpos (point-marker)))
488 ;; If none, insert one.
489 (save-excursion
490 ;; Some comment-indent-function insist on not moving comments that
491 ;; are in column 0, so we first go to the likely target column.
492 (indent-to comment-column)
493 ;; Ensure there's a space before the comment for things
494 ;; like sh where it matters (as well as being neater).
495 (unless (memq (char-before) '(nil ?\n ?\t ?\ ))
496 (insert ?\ ))
497 (setq begpos (point))
498 (insert starter)
499 (setq cpos (point-marker))
500 (insert ender)))
501 (goto-char begpos)
502 ;; Compute desired indent.
503 (setq indent (save-excursion (funcall comment-indent-function)))
504 (if (not indent)
505 ;; comment-indent-function refuses: delegate to line-indent.
506 (indent-according-to-mode)
507 ;; Avoid moving comments past the fill-column.
508 (unless (save-excursion (skip-chars-backward " \t") (bolp))
509 (let ((max (+ (current-column)
510 (- (or comment-fill-column fill-column)
511 (save-excursion (end-of-line) (current-column))))))
512 (if (<= max indent)
513 (setq indent max) ;Don't move past the fill column.
514 ;; We can choose anywhere between indent..max.
515 ;; Let's try to align to a comment on the previous line.
516 (let ((other nil))
517 (save-excursion
518 (when (and (zerop (forward-line -1))
519 (setq other (comment-search-forward
520 (line-end-position) t)))
521 (goto-char other) (setq other (current-column))))
522 (if (and other (<= other max) (> other indent))
523 ;; There is a comment and it's in the range: bingo.
524 (setq indent other)
525 ;; Let's try to align to a comment on the next line, then.
526 (let ((other nil))
527 (save-excursion
528 (when (and (zerop (forward-line 1))
529 (setq other (comment-search-forward
530 (line-end-position) t)))
531 (goto-char other) (setq other (current-column))))
532 (if (and other (<= other max) (> other indent))
533 ;; There is a comment and it's in the range: bingo.
534 (setq indent other))))))))
535 (unless (= (current-column) indent)
536 ;; If that's different from current, change it.
537 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
538 (indent-to (if (bolp) indent
539 (max indent (1+ (current-column)))))))
540 (goto-char cpos)
541 (set-marker cpos nil))))
542
543 ;;;###autoload
544 (defun comment-set-column (arg)
545 "Set the comment column based on point.
546 With no ARG, set the comment column to the current column.
547 With just minus as arg, kill any comment on this line.
548 With any other arg, set comment column to indentation of the previous comment
549 and then align or create a comment on this line at that column."
550 (interactive "P")
551 (cond
552 ((eq arg '-) (comment-kill nil))
553 (arg
554 (comment-normalize-vars)
555 (save-excursion
556 (beginning-of-line)
557 (comment-search-backward)
558 (beginning-of-line)
559 (goto-char (comment-search-forward (line-end-position)))
560 (setq comment-column (current-column))
561 (message "Comment column set to %d" comment-column))
562 (comment-indent))
563 (t (setq comment-column (current-column))
564 (message "Comment column set to %d" comment-column))))
565
566 ;;;###autoload
567 (defun comment-kill (arg)
568 "Kill the comment on this line, if any.
569 With prefix ARG, kill comments on that many lines starting with this one."
570 (interactive "P")
571 (comment-normalize-vars)
572 (dotimes (_ (prefix-numeric-value arg))
573 (save-excursion
574 (beginning-of-line)
575 (let ((cs (comment-search-forward (line-end-position) t)))
576 (when cs
577 (goto-char cs)
578 (skip-syntax-backward " ")
579 (setq cs (point))
580 (comment-forward)
581 (kill-region cs (if (bolp) (1- (point)) (point)))
582 (indent-according-to-mode))))
583 (if arg (forward-line 1))))
584
585 (defun comment-padright (str &optional n)
586 "Construct a string composed of STR plus `comment-padding'.
587 It also adds N copies of the last non-whitespace chars of STR.
588 If STR already contains padding, the corresponding amount is
589 ignored from `comment-padding'.
590 N defaults to 0.
591 If N is `re', a regexp is returned instead, that would match
592 the string for any N."
593 (setq n (or n 0))
594 (when (and (stringp str) (not (string= "" str)))
595 ;; Separate the actual string from any leading/trailing padding
596 (string-match "\\`\\s-*\\(.*?\\)\\s-*\\'" str)
597 (let ((s (match-string 1 str)) ;actual string
598 (lpad (substring str 0 (match-beginning 1))) ;left padding
599 (rpad (concat (substring str (match-end 1)) ;original right padding
600 (substring comment-padding ;additional right padding
601 (min (- (match-end 0) (match-end 1))
602 (length comment-padding)))))
603 ;; We can only duplicate C if the comment-end has multiple chars
604 ;; or if comments can be nested, else the comment-end `}' would
605 ;; be turned into `}}}' where only the first ends the comment
606 ;; and the rest becomes bogus junk.
607 (multi (not (and comment-quote-nested
608 ;; comment-end is a single char
609 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
610 (if (not (symbolp n))
611 (concat lpad s (when multi (make-string n (aref str (1- (match-end 1))))) rpad)
612 ;; construct a regexp that would match anything from just S
613 ;; to any possible output of this function for any N.
614 (concat (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
615 lpad "") ;padding is not required
616 (regexp-quote s)
617 (when multi "+") ;the last char of S might be repeated
618 (mapconcat (lambda (c) (concat (regexp-quote (string c)) "?"))
619 rpad "")))))) ;padding is not required
620
621 (defun comment-padleft (str &optional n)
622 "Construct a string composed of `comment-padding' plus STR.
623 It also adds N copies of the first non-whitespace chars of STR.
624 If STR already contains padding, the corresponding amount is
625 ignored from `comment-padding'.
626 N defaults to 0.
627 If N is `re', a regexp is returned instead, that would match
628 the string for any N."
629 (setq n (or n 0))
630 (when (and (stringp str) (not (string= "" str)))
631 ;; Only separate the left pad because we assume there is no right pad.
632 (string-match "\\`\\s-*" str)
633 (let ((s (substring str (match-end 0)))
634 (pad (concat (substring comment-padding
635 (min (- (match-end 0) (match-beginning 0))
636 (length comment-padding)))
637 (match-string 0 str)))
638 (c (aref str (match-end 0))) ;the first non-space char of STR
639 ;; We can only duplicate C if the comment-end has multiple chars
640 ;; or if comments can be nested, else the comment-end `}' would
641 ;; be turned into `}}}' where only the first ends the comment
642 ;; and the rest becomes bogus junk.
643 (multi (not (and comment-quote-nested
644 ;; comment-end is a single char
645 (string-match "\\`\\s-*\\S-\\s-*\\'" comment-end)))))
646 (if (not (symbolp n))
647 (concat pad (when multi (make-string n c)) s)
648 ;; Construct a regexp that would match anything from just S
649 ;; to any possible output of this function for any N.
650 ;; We match any number of leading spaces because this regexp will
651 ;; be used for uncommenting where we might want to remove
652 ;; uncomment markers with arbitrary leading space (because
653 ;; they were aligned).
654 (concat "\\s-*"
655 (if multi (concat (regexp-quote (string c)) "*"))
656 (regexp-quote s))))))
657
658 ;;;###autoload
659 (defun uncomment-region (beg end &optional arg)
660 "Uncomment each line in the BEG .. END region.
661 The numeric prefix ARG can specify a number of chars to remove from the
662 comment markers."
663 (interactive "*r\nP")
664 (comment-normalize-vars)
665 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
666 (save-excursion
667 (goto-char beg)
668 (setq end (copy-marker end))
669 (let* ((numarg (prefix-numeric-value arg))
670 (ccs comment-continue)
671 (srei (comment-padright ccs 're))
672 (csre (comment-padright comment-start 're))
673 (sre (and srei (concat "^\\s-*?\\(" srei "\\)")))
674 spt)
675 (while (and (< (point) end)
676 (setq spt (comment-search-forward end t)))
677 (let ((ipt (point))
678 ;; Find the end of the comment.
679 (ept (progn
680 (goto-char spt)
681 (unless (comment-forward)
682 (error "Can't find the comment end"))
683 (point)))
684 (box nil)
685 (box-equal nil)) ;Whether we might be using `=' for boxes.
686 (save-restriction
687 (narrow-to-region spt ept)
688
689 ;; Remove the comment-start.
690 (goto-char ipt)
691 (skip-syntax-backward " ")
692 ;; A box-comment starts with a looong comment-start marker.
693 (when (and (or (and (= (- (point) (point-min)) 1)
694 (setq box-equal t)
695 (looking-at "=\\{7\\}")
696 (not (eq (char-before (point-max)) ?\n))
697 (skip-chars-forward "="))
698 (> (- (point) (point-min) (length comment-start)) 7))
699 (> (count-lines (point-min) (point-max)) 2))
700 (setq box t))
701 ;; Skip the padding. Padding can come from comment-padding and/or
702 ;; from comment-start, so we first check comment-start.
703 (if (or (save-excursion (goto-char (point-min)) (looking-at csre))
704 (looking-at (regexp-quote comment-padding)))
705 (goto-char (match-end 0)))
706 (when (and sre (looking-at (concat "\\s-*\n\\s-*" srei)))
707 (goto-char (match-end 0)))
708 (if (null arg) (delete-region (point-min) (point))
709 (skip-syntax-backward " ")
710 (delete-char (- numarg))
711 (unless (or (bobp)
712 (save-excursion (goto-char (point-min))
713 (looking-at comment-start-skip)))
714 ;; If there's something left but it doesn't look like
715 ;; a comment-start any more, just remove it.
716 (delete-region (point-min) (point))))
717
718 ;; Remove the end-comment (and leading padding and such).
719 (goto-char (point-max)) (comment-enter-backward)
720 ;; Check for special `=' used sometimes in comment-box.
721 (when (and box-equal (not (eq (char-before (point-max)) ?\n)))
722 (let ((pos (point)))
723 ;; skip `=' but only if there are at least 7.
724 (when (> (skip-chars-backward "=") -7) (goto-char pos))))
725 (unless (looking-at "\\(\n\\|\\s-\\)*\\'")
726 (when (and (bolp) (not (bobp))) (backward-char))
727 (if (null arg) (delete-region (point) (point-max))
728 (skip-syntax-forward " ")
729 (delete-char numarg)
730 (unless (or (eobp) (looking-at comment-end-skip))
731 ;; If there's something left but it doesn't look like
732 ;; a comment-end any more, just remove it.
733 (delete-region (point) (point-max)))))
734
735 ;; Unquote any nested end-comment.
736 (comment-quote-nested comment-start comment-end t)
737
738 ;; Eliminate continuation markers as well.
739 (when sre
740 (let* ((cce (comment-string-reverse (or comment-continue
741 comment-start)))
742 (erei (and box (comment-padleft cce 're)))
743 (ere (and erei (concat "\\(" erei "\\)\\s-*$"))))
744 (goto-char (point-min))
745 (while (progn
746 (if (and ere (re-search-forward
747 ere (line-end-position) t))
748 (replace-match "" t t nil (if (match-end 2) 2 1))
749 (setq ere nil))
750 (forward-line 1)
751 (re-search-forward sre (line-end-position) t))
752 (replace-match "" t t nil (if (match-end 2) 2 1)))))
753 ;; Go to the end for the next comment.
754 (goto-char (point-max)))))
755 (set-marker end nil))))
756
757 (defun comment-make-extra-lines (cs ce ccs cce min-indent max-indent &optional block)
758 "Make the leading and trailing extra lines.
759 This is used for `extra-line' style (or `box' style if BLOCK is specified)."
760 (let ((eindent 0))
761 (if (not block)
762 ;; Try to match CS and CE's content so they align aesthetically.
763 (progn
764 (setq ce (comment-string-strip ce t t))
765 (when (string-match "\\(.+\\).*\n\\(.*?\\)\\1" (concat ce "\n" cs))
766 (setq eindent
767 (max (- (match-end 2) (match-beginning 2) (match-beginning 0))
768 0))))
769 ;; box comment
770 (let* ((width (- max-indent min-indent))
771 (s (concat cs "a=m" cce))
772 (e (concat ccs "a=m" ce))
773 (c (if (string-match ".*\\S-\\S-" cs)
774 (aref cs (1- (match-end 0)))
775 (if (and (equal comment-end "") (string-match ".*\\S-" cs))
776 (aref cs (1- (match-end 0))) ?=)))
777 (re "\\s-*a=m\\s-*")
778 (_ (string-match re s))
779 (lcs (length cs))
780 (fill
781 (make-string (+ width (- (match-end 0)
782 (match-beginning 0) lcs 3)) c)))
783 (setq cs (replace-match fill t t s))
784 (when (and (not (string-match comment-start-skip cs))
785 (string-match "a=m" s))
786 ;; The whitespace around CS cannot be ignored: put it back.
787 (setq re "a=m")
788 (setq fill (make-string (- width lcs) c))
789 (setq cs (replace-match fill t t s)))
790 (string-match re e)
791 (setq ce (replace-match fill t t e))))
792 (cons (concat cs "\n" (make-string min-indent ? ) ccs)
793 (concat cce "\n" (make-string (+ min-indent eindent) ? ) ce))))
794
795 (defmacro comment-with-narrowing (beg end &rest body)
796 "Execute BODY with BEG..END narrowing.
797 Space is added (and then removed) at the beginning for the text's
798 indentation to be kept as it was before narrowing."
799 (declare (debug t) (indent 2))
800 (let ((bindent (make-symbol "bindent")))
801 `(let ((,bindent (save-excursion (goto-char ,beg) (current-column))))
802 (save-restriction
803 (narrow-to-region ,beg ,end)
804 (goto-char (point-min))
805 (insert (make-string ,bindent ? ))
806 (prog1
807 (progn ,@body)
808 ;; remove the bindent
809 (save-excursion
810 (goto-char (point-min))
811 (when (looking-at " *")
812 (let ((n (min (- (match-end 0) (match-beginning 0)) ,bindent)))
813 (delete-char n)
814 (setq ,bindent (- ,bindent n))))
815 (end-of-line)
816 (let ((e (point)))
817 (beginning-of-line)
818 (while (and (> ,bindent 0) (re-search-forward " *" e t))
819 (let ((n (min ,bindent (- (match-end 0) (match-beginning 0) 1))))
820 (goto-char (match-beginning 0))
821 (delete-char n)
822 (setq ,bindent (- ,bindent n)))))))))))
823
824 (defun comment-region-internal (beg end cs ce
825 &optional ccs cce block lines indent)
826 "Comment region BEG .. END.
827 CS and CE are the comment start resp end string.
828 CCS and CCE are the comment continuation strings for the start resp end
829 of lines (default to CS and CE).
830 BLOCK indicates that end of lines should be marked with either CCE, CE or CS
831 \(if CE is empty) and that those markers should be aligned.
832 LINES indicates that an extra lines will be used at the beginning and end
833 of the region for CE and CS.
834 INDENT indicates to put CS and CCS at the current indentation of the region
835 rather than at left margin."
836 ;;(assert (< beg end))
837 (let ((no-empty (not (or (eq comment-empty-lines t)
838 (and comment-empty-lines (zerop (length ce)))))))
839 ;; Sanitize CE and CCE.
840 (if (and (stringp ce) (string= "" ce)) (setq ce nil))
841 (if (and (stringp cce) (string= "" cce)) (setq cce nil))
842 ;; If CE is empty, multiline cannot be used.
843 (unless ce (setq ccs nil cce nil))
844 ;; Should we mark empty lines as well ?
845 (if (or ccs block lines) (setq no-empty nil))
846 ;; Make sure we have end-markers for BLOCK mode.
847 (when block (unless ce (setq ce (comment-string-reverse cs))))
848 ;; If BLOCK is not requested, we don't need CCE.
849 (unless block (setq cce nil))
850 ;; Continuation defaults to the same as CS and CE.
851 (unless ccs (setq ccs cs cce ce))
852
853 (save-excursion
854 (goto-char end)
855 ;; If the end is not at the end of a line and the comment-end
856 ;; is implicit (i.e. a newline), explicitly insert a newline.
857 (unless (or ce (eolp)) (insert "\n") (indent-according-to-mode))
858 (comment-with-narrowing beg end
859 (let ((min-indent (point-max))
860 (max-indent 0))
861 (goto-char (point-min))
862 ;; Quote any nested comment marker
863 (comment-quote-nested comment-start comment-end nil)
864
865 ;; Loop over all lines to find the needed indentations.
866 (goto-char (point-min))
867 (while
868 (progn
869 (unless (looking-at "[ \t]*$")
870 (setq min-indent (min min-indent (current-indentation))))
871 (end-of-line)
872 (setq max-indent (max max-indent (current-column)))
873 (not (or (eobp) (progn (forward-line) nil)))))
874
875 ;; Inserting ccs can change max-indent by (1- tab-width).
876 (setq max-indent
877 (+ max-indent (max (length cs) (length ccs)) tab-width -1))
878 (unless indent (setq min-indent 0))
879
880 ;; make the leading and trailing lines if requested
881 (when lines
882 (let ((csce
883 (comment-make-extra-lines
884 cs ce ccs cce min-indent max-indent block)))
885 (setq cs (car csce))
886 (setq ce (cdr csce))))
887
888 (goto-char (point-min))
889 ;; Loop over all lines from BEG to END.
890 (while
891 (progn
892 (unless (and no-empty (looking-at "[ \t]*$"))
893 (move-to-column min-indent t)
894 (insert cs) (setq cs ccs) ;switch to CCS after the first line
895 (end-of-line)
896 (if (eobp) (setq cce ce))
897 (when cce
898 (when block (move-to-column max-indent t))
899 (insert cce)))
900 (end-of-line)
901 (not (or (eobp) (progn (forward-line) nil))))))))))
902
903 ;;;###autoload
904 (defun comment-region (beg end &optional arg)
905 "Comment or uncomment each line in the region.
906 With just \\[universal-argument] prefix arg, uncomment each line in region BEG .. END.
907 Numeric prefix arg ARG means use ARG comment characters.
908 If ARG is negative, delete that many comment characters instead.
909 By default, comments start at the left margin, are terminated on each line,
910 even for syntax in which newline does not end the comment and blank lines
911 do not get comments. This can be changed with `comment-style'.
912
913 The strings used as comment starts are built from
914 `comment-start' without trailing spaces and `comment-padding'."
915 (interactive "*r\nP")
916 (comment-normalize-vars)
917 (if (> beg end) (let (mid) (setq mid beg beg end end mid)))
918 (let* ((numarg (prefix-numeric-value arg))
919 (add comment-add)
920 (style (cdr (assoc comment-style comment-styles)))
921 (lines (nth 2 style))
922 (block (nth 1 style))
923 (multi (nth 0 style)))
924 (save-excursion
925 ;; we use `chars' instead of `syntax' because `\n' might be
926 ;; of end-comment syntax rather than of whitespace syntax.
927 ;; sanitize BEG and END
928 (goto-char beg) (skip-chars-forward " \t\n\r") (beginning-of-line)
929 (setq beg (max beg (point)))
930 (goto-char end) (skip-chars-backward " \t\n\r") (end-of-line)
931 (setq end (min end (point)))
932 (if (>= beg end) (error "Nothing to comment"))
933
934 ;; sanitize LINES
935 (setq lines
936 (and
937 lines ;; multi
938 (progn (goto-char beg) (beginning-of-line)
939 (skip-syntax-forward " ")
940 (>= (point) beg))
941 (progn (goto-char end) (end-of-line) (skip-syntax-backward " ")
942 (<= (point) end))
943 (or block (not (string= "" comment-end)))
944 (or block (progn (goto-char beg) (search-forward "\n" end t))))))
945
946 ;; don't add end-markers just because the user asked for `block'
947 (unless (or lines (string= "" comment-end)) (setq block nil))
948
949 (cond
950 ((consp arg) (uncomment-region beg end))
951 ((< numarg 0) (uncomment-region beg end (- numarg)))
952 (t
953 (setq numarg (if (and (null arg) (= (length comment-start) 1))
954 add (1- numarg)))
955 (comment-region-internal
956 beg end
957 (let ((s (comment-padright comment-start numarg)))
958 (if (string-match comment-start-skip s) s
959 (comment-padright comment-start)))
960 (let ((s (comment-padleft comment-end numarg)))
961 (and s (if (string-match comment-end-skip s) s
962 (comment-padright comment-end))))
963 (if multi (comment-padright comment-continue numarg))
964 (if multi (comment-padleft (comment-string-reverse comment-continue) numarg))
965 block
966 lines
967 (nth 3 style))))))
968
969 (defun comment-box (beg end &optional arg)
970 "Comment out the BEG .. END region, putting it inside a box.
971 The numeric prefix ARG specifies how many characters to add to begin- and
972 end- comment markers additionally to what `comment-add' already specifies."
973 (interactive "*r\np")
974 (let ((comment-style (if (cadr (assoc comment-style comment-styles))
975 'box-multi 'box)))
976 (comment-region beg end (+ comment-add arg))))
977
978
979 ;;;###autoload
980 (defun comment-or-uncomment-region (beg end &optional arg)
981 "Call `comment-region', unless the region only consists of comments,
982 in which case call `uncomment-region'. If a prefix arg is given, it
983 is passed on to the respective function."
984 (interactive "*r\nP")
985 (comment-normalize-vars)
986 (funcall (if (save-excursion ;; check for already commented region
987 (goto-char beg)
988 (comment-forward (point-max))
989 (<= end (point)))
990 'uncomment-region 'comment-region)
991 beg end arg))
992
993 ;;;###autoload
994 (defun comment-dwim (arg)
995 "Call the comment command you want (Do What I Mean).
996 If the region is active and `transient-mark-mode' is on, call
997 `comment-region' (unless it only consists of comments, in which
998 case it calls `uncomment-region').
999 Else, if the current line is empty, insert a comment and indent it.
1000 Else if a prefix ARG is specified, call `comment-kill'.
1001 Else, call `comment-indent'."
1002 (interactive "*P")
1003 (comment-normalize-vars)
1004 (if (and mark-active transient-mark-mode)
1005 (comment-or-uncomment-region (region-beginning) (region-end) arg)
1006 (if (save-excursion (beginning-of-line) (not (looking-at "\\s-*$")))
1007 ;; FIXME: If there's no comment to kill on this line and ARG is
1008 ;; specified, calling comment-kill is not very clever.
1009 (if arg (comment-kill (and (integerp arg) arg)) (comment-indent))
1010 (let ((add (if arg (prefix-numeric-value arg)
1011 (if (= (length comment-start) 1) comment-add 0))))
1012 ;; Some modes insist on keeping column 0 comment in column 0
1013 ;; so we need to move away from it before inserting the comment.
1014 (indent-according-to-mode)
1015 (insert (comment-padright comment-start add))
1016 (save-excursion
1017 (unless (string= "" comment-end)
1018 (insert (comment-padleft comment-end add)))
1019 (indent-according-to-mode))))))
1020
1021 (defcustom comment-auto-fill-only-comments nil
1022 "Non-nil means to only auto-fill inside comments.
1023 This has no effect in modes that do not define a comment syntax."
1024 :type 'boolean)
1025
1026 (defun comment-valid-prefix-p (prefix compos)
1027 (or
1028 ;; Accept any prefix if the current comment is not EOL-terminated.
1029 (save-excursion (goto-char compos) (comment-forward) (not (bolp)))
1030 ;; Accept any prefix that starts with a comment-start marker.
1031 (string-match (concat "\\`[ \t]*\\(?:" comment-start-skip "\\)")
1032 prefix)))
1033
1034 ;;;###autoload
1035 (defun comment-indent-new-line (&optional soft)
1036 "Break line at point and indent, continuing comment if within one.
1037 This indents the body of the continued comment
1038 under the previous comment line.
1039
1040 This command is intended for styles where you write a comment per line,
1041 starting a new comment (and terminating it if necessary) on each line.
1042 If you want to continue one comment across several lines, use \\[newline-and-indent].
1043
1044 If a fill column is specified, it overrides the use of the comment column
1045 or comment indentation.
1046
1047 The inserted newline is marked hard if variable `use-hard-newlines' is true,
1048 unless optional argument SOFT is non-nil."
1049 (interactive)
1050 (comment-normalize-vars t)
1051 (let (compos comin)
1052 ;; If we are not inside a comment and we only auto-fill comments,
1053 ;; don't do anything (unless no comment syntax is defined).
1054 (unless (and comment-start
1055 comment-auto-fill-only-comments
1056 (not (interactive-p))
1057 (not (save-excursion
1058 (prog1 (setq compos (comment-beginning))
1059 (setq comin (point))))))
1060
1061 ;; Now we know we should auto-fill.
1062 ;; Insert the newline before removing empty space so that markers
1063 ;; get preserved better.
1064 (if soft (insert-and-inherit ?\n) (newline 1))
1065 (save-excursion (forward-char -1) (delete-horizontal-space))
1066 (delete-horizontal-space)
1067
1068 (if (and fill-prefix (not adaptive-fill-mode))
1069 ;; Blindly trust a non-adaptive fill-prefix.
1070 (progn
1071 (indent-to-left-margin)
1072 (insert-before-markers-and-inherit fill-prefix))
1073
1074 ;; If necessary check whether we're inside a comment.
1075 (unless (or compos (null comment-start))
1076 (save-excursion
1077 (backward-char)
1078 (setq compos (comment-beginning))
1079 (setq comin (point))))
1080
1081 (cond
1082 ;; If there's an adaptive prefix, use it unless we're inside
1083 ;; a comment and the prefix is not a comment starter.
1084 ((and fill-prefix
1085 (or (not compos)
1086 (comment-valid-prefix-p fill-prefix compos)))
1087 (indent-to-left-margin)
1088 (insert-and-inherit fill-prefix))
1089 ;; If we're not inside a comment, just try to indent.
1090 ((not compos) (indent-according-to-mode))
1091 (t
1092 (let* ((comment-column
1093 ;; The continuation indentation should be somewhere between
1094 ;; the current line's indentation (plus 2 for good measure)
1095 ;; and the current comment's indentation, with a preference
1096 ;; for comment-column.
1097 (save-excursion
1098 ;; FIXME: use prev line's info rather than first line's.
1099 (goto-char compos)
1100 (min (current-column) (max comment-column
1101 (+ 2 (current-indentation))))))
1102 (comstart (buffer-substring compos comin))
1103 (normalp
1104 (string-match (regexp-quote (comment-string-strip
1105 comment-start t t))
1106 comstart))
1107 (comment-end
1108 (if normalp comment-end
1109 ;; The comment starter is not the normal comment-start
1110 ;; so we can't just use comment-end.
1111 (save-excursion
1112 (goto-char compos)
1113 (if (not (comment-forward)) comment-end
1114 (comment-string-strip
1115 (buffer-substring
1116 (save-excursion (comment-enter-backward) (point))
1117 (point))
1118 nil t)))))
1119 (comment-start comstart)
1120 (continuep (or comment-multi-line
1121 (cadr (assoc comment-style comment-styles))))
1122 ;; Force comment-continue to be recreated from comment-start.
1123 ;; FIXME: wrong if comment-continue was set explicitly!
1124 ;; FIXME: use prev line's continuation if available.
1125 (comment-continue nil))
1126 (if (and comment-multi-line (> (length comment-end) 0))
1127 (indent-according-to-mode)
1128 (insert-and-inherit ?\n)
1129 (forward-char -1)
1130 (comment-indent continuep)
1131 (save-excursion
1132 (let ((pt (point)))
1133 (end-of-line)
1134 (let ((comend (buffer-substring pt (point))))
1135 ;; The 1+ is to make sure we delete the \n inserted above.
1136 (delete-region pt (1+ (point)))
1137 (end-of-line 0)
1138 (insert comend))))))))))))
1139
1140 (provide 'newcomment)
1141
1142 ;;; arch-tag: 01e3320a-00c8-44ea-a696-8f8e7354c858
1143 ;;; newcomment.el ends here