(gnus-summary-set-local-parameters): Always evaluate parameter's operands.
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
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 3 of the License, or
14 ;; (at your option) 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.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Nothing in this file depends on any other parts of Gnus -- all
27 ;; functions and macros in this file are utility functions that are
28 ;; used by Gnus and may be used by any other package without loading
29 ;; Gnus first.
30
31 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
32 ;; autoloads and defvars below...]
33
34 ;;; Code:
35
36 ;; For Emacs < 22.2.
37 (eval-and-compile
38   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
39 (eval-when-compile
40   (require 'cl))
41 ;; Fixme: this should be a gnus variable, not nnmail-.
42 (defvar nnmail-pathname-coding-system)
43 (defvar nnmail-active-file-coding-system)
44
45 ;; Inappropriate references to other parts of Gnus.
46 (defvar gnus-emphasize-whitespace-regexp)
47 (defvar gnus-original-article-buffer)
48 (defvar gnus-user-agent)
49
50 (require 'time-date)
51 (require 'netrc)
52
53 (autoload 'message-fetch-field "message")
54 (autoload 'gnus-get-buffer-window "gnus-win")
55 (autoload 'rmail-insert-rmail-file-header "rmail")
56 (autoload 'rmail-count-new-messages "rmail")
57 (autoload 'rmail-show-message "rmail")
58 (autoload 'nnheader-narrow-to-headers "nnheader")
59 (autoload 'nnheader-replace-chars-in-string "nnheader")
60 (autoload 'mail-header-remove-comments "mail-parse")
61
62 (eval-and-compile
63   (cond
64    ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
65    ;; SXEmacs 22.1.4) over `replace-in-string'.  The latter leads to inf-loops
66    ;; on empty matches:
67    ;;   (replace-in-string "foo" "/*$" "/")
68    ;;   (replace-in-string "xe" "\\(x\\)?" "")
69    ((fboundp 'replace-regexp-in-string)
70     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
71       "Replace all matches for REGEXP with NEWTEXT in STRING.
72 If LITERAL is non-nil, insert NEWTEXT literally.  Return a new
73 string containing the replacements.
74
75 This is a compatibility function for different Emacsen."
76       (replace-regexp-in-string regexp newtext string nil literal)))
77    ((fboundp 'replace-in-string)
78     (defalias 'gnus-replace-in-string 'replace-in-string))))
79
80 (defun gnus-boundp (variable)
81   "Return non-nil if VARIABLE is bound and non-nil."
82   (and (boundp variable)
83        (symbol-value variable)))
84
85 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
86   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
87   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
88         (w (make-symbol "w"))
89         (buf (make-symbol "buf")))
90     `(let* ((,tempvar (selected-window))
91             (,buf ,buffer)
92             (,w (gnus-get-buffer-window ,buf 'visible)))
93        (unwind-protect
94            (progn
95              (if ,w
96                  (progn
97                    (select-window ,w)
98                    (set-buffer (window-buffer ,w)))
99                (pop-to-buffer ,buf))
100              ,@forms)
101          (select-window ,tempvar)))))
102
103 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
104 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
105
106 (defmacro gnus-intern-safe (string hashtable)
107   "Get hash value.  Arguments are STRING and HASHTABLE."
108   `(let ((symbol (intern ,string ,hashtable)))
109      (or (boundp symbol)
110          (set symbol nil))
111      symbol))
112
113 (defsubst gnus-goto-char (point)
114   (and point (goto-char point)))
115
116 (defmacro gnus-buffer-exists-p (buffer)
117   `(let ((buffer ,buffer))
118      (when buffer
119        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
120                 buffer))))
121
122 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
123 ;; XEmacs.  In Emacs we don't need to call `make-local-hook' first.
124 ;; It's harmless, though, so the main purpose of this alias is to shut
125 ;; up the byte compiler.
126 (defalias 'gnus-make-local-hook
127   (if (eq (get 'make-local-hook 'byte-compile)
128           'byte-compile-obsolete)
129       'ignore                           ; Emacs
130     'make-local-hook))                  ; XEmacs
131
132 (defun gnus-delete-first (elt list)
133   "Delete by side effect the first occurrence of ELT as a member of LIST."
134   (if (equal (car list) elt)
135       (cdr list)
136     (let ((total list))
137       (while (and (cdr list)
138                   (not (equal (cadr list) elt)))
139         (setq list (cdr list)))
140       (when (cdr list)
141         (setcdr list (cddr list)))
142       total)))
143
144 ;; Delete the current line (and the next N lines).
145 (defmacro gnus-delete-line (&optional n)
146   `(delete-region (point-at-bol)
147                   (progn (forward-line ,(or n 1)) (point))))
148
149 (defun gnus-byte-code (func)
150   "Return a form that can be `eval'ed based on FUNC."
151   (let ((fval (indirect-function func)))
152     (if (byte-code-function-p fval)
153         (let ((flist (append fval nil)))
154           (setcar flist 'byte-code)
155           flist)
156       (cons 'progn (cddr fval)))))
157
158 (defun gnus-extract-address-components (from)
159   "Extract address components from a From header.
160 Given an RFC-822 address FROM, extract full name and canonical address.
161 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).  Much more simple
162 solution than `mail-extract-address-components', which works much better, but
163 is slower."
164   (let (name address)
165     ;; First find the address - the thing with the @ in it.  This may
166     ;; not be accurate in mail addresses, but does the trick most of
167     ;; the time in news messages.
168     (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
169            ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
170            ;; correctly.
171            (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
172            (setq address (substring from (match-beginning 1) (match-end 1))))
173           ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
174            (setq address (substring from (match-beginning 0) (match-end 0)))))
175     ;; Then we check whether the "name <address>" format is used.
176     (and address
177          ;; Linear white space is not required.
178          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
179          (and (setq name (substring from 0 (match-beginning 0)))
180               ;; Strip any quotes from the name.
181               (string-match "^\".*\"$" name)
182               (setq name (substring name 1 (1- (match-end 0))))))
183     ;; If not, then "address (name)" is used.
184     (or name
185         (and (string-match "(.+)" from)
186              (setq name (substring from (1+ (match-beginning 0))
187                                    (1- (match-end 0)))))
188         (and (string-match "()" from)
189              (setq name address))
190         ;; XOVER might not support folded From headers.
191         (and (string-match "(.*" from)
192              (setq name (substring from (1+ (match-beginning 0))
193                                    (match-end 0)))))
194     (list (if (string= name "") nil name) (or address from))))
195
196 (defun gnus-extract-address-component-name (from)
197   "Extract name from a From header.
198 Uses `gnus-extract-address-components'."
199   (nth 0 (gnus-extract-address-components from)))
200
201 (defun gnus-extract-address-component-email (from)
202   "Extract e-mail address from a From header.
203 Uses `gnus-extract-address-components'."
204   (nth 1 (gnus-extract-address-components from)))
205
206 (defun gnus-fetch-field (field)
207   "Return the value of the header FIELD of current article."
208   (save-excursion
209     (save-restriction
210       (let ((inhibit-point-motion-hooks t))
211         (nnheader-narrow-to-headers)
212         (message-fetch-field field)))))
213
214 (defun gnus-fetch-original-field (field)
215   "Fetch FIELD from the original version of the current article."
216   (with-current-buffer gnus-original-article-buffer
217     (gnus-fetch-field field)))
218
219
220 (defun gnus-goto-colon ()
221   (beginning-of-line)
222   (let ((eol (point-at-eol)))
223     (goto-char (or (text-property-any (point) eol 'gnus-position t)
224                    (search-forward ":" eol t)
225                    (point)))))
226
227 (declare-function gnus-find-method-for-group "gnus" (group &optional info))
228 (autoload 'gnus-group-name-decode "gnus-group")
229 (declare-function gnus-group-name-charset "gnus-group" (method group))
230 ;; gnus-group requires gnus-int which requires message.
231 (declare-function message-tokenize-header "message"
232                   (header &optional separator))
233
234 (defun gnus-decode-newsgroups (newsgroups group &optional method)
235   (let ((method (or method (gnus-find-method-for-group group))))
236     (mapconcat (lambda (group)
237                  (gnus-group-name-decode group (gnus-group-name-charset
238                                                 method group)))
239                (message-tokenize-header newsgroups)
240                ",")))
241
242 (defun gnus-remove-text-with-property (prop)
243   "Delete all text in the current buffer with text property PROP."
244   (let ((start (point-min))
245         end)
246     (unless (get-text-property start prop)
247       (setq start (next-single-property-change start prop)))
248     (while start
249       (setq end (text-property-any start (point-max) prop nil))
250       (delete-region start (or end (point-max)))
251       (setq start (when end
252                     (next-single-property-change start prop))))))
253
254 (defun gnus-newsgroup-directory-form (newsgroup)
255   "Make hierarchical directory name from NEWSGROUP name."
256   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
257          (idx (string-match ":" newsgroup)))
258     (concat
259      (if idx (substring newsgroup 0 idx))
260      (if idx "/")
261      (nnheader-replace-chars-in-string
262       (if idx (substring newsgroup (1+ idx)) newsgroup)
263       ?. ?/))))
264
265 (defun gnus-newsgroup-savable-name (group)
266   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
267   ;; with dots.
268   (nnheader-replace-chars-in-string group ?/ ?.))
269
270 (defun gnus-string> (s1 s2)
271   (not (or (string< s1 s2)
272            (string= s1 s2))))
273
274 (defun gnus-string< (s1 s2)
275   "Return t if first arg string is less than second in lexicographic order.
276 Case is significant if and only if `case-fold-search' is nil.
277 Symbols are also allowed; their print names are used instead."
278   (if case-fold-search
279       (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
280                     (downcase (if (symbolp s2) (symbol-name s2) s2)))
281     (string-lessp s1 s2)))
282
283 ;;; Time functions.
284
285 (defun gnus-file-newer-than (file date)
286   (let ((fdate (nth 5 (file-attributes file))))
287     (or (> (car fdate) (car date))
288         (and (= (car fdate) (car date))
289              (> (nth 1 fdate) (nth 1 date))))))
290
291 ;;; Keymap macros.
292
293 (defmacro gnus-local-set-keys (&rest plist)
294   "Set the keys in PLIST in the current keymap."
295   `(gnus-define-keys-1 (current-local-map) ',plist))
296
297 (defmacro gnus-define-keys (keymap &rest plist)
298   "Define all keys in PLIST in KEYMAP."
299   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
300
301 (defmacro gnus-define-keys-safe (keymap &rest plist)
302   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
303   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
304
305 (put 'gnus-define-keys 'lisp-indent-function 1)
306 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
307 (put 'gnus-local-set-keys 'lisp-indent-function 1)
308
309 (defmacro gnus-define-keymap (keymap &rest plist)
310   "Define all keys in PLIST in KEYMAP."
311   `(gnus-define-keys-1 ,keymap (quote ,plist)))
312
313 (put 'gnus-define-keymap 'lisp-indent-function 1)
314
315 (defun gnus-define-keys-1 (keymap plist &optional safe)
316   (when (null keymap)
317     (error "Can't set keys in a null keymap"))
318   (cond ((symbolp keymap)
319          (setq keymap (symbol-value keymap)))
320         ((keymapp keymap))
321         ((listp keymap)
322          (set (car keymap) nil)
323          (define-prefix-command (car keymap))
324          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
325          (setq keymap (symbol-value (car keymap)))))
326   (let (key)
327     (while plist
328       (when (symbolp (setq key (pop plist)))
329         (setq key (symbol-value key)))
330       (if (or (not safe)
331               (eq (lookup-key keymap key) 'undefined))
332           (define-key keymap key (pop plist))
333         (pop plist)))))
334
335 (defun gnus-completing-read-with-default (default prompt &rest args)
336   ;; Like `completing-read', except that DEFAULT is the default argument.
337   (let* ((prompt (if default
338                      (concat prompt " (default " default "): ")
339                    (concat prompt ": ")))
340          (answer (apply 'completing-read prompt args)))
341     (if (or (null answer) (zerop (length answer)))
342         default
343       answer)))
344
345 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
346 ;; the echo area.
347 ;;
348 ;; Do we really need these functions?  Workarounds for bugs in the corresponding
349 ;; Emacs functions?  Maybe these bugs are no longer present in any supported
350 ;; (X)Emacs version?  Alias them to the original functions and see if anyone
351 ;; reports a problem.  If not, replace with original functions.  --rsteib,
352 ;; 2007-12-14
353 ;;
354 ;; All supported Emacsen clear the echo area after `yes-or-no-p', so we can
355 ;; remove `yes-or-no-p'.  RMS says that not clearing after `y-or-n-p' is
356 ;; intentional (see below), so we could remove `gnus-y-or-n-p' too.
357 ;; Objections?  --rsteib, 2008-02-16
358 ;;
359 ;; ,----[ http://thread.gmane.org/gmane.emacs.gnus.general/65099/focus=66070 ]
360 ;; | From: Richard Stallman
361 ;; | Subject: Re: Do we need gnus-yes-or-no-p and gnus-y-or-n-p?
362 ;; | To: Katsumi Yamaoka [...]
363 ;; | Cc: emacs-devel@[...], xemacs-beta@[...], ding@[...]
364 ;; | Date: Mon, 07 Jan 2008 12:16:05 -0500
365 ;; | Message-ID: <E1JBva1-000528-VY@fencepost.gnu.org>
366 ;; |
367 ;; |     The behavior of `y-or-n-p' that it doesn't clear the question
368 ;; |     and the answer is not serious of course, but I feel it is not
369 ;; |     cool.
370 ;; |
371 ;; | It is intentional.
372 ;; |
373 ;; |     Currently, it is commented out in the trunk by Reiner Steib.  He
374 ;; |     also wrote the benefit of leaving the question and the answer in
375 ;; |     the echo area as follows:
376 ;; |
377 ;; |     (http://article.gmane.org/gmane.emacs.gnus.general/66061)
378 ;; |     > In contrast to yes-or-no-p it is much easier to type y, n,
379 ;; |     > SPC, DEL, etc accidentally, so it might be useful for the user
380 ;; |     > to see what he has typed.
381 ;; |
382 ;; | Yes, that is the reason.
383 ;; `----
384
385 ;; (defun gnus-y-or-n-p (prompt)
386 ;;   (prog1
387 ;;       (y-or-n-p prompt)
388 ;;     (message "")))
389 ;; (defun gnus-yes-or-no-p (prompt)
390 ;;   (prog1
391 ;;       (yes-or-no-p prompt)
392 ;;     (message "")))
393
394 (defalias 'gnus-y-or-n-p 'y-or-n-p)
395 (defalias 'gnus-yes-or-no-p 'yes-or-no-p)
396
397 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
398 ;; age-depending date representations. (e.g. just the time if it's
399 ;; from today, the day of the week if it's within the last 7 days and
400 ;; the full date if it's older)
401
402 (defun gnus-seconds-today ()
403   "Return the number of seconds passed today."
404   (let ((now (decode-time (current-time))))
405     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
406
407 (defun gnus-seconds-month ()
408   "Return the number of seconds passed this month."
409   (let ((now (decode-time (current-time))))
410     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
411        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
412
413 (defun gnus-seconds-year ()
414   "Return the number of seconds passed this year."
415   (let ((now (decode-time (current-time)))
416         (days (format-time-string "%j" (current-time))))
417     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
418        (* (- (string-to-number days) 1) 3600 24))))
419
420 (defvar gnus-user-date-format-alist
421   '(((gnus-seconds-today) . "%k:%M")
422     (604800 . "%a %k:%M")                   ;;that's one week
423     ((gnus-seconds-month) . "%a %d")
424     ((gnus-seconds-year) . "%b %d")
425     (t . "%b %d '%y"))                      ;;this one is used when no
426                                             ;;other does match
427   "Specifies date format depending on age of article.
428 This is an alist of items (AGE . FORMAT).  AGE can be a number (of
429 seconds) or a Lisp expression evaluating to a number.  When the age of
430 the article is less than this number, then use `format-time-string'
431 with the corresponding FORMAT for displaying the date of the article.
432 If AGE is not a number or a Lisp expression evaluating to a
433 non-number, then the corresponding FORMAT is used as a default value.
434
435 Note that the list is processed from the beginning, so it should be
436 sorted by ascending AGE.  Also note that items following the first
437 non-number AGE will be ignored.
438
439 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
440 and `gnus-seconds-year' in the AGE spec.  They return the number of
441 seconds passed since the start of today, of this month, of this year,
442 respectively.")
443
444 (defun gnus-user-date (messy-date)
445   "Format the messy-date according to gnus-user-date-format-alist.
446 Returns \"  ?  \" if there's bad input or if an other error occurs.
447 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
448   (condition-case ()
449       (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
450              (now (time-to-seconds (current-time)))
451              ;;If we don't find something suitable we'll use this one
452              (my-format "%b %d '%y"))
453         (let* ((difference (- now messy-date))
454                (templist gnus-user-date-format-alist)
455                (top (eval (caar templist))))
456           (while (if (numberp top) (< top difference) (not top))
457             (progn
458               (setq templist (cdr templist))
459               (setq top (eval (caar templist)))))
460           (if (stringp (cdr (car templist)))
461               (setq my-format (cdr (car templist)))))
462         (format-time-string (eval my-format) (seconds-to-time messy-date)))
463     (error "  ?   ")))
464
465 (defun gnus-dd-mmm (messy-date)
466   "Return a string like DD-MMM from a big messy string."
467   (condition-case ()
468       (format-time-string "%d-%b" (safe-date-to-time messy-date))
469     (error "  -   ")))
470
471 (defmacro gnus-date-get-time (date)
472   "Convert DATE string to Emacs time.
473 Cache the result as a text property stored in DATE."
474   ;; Either return the cached value...
475   `(let ((d ,date))
476      (if (equal "" d)
477          '(0 0)
478        (or (get-text-property 0 'gnus-time d)
479            ;; or compute the value...
480            (let ((time (safe-date-to-time d)))
481              ;; and store it back in the string.
482              (put-text-property 0 1 'gnus-time time d)
483              time)))))
484
485 (defsubst gnus-time-iso8601 (time)
486   "Return a string of TIME in YYYYMMDDTHHMMSS format."
487   (format-time-string "%Y%m%dT%H%M%S" time))
488
489 (defun gnus-date-iso8601 (date)
490   "Convert the DATE to YYYYMMDDTHHMMSS."
491   (condition-case ()
492       (gnus-time-iso8601 (gnus-date-get-time date))
493     (error "")))
494
495 (defun gnus-mode-string-quote (string)
496   "Quote all \"%\"'s in STRING."
497   (gnus-replace-in-string string "%" "%%"))
498
499 ;; Make a hash table (default and minimum size is 256).
500 ;; Optional argument HASHSIZE specifies the table size.
501 (defun gnus-make-hashtable (&optional hashsize)
502   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
503
504 ;; Make a number that is suitable for hashing; bigger than MIN and
505 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
506 ;; hardware modulo operation, so they implement it in software.  On
507 ;; many sparcs over 50% of the time to intern is spent in the modulo.
508 ;; Yes, it's slower than actually computing the hash from the string!
509 ;; So we use powers of 2 so people can optimize the modulo to a mask.
510 (defun gnus-create-hash-size (min)
511   (let ((i 1))
512     (while (< i min)
513       (setq i (* 2 i)))
514     i))
515
516 (defcustom gnus-verbose 7
517   "*Integer that says how verbose Gnus should be.
518 The higher the number, the more messages Gnus will flash to say what
519 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
520 display most important messages; and at ten, Gnus will keep on
521 jabbering all the time."
522   :group 'gnus-start
523   :type 'integer)
524
525 (defcustom gnus-add-timestamp-to-message nil
526   "Non-nil means add timestamps to messages that Gnus issues.
527 If it is `log', add timestamps to only the messages that go into the
528 \"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
529 If it is neither nil nor `log', add timestamps not only to log messages
530 but also to the ones displayed in the echo area."
531   :version "23.1" ;; No Gnus
532   :group  'gnus-various
533   :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
534                  (const :tag "Logged messages only" log)
535                  (sexp :tag "All messages"
536                        :match (lambda (widget value) value)
537                        :value t)
538                  (const :tag "No timestamp" nil)))
539
540 (eval-when-compile
541   (defmacro gnus-message-with-timestamp-1 (format-string args)
542     (let ((timestamp '((format-time-string "%Y%m%dT%H%M%S" time)
543                        "." (format "%03d" (/ (nth 2 time) 1000)) "> ")))
544       (if (featurep 'xemacs)
545           `(let (str time)
546              (if (or (and (null ,format-string) (null ,args))
547                      (progn
548                        (setq str (apply 'format ,format-string ,args))
549                        (zerop (length str))))
550                  (prog1
551                      (and ,format-string str)
552                    (clear-message nil))
553                (cond ((eq gnus-add-timestamp-to-message 'log)
554                       (setq time (current-time))
555                       (display-message 'no-log str)
556                       (log-message 'message (concat ,@timestamp str)))
557                      (gnus-add-timestamp-to-message
558                       (setq time (current-time))
559                       (display-message 'message (concat ,@timestamp str)))
560                      (t
561                       (display-message 'message str))))
562              str)
563         `(let (str time)
564            (cond ((eq gnus-add-timestamp-to-message 'log)
565                   (setq str (let (message-log-max)
566                               (apply 'message ,format-string ,args)))
567                   (when (and message-log-max
568                              (> message-log-max 0)
569                              (/= (length str) 0))
570                     (setq time (current-time))
571                     (with-current-buffer (get-buffer-create "*Messages*")
572                       (goto-char (point-max))
573                       (insert ,@timestamp str "\n")
574                       (forward-line (- message-log-max))
575                       (delete-region (point-min) (point))
576                       (goto-char (point-max))))
577                   str)
578                  (gnus-add-timestamp-to-message
579                   (if (or (and (null ,format-string) (null ,args))
580                           (progn
581                             (setq str (apply 'format ,format-string ,args))
582                             (zerop (length str))))
583                       (prog1
584                           (and ,format-string str)
585                         (message nil))
586                     (setq time (current-time))
587                     (message "%s" (concat ,@timestamp str))
588                     str))
589                  (t
590                   (apply 'message ,format-string ,args))))))))
591
592 (defun gnus-message-with-timestamp (format-string &rest args)
593   "Display message with timestamp.  Arguments are the same as `message'.
594 The `gnus-add-timestamp-to-message' variable controls how to add
595 timestamp to message."
596   (gnus-message-with-timestamp-1 format-string args))
597
598 (defun gnus-message (level &rest args)
599   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
600
601 Guideline for numbers:
602 1 - error messages, 3 - non-serious error messages, 5 - messages for things
603 that take a long time, 7 - not very important messages on stuff, 9 - messages
604 inside loops."
605   (if (<= level gnus-verbose)
606       (if gnus-add-timestamp-to-message
607           (apply 'gnus-message-with-timestamp args)
608         (apply 'message args))
609     ;; We have to do this format thingy here even if the result isn't
610     ;; shown - the return value has to be the same as the return value
611     ;; from `message'.
612     (apply 'format args)))
613
614 (defun gnus-error (level &rest args)
615   "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
616 ARGS are passed to `message'."
617   (when (<= (floor level) gnus-verbose)
618     (apply 'message args)
619     (ding)
620     (let (duration)
621       (when (and (floatp level)
622                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
623         (sit-for duration))))
624   nil)
625
626 (defun gnus-split-references (references)
627   "Return a list of Message-IDs in REFERENCES."
628   (let ((beg 0)
629         (references (mail-header-remove-comments (or references "")))
630         ids)
631     (while (string-match "<[^<]+[^< \t]" references beg)
632       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
633             ids))
634     (nreverse ids)))
635
636 (defun gnus-extract-references (references)
637   "Return a list of Message-IDs in REFERENCES (in In-Reply-To
638   format), trimmed to only contain the Message-IDs."
639   (let ((ids (gnus-split-references references))
640         refs)
641     (dolist (id ids)
642       (when (string-match "<[^<>]+>" id)
643         (push (match-string 0 id) refs)))
644     refs))
645
646 (defsubst gnus-parent-id (references &optional n)
647   "Return the last Message-ID in REFERENCES.
648 If N, return the Nth ancestor instead."
649   (when (and references
650              (not (zerop (length references))))
651     (if n
652         (let ((ids (inline (gnus-split-references references))))
653           (while (nthcdr n ids)
654             (setq ids (cdr ids)))
655           (car ids))
656       (let ((references (mail-header-remove-comments references)))
657         (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
658           (match-string 1 references))))))
659
660 (defun gnus-buffer-live-p (buffer)
661   "Say whether BUFFER is alive or not."
662   (and buffer
663        (get-buffer buffer)
664        (buffer-name (get-buffer buffer))))
665
666 (defun gnus-horizontal-recenter ()
667   "Recenter the current buffer horizontally."
668   (if (< (current-column) (/ (window-width) 2))
669       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
670     (let* ((orig (point))
671            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
672            (max 0))
673       (when end
674         ;; Find the longest line currently displayed in the window.
675         (goto-char (window-start))
676         (while (and (not (eobp))
677                     (< (point) end))
678           (end-of-line)
679           (setq max (max max (current-column)))
680           (forward-line 1))
681         (goto-char orig)
682         ;; Scroll horizontally to center (sort of) the point.
683         (if (> max (window-width))
684             (set-window-hscroll
685              (gnus-get-buffer-window (current-buffer) t)
686              (min (- (current-column) (/ (window-width) 3))
687                   (+ 2 (- max (window-width)))))
688           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
689         max))))
690
691 (defun gnus-read-event-char (&optional prompt)
692   "Get the next event."
693   (let ((event (read-event prompt)))
694     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
695     (cons (and (numberp event) event) event)))
696
697 (defun gnus-sortable-date (date)
698   "Make string suitable for sorting from DATE."
699   (gnus-time-iso8601 (date-to-time date)))
700
701 (defun gnus-copy-file (file &optional to)
702   "Copy FILE to TO."
703   (interactive
704    (list (read-file-name "Copy file: " default-directory)
705          (read-file-name "Copy file to: " default-directory)))
706   (unless to
707     (setq to (read-file-name "Copy file to: " default-directory)))
708   (when (file-directory-p to)
709     (setq to (concat (file-name-as-directory to)
710                      (file-name-nondirectory file))))
711   (copy-file file to))
712
713 (defvar gnus-work-buffer " *gnus work*")
714
715 (declare-function gnus-get-buffer-create "gnus" (name))
716 ;; gnus.el requires mm-util.
717 (declare-function mm-enable-multibyte "mm-util")
718
719 (defun gnus-set-work-buffer ()
720   "Put point in the empty Gnus work buffer."
721   (if (get-buffer gnus-work-buffer)
722       (progn
723         (set-buffer gnus-work-buffer)
724         (erase-buffer))
725     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
726     (kill-all-local-variables)
727     (mm-enable-multibyte)))
728
729 (defmacro gnus-group-real-name (group)
730   "Find the real name of a foreign newsgroup."
731   `(let ((gname ,group))
732      (if (string-match "^[^:]+:" gname)
733          (substring gname (match-end 0))
734        gname)))
735
736 (defmacro gnus-group-server (group)
737   "Find the server name of a foreign newsgroup.
738 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
739 yield \"nnimap:yxa\"."
740   `(let ((gname ,group))
741      (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
742          (format "%s:%s" (match-string 1 gname) (or
743                                                  (match-string 2 gname)
744                                                  ""))
745        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
746
747 (defun gnus-make-sort-function (funs)
748   "Return a composite sort condition based on the functions in FUNS."
749   (cond
750    ;; Just a simple function.
751    ((functionp funs) funs)
752    ;; No functions at all.
753    ((null funs) funs)
754    ;; A list of functions.
755    ((or (cdr funs)
756         (listp (car funs)))
757     (gnus-byte-compile
758      `(lambda (t1 t2)
759         ,(gnus-make-sort-function-1 (reverse funs)))))
760    ;; A list containing just one function.
761    (t
762     (car funs))))
763
764 (defun gnus-make-sort-function-1 (funs)
765   "Return a composite sort condition based on the functions in FUNS."
766   (let ((function (car funs))
767         (first 't1)
768         (last 't2))
769     (when (consp function)
770       (cond
771        ;; Reversed spec.
772        ((eq (car function) 'not)
773         (setq function (cadr function)
774               first 't2
775               last 't1))
776        ((functionp function)
777         ;; Do nothing.
778         )
779        (t
780         (error "Invalid sort spec: %s" function))))
781     (if (cdr funs)
782         `(or (,function ,first ,last)
783              (and (not (,function ,last ,first))
784                   ,(gnus-make-sort-function-1 (cdr funs))))
785       `(,function ,first ,last))))
786
787 (defun gnus-turn-off-edit-menu (type)
788   "Turn off edit menu in `gnus-TYPE-mode-map'."
789   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
790     [menu-bar edit] 'undefined))
791
792 (defmacro gnus-bind-print-variables (&rest forms)
793   "Bind print-* variables and evaluate FORMS.
794 This macro is used with `prin1', `pp', etc. in order to ensure printed
795 Lisp objects are loadable.  Bind `print-quoted' and `print-readably'
796 to t, and `print-escape-multibyte', `print-escape-newlines',
797 `print-escape-nonascii', `print-length', `print-level' and
798 `print-string-length' to nil."
799   `(let ((print-quoted t)
800          (print-readably t)
801          ;;print-circle
802          ;;print-continuous-numbering
803          print-escape-multibyte
804          print-escape-newlines
805          print-escape-nonascii
806          ;;print-gensym
807          print-length
808          print-level
809          print-string-length)
810      ,@forms))
811
812 (defun gnus-prin1 (form)
813   "Use `prin1' on FORM in the current buffer.
814 Bind `print-quoted' and `print-readably' to t, and `print-length' and
815 `print-level' to nil.  See also `gnus-bind-print-variables'."
816   (gnus-bind-print-variables (prin1 form (current-buffer))))
817
818 (defun gnus-prin1-to-string (form)
819   "The same as `prin1'.
820 Bind `print-quoted' and `print-readably' to t, and `print-length' and
821 `print-level' to nil.  See also `gnus-bind-print-variables'."
822   (gnus-bind-print-variables (prin1-to-string form)))
823
824 (defun gnus-pp (form &optional stream)
825   "Use `pp' on FORM in the current buffer.
826 Bind `print-quoted' and `print-readably' to t, and `print-length' and
827 `print-level' to nil.  See also `gnus-bind-print-variables'."
828   (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
829
830 (defun gnus-pp-to-string (form)
831   "The same as `pp-to-string'.
832 Bind `print-quoted' and `print-readably' to t, and `print-length' and
833 `print-level' to nil.  See also `gnus-bind-print-variables'."
834   (gnus-bind-print-variables (pp-to-string form)))
835
836 (defun gnus-make-directory (directory)
837   "Make DIRECTORY (and all its parents) if it doesn't exist."
838   (require 'nnmail)
839   (let ((file-name-coding-system nnmail-pathname-coding-system))
840     (when (and directory
841                (not (file-exists-p directory)))
842       (make-directory directory t)))
843   t)
844
845 (defun gnus-write-buffer (file)
846   "Write the current buffer's contents to FILE."
847   (let ((file-name-coding-system nnmail-pathname-coding-system))
848     ;; Make sure the directory exists.
849     (gnus-make-directory (file-name-directory file))
850     ;; Write the buffer.
851     (write-region (point-min) (point-max) file nil 'quietly)))
852
853 (defun gnus-delete-file (file)
854   "Delete FILE if it exists."
855   (when (file-exists-p file)
856     (delete-file file)))
857
858 (defun gnus-delete-directory (directory)
859   "Delete files in DIRECTORY.  Subdirectories remain.
860 If there's no subdirectory, delete DIRECTORY as well."
861   (when (file-directory-p directory)
862     (let ((files (directory-files
863                   directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
864           file dir)
865       (while files
866         (setq file (pop files))
867         (if (eq t (car (file-attributes file)))
868             ;; `file' is a subdirectory.
869             (setq dir t)
870           ;; `file' is a file or a symlink.
871           (delete-file file)))
872       (unless dir
873         (delete-directory directory)))))
874
875 ;; The following two functions are used in gnus-registry.
876 ;; They were contributed by Andreas Fuchs <asf@void.at>.
877 (defun gnus-alist-to-hashtable (alist)
878   "Build a hashtable from the values in ALIST."
879   (let ((ht (make-hash-table
880              :size 4096
881              :test 'equal)))
882     (mapc
883      (lambda (kv-pair)
884        (puthash (car kv-pair) (cdr kv-pair) ht))
885      alist)
886      ht))
887
888 (defun gnus-hashtable-to-alist (hash)
889   "Build an alist from the values in HASH."
890   (let ((list nil))
891     (maphash
892      (lambda (key value)
893        (setq list (cons (cons key value) list)))
894      hash)
895     list))
896
897 (defun gnus-strip-whitespace (string)
898   "Return STRING stripped of all whitespace."
899   (while (string-match "[\r\n\t ]+" string)
900     (setq string (replace-match "" t t string)))
901   string)
902
903 (declare-function gnus-put-text-property "gnus"
904                   (start end property value &optional object))
905
906 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
907   "The same as `put-text-property', but don't put this prop on any newlines in the region."
908   (save-match-data
909     (save-excursion
910       (save-restriction
911         (goto-char beg)
912         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
913           (gnus-put-text-property beg (match-beginning 0) prop val)
914           (setq beg (point)))
915         (gnus-put-text-property beg (point) prop val)))))
916
917 (declare-function gnus-overlay-put  "gnus" (overlay prop value))
918 (declare-function gnus-make-overlay "gnus"
919                   (beg end &optional buffer front-advance rear-advance))
920
921 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
922   "The same as `put-text-property', but don't put this prop on any newlines in the region."
923   (save-match-data
924     (save-excursion
925       (save-restriction
926         (goto-char beg)
927         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
928           (gnus-overlay-put
929            (gnus-make-overlay beg (match-beginning 0))
930            prop val)
931           (setq beg (point)))
932         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
933
934 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
935                                                                    prop val)
936   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
937   (let ((b beg))
938     (while (/= b end)
939       (when (get-text-property b 'gnus-face)
940         (setq b (next-single-property-change b 'gnus-face nil end)))
941       (when (/= b end)
942         (inline
943           (gnus-put-text-property
944            b (setq b (next-single-property-change b 'gnus-face nil end))
945            prop val))))))
946
947 (defmacro gnus-faces-at (position)
948   "Return a list of faces at POSITION."
949   (if (featurep 'xemacs)
950       `(let ((pos ,position))
951          (mapcar-extents 'extent-face
952                          nil (current-buffer) pos pos nil 'face))
953     `(let ((pos ,position))
954        (delq nil (cons (get-text-property pos 'face)
955                        (mapcar
956                         (lambda (overlay)
957                           (overlay-get overlay 'face))
958                         (overlays-at pos)))))))
959
960 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
961 ;; The primary idea here is to try to protect internal datastructures
962 ;; from becoming corrupted when the user hits C-g, or if a hook or
963 ;; similar blows up.  Often in Gnus multiple tables/lists need to be
964 ;; updated at the same time, or information can be lost.
965
966 (defvar gnus-atomic-be-safe t
967   "If t, certain operations will be protected from interruption by C-g.")
968
969 (defmacro gnus-atomic-progn (&rest forms)
970   "Evaluate FORMS atomically, which means to protect the evaluation
971 from being interrupted by the user.  An error from the forms themselves
972 will return without finishing the operation.  Since interrupts from
973 the user are disabled, it is recommended that only the most minimal
974 operations are performed by FORMS.  If you wish to assign many
975 complicated values atomically, compute the results into temporary
976 variables and then do only the assignment atomically."
977   `(let ((inhibit-quit gnus-atomic-be-safe))
978      ,@forms))
979
980 (put 'gnus-atomic-progn 'lisp-indent-function 0)
981
982 (defmacro gnus-atomic-progn-assign (protect &rest forms)
983   "Evaluate FORMS, but ensure that the variables listed in PROTECT
984 are not changed if anything in FORMS signals an error or otherwise
985 non-locally exits.  The variables listed in PROTECT are updated atomically.
986 It is safe to use gnus-atomic-progn-assign with long computations.
987
988 Note that if any of the symbols in PROTECT were unbound, they will be
989 set to nil on a successful assignment.  In case of an error or other
990 non-local exit, it will still be unbound."
991   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
992                                                   (concat (symbol-name x)
993                                                           "-tmp"))
994                                                  x))
995                                protect))
996          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
997                                temp-sym-map))
998          (temp-sym-let (mapcar (lambda (x) (list (car x)
999                                                  `(and (boundp ',(cadr x))
1000                                                        ,(cadr x))))
1001                                temp-sym-map))
1002          (sym-temp-let sym-temp-map)
1003          (temp-sym-assign (apply 'append temp-sym-map))
1004          (sym-temp-assign (apply 'append sym-temp-map))
1005          (result (make-symbol "result-tmp")))
1006     `(let (,@temp-sym-let
1007            ,result)
1008        (let ,sym-temp-let
1009          (setq ,result (progn ,@forms))
1010          (setq ,@temp-sym-assign))
1011        (let ((inhibit-quit gnus-atomic-be-safe))
1012          (setq ,@sym-temp-assign))
1013        ,result)))
1014
1015 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
1016 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
1017
1018 (defmacro gnus-atomic-setq (&rest pairs)
1019   "Similar to setq, except that the real symbols are only assigned when
1020 there are no errors.  And when the real symbols are assigned, they are
1021 done so atomically.  If other variables might be changed via side-effect,
1022 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
1023 with potentially long computations."
1024   (let ((tpairs pairs)
1025         syms)
1026     (while tpairs
1027       (push (car tpairs) syms)
1028       (setq tpairs (cddr tpairs)))
1029     `(gnus-atomic-progn-assign ,syms
1030        (setq ,@pairs))))
1031
1032 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
1033
1034
1035 ;;; Functions for saving to babyl/mail files.
1036
1037 (eval-when-compile
1038   (condition-case nil
1039       (progn
1040         (require 'rmail)
1041         (autoload 'rmail-update-summary "rmailsum"))
1042     (error
1043      (define-compiler-macro rmail-select-summary (&rest body)
1044        ;; Rmail of the XEmacs version is supplied by the package, and
1045        ;; requires tm and apel packages.  However, there may be those
1046        ;; who haven't installed those packages.  This macro helps such
1047        ;; people even if they install those packages later.
1048        `(eval '(rmail-select-summary ,@body)))
1049      ;; If there's rmail but there's no tm (or there's apel of the
1050      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
1051      ;; version fails halfway, however it provides the rmail-select-summary
1052      ;; macro which uses the following functions:
1053      (autoload 'rmail-summary-displayed "rmail")
1054      (autoload 'rmail-maybe-display-summary "rmail"))))
1055
1056 (defvar rmail-default-rmail-file)
1057 (defvar mm-text-coding-system)
1058
1059 (declare-function mm-append-to-file "mm-util"
1060                   (start end filename &optional codesys inhibit))
1061
1062 (defun gnus-output-to-rmail (filename &optional ask)
1063   "Append the current article to an Rmail file named FILENAME."
1064   (require 'rmail)
1065   (require 'mm-util)
1066   ;; Most of these codes are borrowed from rmailout.el.
1067   (setq filename (expand-file-name filename))
1068   (setq rmail-default-rmail-file filename)
1069   (let ((artbuf (current-buffer))
1070         (tmpbuf (get-buffer-create " *Gnus-output*")))
1071     (save-excursion
1072       (or (get-file-buffer filename)
1073           (file-exists-p filename)
1074           (if (or (not ask)
1075                   (gnus-yes-or-no-p
1076                    (concat "\"" filename "\" does not exist, create it? ")))
1077               (let ((file-buffer (create-file-buffer filename)))
1078                 (save-excursion
1079                   (set-buffer file-buffer)
1080                   (rmail-insert-rmail-file-header)
1081                   (let ((require-final-newline nil)
1082                         (coding-system-for-write mm-text-coding-system))
1083                     (gnus-write-buffer filename)))
1084                 (kill-buffer file-buffer))
1085             (error "Output file does not exist")))
1086       (set-buffer tmpbuf)
1087       (erase-buffer)
1088       (insert-buffer-substring artbuf)
1089       (gnus-convert-article-to-rmail)
1090       ;; Decide whether to append to a file or to an Emacs buffer.
1091       (let ((outbuf (get-file-buffer filename)))
1092         (if (not outbuf)
1093             (let ((file-name-coding-system nnmail-pathname-coding-system))
1094               (mm-append-to-file (point-min) (point-max) filename))
1095           ;; File has been visited, in buffer OUTBUF.
1096           (set-buffer outbuf)
1097           (let ((buffer-read-only nil)
1098                 (msg (and (boundp 'rmail-current-message)
1099                           (symbol-value 'rmail-current-message))))
1100             ;; If MSG is non-nil, buffer is in RMAIL mode.
1101             (when msg
1102               (widen)
1103               (narrow-to-region (point-max) (point-max)))
1104             (insert-buffer-substring tmpbuf)
1105             (when msg
1106               (goto-char (point-min))
1107               (widen)
1108               (search-backward "\n\^_")
1109               (narrow-to-region (point) (point-max))
1110               (rmail-count-new-messages t)
1111               (when (rmail-summary-exists)
1112                 (rmail-select-summary
1113                  (rmail-update-summary)))
1114               (rmail-count-new-messages t)
1115               (rmail-show-message msg))
1116             (save-buffer)))))
1117     (kill-buffer tmpbuf)))
1118
1119 (defun gnus-output-to-mail (filename &optional ask)
1120   "Append the current article to a mail file named FILENAME."
1121   (setq filename (expand-file-name filename))
1122   (let ((artbuf (current-buffer))
1123         (tmpbuf (get-buffer-create " *Gnus-output*")))
1124     (save-excursion
1125       ;; Create the file, if it doesn't exist.
1126       (when (and (not (get-file-buffer filename))
1127                  (not (file-exists-p filename)))
1128         (if (or (not ask)
1129                 (gnus-y-or-n-p
1130                  (concat "\"" filename "\" does not exist, create it? ")))
1131             (let ((file-buffer (create-file-buffer filename)))
1132               (save-excursion
1133                 (set-buffer file-buffer)
1134                 (let ((require-final-newline nil)
1135                       (coding-system-for-write mm-text-coding-system))
1136                   (gnus-write-buffer filename)))
1137               (kill-buffer file-buffer))
1138           (error "Output file does not exist")))
1139       (set-buffer tmpbuf)
1140       (erase-buffer)
1141       (insert-buffer-substring artbuf)
1142       (goto-char (point-min))
1143       (if (looking-at "From ")
1144           (forward-line 1)
1145         (insert "From nobody " (current-time-string) "\n"))
1146       (let (case-fold-search)
1147         (while (re-search-forward "^From " nil t)
1148           (beginning-of-line)
1149           (insert ">")))
1150       ;; Decide whether to append to a file or to an Emacs buffer.
1151       (let ((outbuf (get-file-buffer filename)))
1152         (if (not outbuf)
1153             (let ((buffer-read-only nil))
1154               (save-excursion
1155                 (goto-char (point-max))
1156                 (forward-char -2)
1157                 (unless (looking-at "\n\n")
1158                   (goto-char (point-max))
1159                   (unless (bolp)
1160                     (insert "\n"))
1161                   (insert "\n"))
1162                 (goto-char (point-max))
1163                 (let ((file-name-coding-system nnmail-pathname-coding-system))
1164                   (mm-append-to-file (point-min) (point-max) filename))))
1165           ;; File has been visited, in buffer OUTBUF.
1166           (set-buffer outbuf)
1167           (let ((buffer-read-only nil))
1168             (goto-char (point-max))
1169             (unless (eobp)
1170               (insert "\n"))
1171             (insert "\n")
1172             (insert-buffer-substring tmpbuf)))))
1173     (kill-buffer tmpbuf)))
1174
1175 (defun gnus-convert-article-to-rmail ()
1176   "Convert article in current buffer to Rmail message format."
1177   (let ((buffer-read-only nil))
1178     ;; Convert article directly into Babyl format.
1179     (goto-char (point-min))
1180     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1181     (while (search-forward "\n\^_" nil t) ;single char
1182      &nb