Fix comment typo.
[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, 2009, 2010 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
42 (eval-when-compile
43   (unless (fboundp 'with-no-warnings)
44     (defmacro with-no-warnings (&rest body)
45       `(progn ,@body))))
46
47 (defcustom gnus-completing-read-function 'gnus-emacs-completing-read
48   "Function use to do completing read."
49   :version "24.1"
50   :group 'gnus-meta
51   :type `(radio (function-item
52                  :doc "Use Emacs standard `completing-read' function."
53                  gnus-emacs-completing-read)
54                 ;; iswitchb.el is very old and ido.el is unavailable
55                 ;; in XEmacs, so we exclude those function items.
56                 ,@(unless (featurep 'xemacs)
57                     '((function-item
58                        :doc "Use `ido-completing-read' function."
59                        gnus-ido-completing-read)
60                       (function-item
61                        :doc "Use iswitchb based completing-read function."
62                        gnus-iswitchb-completing-read)))))
63
64 (defcustom gnus-completion-styles
65   (if (and (boundp 'completion-styles-alist)
66            (boundp 'completion-styles))
67       (append (when (and (assq 'substring completion-styles-alist)
68                          (not (memq 'substring completion-styles)))
69                 (list 'substring))
70               completion-styles)
71     nil)
72   "Value of `completion-styles' to use when completing."
73   :version "24.1"
74   :group 'gnus-meta
75   :type 'list)
76
77 ;; Fixme: this should be a gnus variable, not nnmail-.
78 (defvar nnmail-pathname-coding-system)
79 (defvar nnmail-active-file-coding-system)
80
81 ;; Inappropriate references to other parts of Gnus.
82 (defvar gnus-emphasize-whitespace-regexp)
83 (defvar gnus-original-article-buffer)
84 (defvar gnus-user-agent)
85
86 (autoload 'gnus-get-buffer-window "gnus-win")
87 (autoload 'nnheader-narrow-to-headers "nnheader")
88 (autoload 'nnheader-replace-chars-in-string "nnheader")
89 (autoload 'mail-header-remove-comments "mail-parse")
90
91 (eval-and-compile
92   (cond
93    ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
94    ;; SXEmacs 22.1.4) over `replace-in-string'.  The latter leads to inf-loops
95    ;; on empty matches:
96    ;;   (replace-in-string "foo" "/*$" "/")
97    ;;   (replace-in-string "xe" "\\(x\\)?" "")
98    ((fboundp 'replace-regexp-in-string)
99     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
100       "Replace all matches for REGEXP with NEWTEXT in STRING.
101 If LITERAL is non-nil, insert NEWTEXT literally.  Return a new
102 string containing the replacements.
103
104 This is a compatibility function for different Emacsen."
105       (replace-regexp-in-string regexp newtext string nil literal)))
106    ((fboundp 'replace-in-string)
107     (defalias 'gnus-replace-in-string 'replace-in-string))))
108
109 (defun gnus-boundp (variable)
110   "Return non-nil if VARIABLE is bound and non-nil."
111   (and (boundp variable)
112        (symbol-value variable)))
113
114 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
115   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
116   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
117         (w (make-symbol "w"))
118         (buf (make-symbol "buf")))
119     `(let* ((,tempvar (selected-window))
120             (,buf ,buffer)
121             (,w (gnus-get-buffer-window ,buf 'visible)))
122        (unwind-protect
123            (progn
124              (if ,w
125                  (progn
126                    (select-window ,w)
127                    (set-buffer (window-buffer ,w)))
128                (pop-to-buffer ,buf))
129              ,@forms)
130          (select-window ,tempvar)))))
131
132 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
133 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
134
135 (defmacro gnus-intern-safe (string hashtable)
136   "Get hash value.  Arguments are STRING and HASHTABLE."
137   `(let ((symbol (intern ,string ,hashtable)))
138      (or (boundp symbol)
139          (set symbol nil))
140      symbol))
141
142 (defsubst gnus-goto-char (point)
143   (and point (goto-char point)))
144
145 (defmacro gnus-buffer-exists-p (buffer)
146   `(let ((buffer ,buffer))
147      (when buffer
148        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
149                 buffer))))
150
151 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
152 ;; XEmacs.  In Emacs we don't need to call `make-local-hook' first.
153 ;; It's harmless, though, so the main purpose of this alias is to shut
154 ;; up the byte compiler.
155 (defalias 'gnus-make-local-hook (if (featurep 'xemacs)
156                                     'make-local-hook
157                                   'ignore))
158
159 (defun gnus-delete-first (elt list)
160   "Delete by side effect the first occurrence of ELT as a member of LIST."
161   (if (equal (car list) elt)
162       (cdr list)
163     (let ((total list))
164       (while (and (cdr list)
165                   (not (equal (cadr list) elt)))
166         (setq list (cdr list)))
167       (when (cdr list)
168         (setcdr list (cddr list)))
169       total)))
170
171 ;; Delete the current line (and the next N lines).
172 (defmacro gnus-delete-line (&optional n)
173   `(delete-region (point-at-bol)
174                   (progn (forward-line ,(or n 1)) (point))))
175
176 (defun gnus-byte-code (func)
177   "Return a form that can be `eval'ed based on FUNC."
178   (let ((fval (indirect-function func)))
179     (if (byte-code-function-p fval)
180         (let ((flist (append fval nil)))
181           (setcar flist 'byte-code)
182           flist)
183       (cons 'progn (cddr fval)))))
184
185 (defun gnus-extract-address-components (from)
186   "Extract address components from a From header.
187 Given an RFC-822 address FROM, extract full name and canonical address.
188 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).  Much more simple
189 solution than `mail-extract-address-components', which works much better, but
190 is slower."
191   (let (name address)
192     ;; First find the address - the thing with the @ in it.  This may
193     ;; not be accurate in mail addresses, but does the trick most of
194     ;; the time in news messages.
195     (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
196            ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
197            ;; correctly.
198            (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
199            (setq address (substring from (match-beginning 1) (match-end 1))))
200           ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
201            (setq address (substring from (match-beginning 0) (match-end 0)))))
202     ;; Then we check whether the "name <address>" format is used.
203     (and address
204          ;; Linear white space is not required.
205          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
206          (and (setq name (substring from 0 (match-beginning 0)))
207               ;; Strip any quotes from the name.
208               (string-match "^\".*\"$" name)
209               (setq name (substring name 1 (1- (match-end 0))))))
210     ;; If not, then "address (name)" is used.
211     (or name
212         (and (string-match "(.+)" from)
213              (setq name (substring from (1+ (match-beginning 0))
214                                    (1- (match-end 0)))))
215         (and (string-match "()" from)
216              (setq name address))
217         ;; XOVER might not support folded From headers.
218         (and (string-match "(.*" from)
219              (setq name (substring from (1+ (match-beginning 0))
220                                    (match-end 0)))))
221     (list (if (string= name "") nil name) (or address from))))
222
223 (defun gnus-extract-address-component-name (from)
224   "Extract name from a From header.
225 Uses `gnus-extract-address-components'."
226   (nth 0 (gnus-extract-address-components from)))
227
228 (defun gnus-extract-address-component-email (from)
229   "Extract e-mail address from a From header.
230 Uses `gnus-extract-address-components'."
231   (nth 1 (gnus-extract-address-components from)))
232
233 (declare-function message-fetch-field "message" (header &optional not-all))
234
235 (defun gnus-fetch-field (field)
236   "Return the value of the header FIELD of current article."
237   (require 'message)
238   (save-excursion
239     (save-restriction
240       (let ((inhibit-point-motion-hooks t))
241         (nnheader-narrow-to-headers)
242         (message-fetch-field field)))))
243
244 (defun gnus-fetch-original-field (field)
245   "Fetch FIELD from the original version of the current article."
246   (with-current-buffer gnus-original-article-buffer
247     (gnus-fetch-field field)))
248
249
250 (defun gnus-goto-colon ()
251   (beginning-of-line)
252   (let ((eol (point-at-eol)))
253     (goto-char (or (text-property-any (point) eol 'gnus-position t)
254                    (search-forward ":" eol t)
255                    (point)))))
256
257 (declare-function gnus-find-method-for-group "gnus" (group &optional info))
258 (declare-function gnus-group-name-decode "gnus-group" (string charset))
259 (declare-function gnus-group-name-charset "gnus-group" (method group))
260 ;; gnus-group requires gnus-int which requires message.
261 (declare-function message-tokenize-header "message"
262                   (header &optional separator))
263
264 (defun gnus-decode-newsgroups (newsgroups group &optional method)
265   (require 'gnus-group)
266   (let ((method (or method (gnus-find-method-for-group group))))
267     (mapconcat (lambda (group)
268                  (gnus-group-name-decode group (gnus-group-name-charset
269                                                 method group)))
270                (message-tokenize-header newsgroups)
271                ",")))
272
273 (defun gnus-remove-text-with-property (prop)
274   "Delete all text in the current buffer with text property PROP."
275   (let ((start (point-min))
276         end)
277     (unless (get-text-property start prop)
278       (setq start (next-single-property-change start prop)))
279     (while start
280       (setq end (text-property-any start (point-max) prop nil))
281       (delete-region start (or end (point-max)))
282       (setq start (when end
283                     (next-single-property-change start prop))))))
284
285 (defun gnus-newsgroup-directory-form (newsgroup)
286   "Make hierarchical directory name from NEWSGROUP name."
287   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
288          (idx (string-match ":" newsgroup)))
289     (concat
290      (if idx (substring newsgroup 0 idx))
291      (if idx "/")
292      (nnheader-replace-chars-in-string
293       (if idx (substring newsgroup (1+ idx)) newsgroup)
294       ?. ?/))))
295
296 (defun gnus-newsgroup-savable-name (group)
297   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
298   ;; with dots.
299   (nnheader-replace-chars-in-string group ?/ ?.))
300
301 (defun gnus-string> (s1 s2)
302   (not (or (string< s1 s2)
303            (string= s1 s2))))
304
305 (defun gnus-string< (s1 s2)
306   "Return t if first arg string is less than second in lexicographic order.
307 Case is significant if and only if `case-fold-search' is nil.
308 Symbols are also allowed; their print names are used instead."
309   (if case-fold-search
310       (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
311                     (downcase (if (symbolp s2) (symbol-name s2) s2)))
312     (string-lessp s1 s2)))
313
314 ;;; Time functions.
315
316 (defun gnus-file-newer-than (file date)
317   (let ((fdate (nth 5 (file-attributes file))))
318     (or (> (car fdate) (car date))
319         (and (= (car fdate) (car date))
320              (> (nth 1 fdate) (nth 1 date))))))
321
322 (eval-and-compile
323   (if (and (fboundp 'float-time)
324            (subrp (symbol-function 'float-time)))
325       (defalias 'gnus-float-time 'float-time)
326     (defun gnus-float-time (&optional time)
327       "Convert time value TIME to a floating point number.
328 TIME defaults to the current time."
329       (with-no-warnings (time-to-seconds (or time (current-time)))))))
330
331 ;;; Keymap macros.
332
333 (defmacro gnus-local-set-keys (&rest plist)
334   "Set the keys in PLIST in the current keymap."
335   `(gnus-define-keys-1 (current-local-map) ',plist))
336
337 (defmacro gnus-define-keys (keymap &rest plist)
338   "Define all keys in PLIST in KEYMAP."
339   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
340
341 (defmacro gnus-define-keys-safe (keymap &rest plist)
342   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
343   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
344
345 (put 'gnus-define-keys 'lisp-indent-function 1)
346 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
347 (put 'gnus-local-set-keys 'lisp-indent-function 1)
348
349 (defmacro gnus-define-keymap (keymap &rest plist)
350   "Define all keys in PLIST in KEYMAP."
351   `(gnus-define-keys-1 ,keymap (quote ,plist)))
352
353 (put 'gnus-define-keymap 'lisp-indent-function 1)
354
355 (defun gnus-define-keys-1 (keymap plist &optional safe)
356   (when (null keymap)
357     (error "Can't set keys in a null keymap"))
358   (cond ((symbolp keymap)
359          (setq keymap (symbol-value keymap)))
360         ((keymapp keymap))
361         ((listp keymap)
362          (set (car keymap) nil)
363          (define-prefix-command (car keymap))
364          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
365          (setq keymap (symbol-value (car keymap)))))
366   (let (key)
367     (while plist
368       (when (symbolp (setq key (pop plist)))
369         (setq key (symbol-value key)))
370       (if (or (not safe)
371               (eq (lookup-key keymap key) 'undefined))
372           (define-key keymap key (pop plist))
373         (pop plist)))))
374
375 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
376 ;; the echo area.
377 ;;
378 ;; Do we really need these functions?  Workarounds for bugs in the corresponding
379 ;; Emacs functions?  Maybe these bugs are no longer present in any supported
380 ;; (X)Emacs version?  Alias them to the original functions and see if anyone
381 ;; reports a problem.  If not, replace with original functions.  --rsteib,
382 ;; 2007-12-14
383 ;;
384 ;; All supported Emacsen clear the echo area after `yes-or-no-p', so we can
385 ;; remove `yes-or-no-p'.  RMS says that not clearing after `y-or-n-p' is
386 ;; intentional (see below), so we could remove `gnus-y-or-n-p' too.
387 ;; Objections?  --rsteib, 2008-02-16
388 ;;
389 ;; ,----[ http://thread.gmane.org/gmane.emacs.gnus.general/65099/focus=66070 ]
390 ;; | From: Richard Stallman
391 ;; | Subject: Re: Do we need gnus-yes-or-no-p and gnus-y-or-n-p?
392 ;; | To: Katsumi Yamaoka [...]
393 ;; | Cc: emacs-devel@[...], xemacs-beta@[...], ding@[...]
394 ;; | Date: Mon, 07 Jan 2008 12:16:05 -0500
395 ;; | Message-ID: <E1JBva1-000528-VY@fencepost.gnu.org>
396 ;; |
397 ;; |     The behavior of `y-or-n-p' that it doesn't clear the question
398 ;; |     and the answer is not serious of course, but I feel it is not
399 ;; |     cool.
400 ;; |
401 ;; | It is intentional.
402 ;; |
403 ;; |     Currently, it is commented out in the trunk by Reiner Steib.  He
404 ;; |     also wrote the benefit of leaving the question and the answer in
405 ;; |     the echo area as follows:
406 ;; |
407 ;; |     (http://article.gmane.org/gmane.emacs.gnus.general/66061)
408 ;; |     > In contrast to yes-or-no-p it is much easier to type y, n,
409 ;; |     > SPC, DEL, etc accidentally, so it might be useful for the user
410 ;; |     > to see what he has typed.
411 ;; |
412 ;; | Yes, that is the reason.
413 ;; `----
414
415 ;; (defun gnus-y-or-n-p (prompt)
416 ;;   (prog1
417 ;;       (y-or-n-p prompt)
418 ;;     (message "")))
419 ;; (defun gnus-yes-or-no-p (prompt)
420 ;;   (prog1
421 ;;       (yes-or-no-p prompt)
422 ;;     (message "")))
423
424 (defalias 'gnus-y-or-n-p 'y-or-n-p)
425 (defalias 'gnus-yes-or-no-p 'yes-or-no-p)
426
427 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
428 ;; age-depending date representations. (e.g. just the time if it's
429 ;; from today, the day of the week if it's within the last 7 days and
430 ;; the full date if it's older)
431
432 (defun gnus-seconds-today ()
433   "Return the number of seconds passed today."
434   (let ((now (decode-time (current-time))))
435     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
436
437 (defun gnus-seconds-month ()
438   "Return the number of seconds passed this month."
439   (let ((now (decode-time (current-time))))
440     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
441        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
442
443 (defun gnus-seconds-year ()
444   "Return the number of seconds passed this year."
445   (let ((now (decode-time (current-time)))
446         (days (format-time-string "%j" (current-time))))
447     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
448        (* (- (string-to-number days) 1) 3600 24))))
449
450 (defmacro gnus-date-get-time (date)
451   "Convert DATE string to Emacs time.
452 Cache the result as a text property stored in DATE."
453   ;; Either return the cached value...
454   `(let ((d ,date))
455      (if (equal "" d)
456          '(0 0)
457        (or (get-text-property 0 'gnus-time d)
458            ;; or compute the value...
459            (let ((time (safe-date-to-time d)))
460              ;; and store it back in the string.
461              (put-text-property 0 1 'gnus-time time d)
462              time)))))
463
464 (defvar gnus-user-date-format-alist
465   '(((gnus-seconds-today) . "%k:%M")
466     (604800 . "%a %k:%M")                   ;;that's one week
467     ((gnus-seconds-month) . "%a %d")
468     ((gnus-seconds-year) . "%b %d")
469     (t . "%b %d '%y"))                      ;;this one is used when no
470                                             ;;other does match
471   "Specifies date format depending on age of article.
472 This is an alist of items (AGE . FORMAT).  AGE can be a number (of
473 seconds) or a Lisp expression evaluating to a number.  When the age of
474 the article is less than this number, then use `format-time-string'
475 with the corresponding FORMAT for displaying the date of the article.
476 If AGE is not a number or a Lisp expression evaluating to a
477 non-number, then the corresponding FORMAT is used as a default value.
478
479 Note that the list is processed from the beginning, so it should be
480 sorted by ascending AGE.  Also note that items following the first
481 non-number AGE will be ignored.
482
483 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
484 and `gnus-seconds-year' in the AGE spec.  They return the number of
485 seconds passed since the start of today, of this month, of this year,
486 respectively.")
487
488 (defun gnus-user-date (messy-date)
489   "Format the messy-date according to gnus-user-date-format-alist.
490 Returns \"  ?  \" if there's bad input or if another error occurs.
491 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
492   (condition-case ()
493       (let* ((messy-date (gnus-float-time (gnus-date-get-time messy-date)))
494              (now (gnus-float-time))
495              ;;If we don't find something suitable we'll use this one
496              (my-format "%b %d '%y"))
497         (let* ((difference (- now messy-date))
498                (templist gnus-user-date-format-alist)
499                (top (eval (caar templist))))
500           (while (if (numberp top) (< top difference) (not top))
501             (progn
502               (setq templist (cdr templist))
503               (setq top (eval (caar templist)))))
504           (if (stringp (cdr (car templist)))
505               (setq my-format (cdr (car templist)))))
506         (format-time-string (eval my-format) (seconds-to-time messy-date)))
507     (error "  ?   ")))
508
509 (defun gnus-dd-mmm (messy-date)
510   "Return a string like DD-MMM from a big messy string."
511   (condition-case ()
512       (format-time-string "%d-%b" (gnus-date-get-time messy-date))
513     (error "  -   ")))
514
515 (defsubst gnus-time-iso8601 (time)
516   "Return a string of TIME in YYYYMMDDTHHMMSS format."
517   (format-time-string "%Y%m%dT%H%M%S" time))
518
519 (defun gnus-date-iso8601 (date)
520   "Convert the DATE to YYYYMMDDTHHMMSS."
521   (condition-case ()
522       (gnus-time-iso8601 (gnus-date-get-time date))
523     (error "")))
524
525 (defun gnus-mode-string-quote (string)
526   "Quote all \"%\"'s in STRING."
527   (gnus-replace-in-string string "%" "%%"))
528
529 ;; Make a hash table (default and minimum size is 256).
530 ;; Optional argument HASHSIZE specifies the table size.
531 (defun gnus-make-hashtable (&optional hashsize)
532   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
533
534 ;; Make a number that is suitable for hashing; bigger than MIN and
535 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
536 ;; hardware modulo operation, so they implement it in software.  On
537 ;; many sparcs over 50% of the time to intern is spent in the modulo.
538 ;; Yes, it's slower than actually computing the hash from the string!
539 ;; So we use powers of 2 so people can optimize the modulo to a mask.
540 (defun gnus-create-hash-size (min)
541   (let ((i 1))
542     (while (< i min)
543       (setq i (* 2 i)))
544     i))
545
546 (defcustom gnus-verbose 7
547   "*Integer that says how verbose Gnus should be.
548 The higher the number, the more messages Gnus will flash to say what
549 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
550 display most important messages; and at ten, Gnus will keep on
551 jabbering all the time."
552   :group 'gnus-start
553   :type 'integer)
554
555 (defcustom gnus-add-timestamp-to-message nil
556   "Non-nil means add timestamps to messages that Gnus issues.
557 If it is `log', add timestamps to only the messages that go into the
558 \"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
559 If it is neither nil nor `log', add timestamps not only to log messages
560 but also to the ones displayed in the echo area."
561   :version "23.1" ;; No Gnus
562   :group  'gnus-various
563   :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
564                  (const :tag "Logged messages only" log)
565                  (sexp :tag "All messages"
566                        :match (lambda (widget value) value)
567                        :value t)
568                  (const :tag "No timestamp" nil)))
569
570 (eval-when-compile
571   (defmacro gnus-message-with-timestamp-1 (format-string args)
572     (let ((timestamp '((format-time-string "%Y%m%dT%H%M%S" time)
573                        "." (format "%03d" (/ (nth 2 time) 1000)) "> ")))
574       (if (featurep 'xemacs)
575           `(let (str time)
576              (if (or (and (null ,format-string) (null ,args))
577                      (progn
578                        (setq str (apply 'format ,format-string ,args))
579                        (zerop (length str))))
580                  (prog1
581                      (and ,format-string str)
582                    (clear-message nil))
583                (cond ((eq gnus-add-timestamp-to-message 'log)
584                       (setq time (current-time))
585                       (display-message 'no-log str)
586                       (log-message 'message (concat ,@timestamp str)))
587                      (gnus-add-timestamp-to-message
588                       (setq time (current-time))
589                       (display-message 'message (concat ,@timestamp str)))
590                      (t
591                       (display-message 'message str))))
592              str)
593         `(let (str time)
594            (cond ((eq gnus-add-timestamp-to-message 'log)
595                   (setq str (let (message-log-max)
596                               (apply 'message ,format-string ,args)))
597                   (when (and message-log-max
598                              (> message-log-max 0)
599                              (/= (length str) 0))
600                     (setq time (current-time))
601                     (with-current-buffer (get-buffer-create "*Messages*")
602                       (goto-char (point-max))
603                       (insert ,@timestamp str "\n")
604                       (forward-line (- message-log-max))
605                       (delete-region (point-min) (point))
606                       (goto-char (point-max))))
607                   str)
608                  (gnus-add-timestamp-to-message
609                   (if (or (and (null ,format-string) (null ,args))
610                           (progn
611                             (setq str (apply 'format ,format-string ,args))
612                             (zerop (length str))))
613                       (prog1
614                           (and ,format-string str)
615                         (message nil))
616                     (setq time (current-time))
617                     (message "%s" (concat ,@timestamp str))
618                     str))
619                  (t
620                   (apply 'message ,format-string ,args))))))))
621
622 (defvar gnus-action-message-log nil)
623
624 (defun gnus-message-with-timestamp (format-string &rest args)
625   "Display message with timestamp.  Arguments are the same as `message'.
626 The `gnus-add-timestamp-to-message' variable controls how to add
627 timestamp to message."
628   (gnus-message-with-timestamp-1 format-string args))
629
630 (defun gnus-message (level &rest args)
631   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
632
633 Guideline for numbers:
634 1 - error messages, 3 - non-serious error messages, 5 - messages for things
635 that take a long time, 7 - not very important messages on stuff, 9 - messages
636 inside loops."
637   (if (<= level gnus-verbose)
638       (let ((message
639              (if gnus-add-timestamp-to-message
640                  (apply 'gnus-message-with-timestamp args)
641                (apply 'message args))))
642         (when (and (consp gnus-action-message-log)
643                    (<= level 3))
644           (push message gnus-action-message-log))
645         message)
646     ;; We have to do this format thingy here even if the result isn't
647     ;; shown - the return value has to be the same as the return value
648     ;; from `message'.
649     (apply 'format args)))
650
651 (defun gnus-final-warning ()
652   (when (and (consp gnus-action-message-log)
653              (setq gnus-action-message-log
654                    (delete nil gnus-action-message-log)))
655     (message "Warning: %s"
656              (mapconcat #'identity gnus-action-message-log "; "))))
657
658 (defun gnus-error (level &rest args)
659   "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
660 ARGS are passed to `message'."
661   (when (<= (floor level) gnus-verbose)
662     (apply 'message args)
663     (ding)
664     (let (duration)
665       (when (and (floatp level)
666                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
667         (sit-for duration))))
668   nil)
669
670 (defun gnus-split-references (references)
671   "Return a list of Message-IDs in REFERENCES."
672   (let ((beg 0)
673         (references (mail-header-remove-comments (or references "")))
674         ids)
675     (while (string-match "<[^<]+[^< \t]" references beg)
676       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
677             ids))
678     (nreverse ids)))
679
680 (defun gnus-extract-references (references)
681   "Return a list of Message-IDs in REFERENCES (in In-Reply-To
682   format), trimmed to only contain the Message-IDs."
683   (let ((ids (gnus-split-references references))
684         refs)
685     (dolist (id ids)
686       (when (string-match "<[^<>]+>" id)
687         (push (match-string 0 id) refs)))
688     refs))
689
690 (defsubst gnus-parent-id (references &optional n)
691   "Return the last Message-ID in REFERENCES.
692 If N, return the Nth ancestor instead."
693   (when (and references
694              (not (zerop (length references))))
695     (if n
696         (let ((ids (inline (gnus-split-references references))))
697           (while (nthcdr n ids)
698             (setq ids (cdr ids)))
699           (car ids))
700       (let ((references (mail-header-remove-comments references)))
701         (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
702           (match-string 1 references))))))
703
704 (defun gnus-buffer-live-p (buffer)
705   "Say whether BUFFER is alive or not."
706   (and buffer
707        (get-buffer buffer)
708        (buffer-name (get-buffer buffer))))
709
710 (defun gnus-horizontal-recenter ()
711   "Recenter the current buffer horizontally."
712   (if (< (current-column) (/ (window-width) 2))
713       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
714     (let* ((orig (point))
715            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
716            (max 0))
717       (when end
718         ;; Find the longest line currently displayed in the window.
719         (goto-char (window-start))
720         (while (and (not (eobp))
721                     (< (point) end))
722           (end-of-line)
723           (setq max (max max (current-column)))
724           (forward-line 1))
725         (goto-char orig)
726         ;; Scroll horizontally to center (sort of) the point.
727         (if (> max (window-width))
728             (set-window-hscroll
729              (gnus-get-buffer-window (current-buffer) t)
730              (min (- (current-column) (/ (window-width) 3))
731                   (+ 2 (- max (window-width)))))
732           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
733         max))))
734
735 (defun gnus-read-event-char (&optional prompt)
736   "Get the next event."
737   (let ((event (read-event prompt)))
738     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
739     (cons (and (numberp event) event) event)))
740
741 (defun gnus-sortable-date (date)
742   "Make string suitable for sorting from DATE."
743   (gnus-time-iso8601 (date-to-time date)))
744
745 (defun gnus-copy-file (file &optional to)
746   "Copy FILE to TO."
747   (interactive
748    (list (read-file-name "Copy file: " default-directory)
749          (read-file-name "Copy file to: " default-directory)))
750   (unless to
751     (setq to (read-file-name "Copy file to: " default-directory)))
752   (when (file-directory-p to)
753     (setq to (concat (file-name-as-directory to)
754                      (file-name-nondirectory file))))
755   (copy-file file to))
756
757 (defvar gnus-work-buffer " *gnus work*")
758
759 (declare-function gnus-get-buffer-create "gnus" (name))
760 ;; gnus.el requires mm-util.
761 (declare-function mm-enable-multibyte "mm-util")
762
763 (defun gnus-set-work-buffer ()
764   "Put point in the empty Gnus work buffer."
765   (if (get-buffer gnus-work-buffer)
766       (progn
767         (set-buffer gnus-work-buffer)
768         (erase-buffer))
769     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
770     (kill-all-local-variables)
771     (mm-enable-multibyte)))
772
773 (defmacro gnus-group-real-name (group)
774   "Find the real name of a foreign newsgroup."
775   `(let ((gname ,group))
776      (if (string-match "^[^:]+:" gname)
777          (substring gname (match-end 0))
778        gname)))
779
780 (defmacro gnus-group-server (group)
781   "Find the server name of a foreign newsgroup.
782 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
783 yield \"nnimap:yxa\"."
784   `(let ((gname ,group))
785      (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
786          (format "%s:%s" (match-string 1 gname) (or
787                                                  (match-string 2 gname)
788                                                  ""))
789        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
790
791 (defun gnus-make-sort-function (funs)
792   "Return a composite sort condition based on the functions in FUNS."
793   (cond
794    ;; Just a simple function.
795    ((functionp funs) funs)
796    ;; No functions at all.
797    ((null funs) funs)
798    ;; A list of functions.
799    ((or (cdr funs)
800         (listp (car funs)))
801     (gnus-byte-compile
802      `(lambda (t1 t2)
803         ,(gnus-make-sort-function-1 (reverse funs)))))
804    ;; A list containing just one function.
805    (t
806     (car funs))))
807
808 (defun gnus-make-sort-function-1 (funs)
809   "Return a composite sort condition based on the functions in FUNS."
810   (let ((function (car funs))
811         (first 't1)
812         (last 't2))
813     (when (consp function)
814       (cond
815        ;; Reversed spec.
816        ((eq (car function) 'not)
817         (setq function (cadr function)
818               first 't2
819               last 't1))
820        ((functionp function)
821         ;; Do nothing.
822         )
823        (t
824         (error "Invalid sort spec: %s" function))))
825     (if (cdr funs)
826         `(or (,function ,first ,last)
827              (and (not (,function ,last ,first))
828                   ,(gnus-make-sort-function-1 (cdr funs))))
829       `(,function ,first ,last))))
830
831 (defun gnus-turn-off-edit-menu (type)
832   "Turn off edit menu in `gnus-TYPE-mode-map'."
833   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
834     [menu-bar edit] 'undefined))
835
836 (defmacro gnus-bind-print-variables (&rest forms)
837   "Bind print-* variables and evaluate FORMS.
838 This macro is used with `prin1', `pp', etc. in order to ensure printed
839 Lisp objects are loadable.  Bind `print-quoted' and `print-readably'
840 to t, and `print-escape-multibyte', `print-escape-newlines',
841 `print-escape-nonascii', `print-length', `print-level' and
842 `print-string-length' to nil."
843   `(let ((print-quoted t)
844          (print-readably t)
845          ;;print-circle
846          ;;print-continuous-numbering
847          print-escape-multibyte
848          print-escape-newlines
849          print-escape-nonascii
850          ;;print-gensym
851          print-length
852          print-level
853          print-string-length)
854      ,@forms))
855
856 (defun gnus-prin1 (form)
857   "Use `prin1' on FORM in the current buffer.
858 Bind `print-quoted' and `print-readably' to t, and `print-length' and
859 `print-level' to nil.  See also `gnus-bind-print-variables'."
860   (gnus-bind-print-variables (prin1 form (current-buffer))))
861
862 (defun gnus-prin1-to-string (form)
863   "The same as `prin1'.
864 Bind `print-quoted' and `print-readably' to t, and `print-length' and
865 `print-level' to nil.  See also `gnus-bind-print-variables'."
866   (gnus-bind-print-variables (prin1-to-string form)))
867
868 (defun gnus-pp (form &optional stream)
869   "Use `pp' on FORM in the current buffer.
870 Bind `print-quoted' and `print-readably' to t, and `print-length' and
871 `print-level' to nil.  See also `gnus-bind-print-variables'."
872   (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
873
874 (defun gnus-pp-to-string (form)
875   "The same as `pp-to-string'.
876 Bind `print-quoted' and `print-readably' to t, and `print-length' and
877 `print-level' to nil.  See also `gnus-bind-print-variables'."
878   (gnus-bind-print-variables (pp-to-string form)))
879
880 (defun gnus-make-directory (directory)
881   "Make DIRECTORY (and all its parents) if it doesn't exist."
882   (require 'nnmail)
883   (let ((file-name-coding-system nnmail-pathname-coding-system))
884     (when (and directory
885                (not (file-exists-p directory)))
886       (make-directory directory t)))
887   t)
888
889 (defun gnus-write-buffer (file)
890   "Write the current buffer's contents to FILE."
891   (let ((file-name-coding-system nnmail-pathname-coding-system))
892     ;; Make sure the directory exists.
893     (gnus-make-directory (file-name-directory file))
894     ;; Write the buffer.
895     (write-region (point-min) (point-max) file nil 'quietly)))
896
897 (defun gnus-delete-file (file)
898   "Delete FILE if it exists."
899   (when (file-exists-p file)
900     (delete-file file)))
901
902 (defun gnus-delete-directory (directory)
903   "Delete files in DIRECTORY.  Subdirectories remain.
904 If there's no subdirectory, delete DIRECTORY as well."
905   (when (file-directory-p directory)
906     (let ((files (directory-files
907                   directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
908           file dir)
909       (while files
910         (setq file (pop files))
911         (if (eq t (car (file-attributes file)))
912             ;; `file' is a subdirectory.
913             (setq dir t)
914           ;; `file' is a file or a symlink.
915           (delete-file file)))
916       (unless dir
917         (delete-directory directory)))))
918
919 ;; The following two functions are used in gnus-registry.
920 ;; They were contributed by Andreas Fuchs <asf@void.at>.
921 (defun gnus-alist-to-hashtable (alist)
922   "Build a hashtable from the values in ALIST."
923   (let ((ht (make-hash-table
924              :size 4096
925              :test 'equal)))
926     (mapc
927      (lambda (kv-pair)
928        (puthash (car kv-pair) (cdr kv-pair) ht))
929      alist)
930      ht))
931
932 (defun gnus-hashtable-to-alist (hash)
933   "Build an alist from the values in HASH."
934   (let ((list nil))
935     (maphash
936      (lambda (key value)
937        (setq list (cons (cons key value) list)))
938      hash)
939     list))
940
941 (defun gnus-strip-whitespace (string)
942   "Return STRING stripped of all whitespace."
943   (while (string-match "[\r\n\t ]+" string)
944     (setq string (replace-match "" t t string)))
945   string)
946
947 (declare-function gnus-put-text-property "gnus"
948                   (start end property value &optional object))
949
950 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
951   "The same as `put-text-property', but don't put this prop on any newlines in the region."
952   (save-match-data
953     (save-excursion
954       (save-restriction
955         (goto-char beg)
956         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
957           (gnus-put-text-property beg (match-beginning 0) prop val)
958           (setq beg (point)))
959         (gnus-put-text-property beg (point) prop val)))))
960
961 (declare-function gnus-overlay-put  "gnus" (overlay prop value))
962 (declare-function gnus-make-overlay "gnus"
963                   (beg end &optional buffer front-advance rear-advance))
964
965 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
966   "The same as `put-text-property', but don't put this prop on any newlines in the region."
967   (save-match-data
968     (save-excursion
969       (save-restriction
970         (goto-char beg)
971         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
972           (gnus-overlay-put
973            (gnus-make-overlay beg (match-beginning 0))
974            prop val)
975           (setq beg (point)))
976         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
977
978 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
979                                                                    prop val)
980   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
981   (let ((b beg))
982     (while (/= b end)
983       (when (get-text-property b 'gnus-face)
984         (setq b (next-single-property-change b 'gnus-face nil end)))
985       (when (/= b end)
986         (inline
987           (gnus-put-text-property
988            b (setq b (next-single-property-change b 'gnus-face nil end))
989            prop val))))))
990
991 (defmacro gnus-faces-at (position)
992   "Return a list of faces at POSITION."
993   (if (featurep 'xemacs)
994       `(let ((pos ,position))
995          (mapcar-extents 'extent-face
996                          nil (current-buffer) pos pos nil 'face))
997     `(let ((pos ,position))
998        (delq nil (cons (get-text-property pos 'face)
999                        (mapcar
1000                         (lambda (overlay)
1001                           (overlay-get overlay 'face))
1002                         (overlays-at pos)))))))
1003
1004 (if (fboundp 'invisible-p)
1005     (defalias 'gnus-invisible-p 'invisible-p)
1006   ;; for Emacs < 22.2, and XEmacs.
1007   (defun gnus-invisible-p (pos)
1008     "Return non-nil if the character after POS is currently invisible."
1009     (let ((prop (get-char-property pos 'invisible)))
1010       (if (eq buffer-invisibility-spec t)
1011           prop
1012         (or (memq prop buffer-invisibility-spec)
1013             (assq prop buffer-invisibility-spec))))))
1014
1015 ;; Note: the optional 2nd argument has a different meaning between
1016 ;; Emacs and XEmacs.
1017 ;; (next-char-property-change POSITION &optional LIMIT)
1018 ;; (next-extent-change        POS      &optional OBJECT)
1019 (defalias 'gnus-next-char-property-change
1020   (if (fboundp 'next-extent-change)
1021       'next-extent-change 'next-char-property-change))
1022
1023 (defalias 'gnus-previous-char-property-change
1024   (if (fboundp 'previous-extent-change)
1025       'previous-extent-change 'previous-char-property-change))
1026
1027 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
1028 ;; The primary idea here is to try to protect internal datastructures
1029 ;; from becoming corrupted when the user hits C-g, or if a hook or
1030 ;; similar blows up.  Often in Gnus multiple tables/lists need to be
1031 ;; updated at the same time, or information can be lost.
1032
1033 (defvar gnus-atomic-be-safe t
1034   "If t, certain operations will be protected from interruption by C-g.")
1035
1036 (defmacro gnus-atomic-progn (&rest forms)
1037   "Evaluate FORMS atomically, which means to protect the evaluation
1038 from being interrupted by the user.  An error from the forms themselves
1039 will return without finishing the operation.  Since interrupts from
1040 the user are disabled, it is recommended that only the most minimal
1041 operations are performed by FORMS.  If you wish to assign many
1042 complicated values atomically, compute the results into temporary
1043 variables and then do only the assignment atomically."
1044   `(let ((inhibit-quit gnus-atomic-be-safe))
1045      ,@forms))
1046
1047 (put 'gnus-atomic-progn 'lisp-indent-function 0)
1048
1049 (defmacro gnus-atomic-progn-assign (protect &rest forms)
1050   "Evaluate FORMS, but ensure that the variables listed in PROTECT
1051 are not changed if anything in FORMS signals an error or otherwise
1052 non-locally exits.  The variables listed in PROTECT are updated atomically.
1053 It is safe to use gnus-atomic-progn-assign with long computations.
1054
1055 Note that if any of the symbols in PROTECT were unbound, they will be
1056 set to nil on a successful assignment.  In case of an error or other
1057 non-local exit, it will still be unbound."
1058   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
1059                                                   (concat (symbol-name x)
1060                                                           "-tmp"))
1061                                                  x))
1062                                protect))
1063          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
1064                                temp-sym-map))
1065          (temp-sym-let (mapcar (lambda (x) (list (car x)
1066                                                  `(and (boundp ',(cadr x))
1067                                                        ,(cadr x))))
1068                                temp-sym-map))
1069          (sym-temp-let sym-temp-map)
1070          (temp-sym-assign (apply 'append temp-sym-map))
1071          (sym-temp-assign (apply 'append sym-temp-map))
1072          (result (make-symbol "result-tmp")))
1073     `(let (,@temp-sym-let
1074            ,result)
1075        (let ,sym-temp-let
1076          (setq ,result (progn ,@forms))
1077          (setq ,@temp-sym-assign))
1078        (let ((inhibit-quit gnus-atomic-be-safe))
1079          (setq ,@sym-temp-assign))
1080        ,result)))
1081
1082 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
1083 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
1084
1085 (defmacro gnus-atomic-setq (&rest pairs)
1086   "Similar to setq, except that the real symbols are only assigned when
1087 there are no errors.  And when the real symbols are assigned, they are
1088 done so atomically.  If other variables might be changed via side-effect,
1089 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
1090 with potentially long computations."
1091   (let ((tpairs pairs)
1092         syms)
1093     (while tpairs
1094       (push (car tpairs) syms)
1095       (setq tpairs (cddr tpairs)))
1096     `(gnus-atomic-progn-assign ,syms
1097        (setq ,@pairs))))
1098
1099 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
1100
1101
1102 ;;; Functions for saving to babyl/mail files.
1103
1104 (eval-when-compile
1105   (if (featurep 'xemacs)
1106       ;; Don't load tm and apel XEmacs packages that provide some
1107       ;; Emacs emulating functions and variables.
1108       (let ((features features))
1109         (provide 'tm-view)
1110         (unless (fboundp 'set-alist) (defalias 'set-alist 'ignore))
1111         (require 'rmail)) ;; It requires tm-view that loads apel.
1112     (require 'rmail))
1113   (autoload 'rmail-update-summary "rmailsum"))
1114
1115 (defvar mm-text-coding-system)
1116
1117 (declare-function mm-append-to-file "mm-util"
1118                   (start end filename &optional codesys inhibit))
1119
1120 (defun gnus-output-to-rmail (filename &optional ask)
1121   "Append the current article to an Rmail file named FILENAME.
1122 In Emacs 22 this writes Babyl format; in Emacs 23 it writes mbox unless
1123 FILENAME exists and is Babyl format."
1124   (require 'rmail)
1125   (require 'mm-util)
1126   ;; Some of this codes is borrowed from rmailout.el.
1127   (setq filename (expand-file-name filename))
1128   ;; FIXME should we really be messing with this defcustom?
1129   ;; It is not needed for the operation of this function.
1130   (if (boundp 'rmail-default-rmail-file)
1131       (setq rmail-default-rmail-file filename) ; 22
1132     (setq rmail-default-file filename))        ; 23
1133   (let ((artbuf (current-buffer))
1134         (tmpbuf (get-buffer-create " *Gnus-output*"))
1135         ;; Babyl rmail.el defines this, mbox does not.
1136         (babyl (fboundp 'rmail-insert-rmail-file-header)))
1137     (save-excursion
1138       ;; Note that we ignore the possibility of visiting a Babyl
1139       ;; format buffer in Emacs 23, since Rmail no longer supports that.
1140      (or (get-file-buffer filename)
1141          (progn
1142            ;; In case someone wants to write to a Babyl file from Emacs 23.
1143            (when (file-exists-p filename)
1144              (setq babyl (mail-file-babyl-p filename))
1145              t))
1146           (if (or (not ask)
1147                   (gnus-yes-or-no-p
1148                    (concat "\"" filename "\" does not exist, create it? ")))
1149               (let ((file-buffer (create-file-buffer filename)))
1150                 (with-current-buffer file-buffer
1151                   (if (fboundp 'rmail-insert-rmail-file-header)
1152                       (rmail-insert-rmail-file-header))
1153                   (let ((require-final-newline nil)
1154                         (coding-system-for-write mm-text-coding-system))
1155                     (gnus-write-buffer filename)))
1156                 (kill-buffer file-buffer))
1157             (error "Output file does not exist")))
1158       (set-buffer tmpbuf)
1159       (erase-buffer)
1160       (insert-buffer-substring artbuf)
1161       (if babyl
1162           (gnus-convert-article-to-rmail)
1163         ;; Non-Babyl case copied from gnus-output-to-mail.
1164         (goto-char (point-min))
1165         (if (looking-at "From ")
1166             (forward-line 1)
1167           (insert "From nobody " (current-time-string) "\n"))
1168         (let (case-fold-search)
1169           (while (re-search-forward "^From " nil t)
1170             (beginning-of-line)
1171             (insert ">"))))
1172       ;; Decide whether to append to a file or to an Emacs buffer.
1173       (let ((outbuf (get-file-buffer filename)))
1174         (if (not outbuf)
1175             (progn
1176               (unless babyl             ; from gnus-output-to-mail
1177                 (let ((buffer-read-only nil))
1178                   (goto-char (point-max))
1179                   (forward-char -2)
1180                   (unless (looking-at "\n\n")
1181                     (goto-char (point-max))
1182                     (unless (bolp)
1183                       (insert "\n"))
1184                     (insert "\n"))))
1185               (let ((file-name-coding-system nnmail-pathname-coding-system))
1186                 (mm-append-to-file (point-min) (point-max) filename)))
1187           ;; File has been visited, in buffer OUTBUF.
1188           (set-buffer outbuf)
1189           (let ((buffer-read-only nil)
1190                 (msg (and (boundp 'rmail-current-message)
1191                           (symbol-value 'rmail-current-message))))
1192             ;; If MSG is non-nil, buffer is in RMAIL mode.
1193             ;; Compare this with rmail-output-to-rmail-buffer in Emacs 23.
1194             (when msg
1195               (unless babyl
1196                 (rmail-swap-buffers-maybe)
1197                 (rmail-maybe-set-message-counters))
1198               (widen)
1199               (narrow-to-region (point-max) (point-max)))
1200             (insert-buffer-substring tmpbuf)
1201             (when msg
1202               (when babyl
1203                 (goto-char (point-min))
1204                 (widen)
1205                 (search-backward "\n\^_")
1206                 (narrow-to-region (point) (point-max)))
1207               (rmail-count-new-messages t)
1208               (when (rmail-summary-exists)
1209                 (rmail-select-summary
1210                  (rmail-update-summary)))
1211               (rmail-show-message msg))
1212             (save-buffer)))))
1213     (kill-buffer tmpbuf)))
1214
1215 (defun gnus-output-to-mail (filename &optional ask)
1216   "Append the current article to a mail file named FILENAME."
1217   (setq filename (expand-file-name filename))
1218   (let ((artbuf (current-buffer))
1219         (tmpbuf (get-buffer-create " *Gnus-output*")))
1220     (save-excursion
1221       ;; Create the file, if it doesn't exist.
1222       (when (and (not (get-file-buffer filename))
1223                  (not (file-exists-p filename)))
1224         (if (or (not ask)
1225                 (gnus-y-or-n-p
1226                  (concat "\"" filename "\" does not exist, create it? ")))
1227             (let ((file-buffer (create-file-buffer filename)))
1228               (with-current-buffer file-buffer
1229                 (let ((require-final-newline nil)
1230                       (coding-system-for-write mm-text-coding-system))
1231                   (gnus-write-buffer filename)))
1232               (kill-buffer file-buffer))
1233           (error "Output file does not exist")))
1234       (set-buffer tmpbuf)
1235       (erase-buffer)
1236       (insert-buffer-substring artbuf)
1237       (goto-char (point-min))
1238       (if (looking-at "From ")
1239           (forward-line 1)
1240         (insert "From nobody " (current-time-string) "\n"))
1241       (let (case-fold-search)
1242         (while (re-search-forward "^From " nil t)
1243           (beginning-of-line)
1244           (insert ">")))
1245       ;; Decide whether to append to a file or to an Emacs buffer.
1246       (let ((outbuf (get-file-buffer filename)))
1247         (if (not outbuf)
1248             (let ((buffer-read-only nil))
1249               (save-excursion
1250                 (goto-char (point-max))
1251                 (forward-char -2)
1252                 (unless (looking-at "\n\n")
1253                   (goto-char (point-max))
1254                   (unless (bolp)
1255                     (insert "\n"))
1256                   (insert "\n"))
1257                 (goto-char (point-max))
1258                 (let ((file-name-coding-system nnmail-pathname-coding-system))
1259                   (mm-append-to-file (point-min) (point-max) filename))))
1260           ;; File has been visited, in buffer OUTBUF.
1261           (set-buffer outbuf)
1262           (let ((buffer-read-only nil))
1263             (goto-char (point-max))
1264             (unless (eobp)
1265               (insert "\n"))
1266             (insert "\n")
1267             (insert-buffer-substring tmpbuf)))))
1268     (kill-buffer tmpbuf)))
1269
1270 (defun gnus-convert-article-to-rmail ()
1271   "Convert article in current buffer to Rmail message format."
1272   (let ((buffer-read-only nil))
1273     ;; Convert article directly into Babyl format.
1274     (goto-char (point-min))
1275     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1276     (while (search-forward "\n\^_" nil t) ;single char
1277       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
1278     (goto-char (point-max))
1279     (insert "\^_")))
1280
1281 (defun gnus-map-function (funs arg)
1282   "Apply the result of the first function in FUNS to the second, and so on.
1283 ARG is passed to the first function."
1284   (while funs
1285     (setq arg (funcall (pop funs) arg)))
1286   arg)
1287
1288 (defun gnus-run-hooks (&rest funcs)
1289   "Does the same as `run-hooks', but saves the current buffer."
1290   (save-current-buffer
1291     (apply 'run-hooks funcs)))
1292
1293 (defun gnus-run-mode-hooks (&rest funcs)
1294   "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1295 This function saves the current buffer."
1296   (if (fboundp 'run-mode-hooks)
1297       (save-current-buffer (apply 'run-mode-hooks funcs))
1298     (save-current-buffer (apply 'run-hooks funcs))))
1299
1300 ;;; Various
1301
1302 (defvar gnus-group-buffer)              ; Compiler directive
1303 (defun gnus-alive-p ()
1304   "Say whether Gnus is running or not."
1305   (and (boundp 'gnus-group-buffer)
1306        (get-buffer gnus-group-buffer)
1307        (with-current-buffer gnus-group-buffer
1308          (eq major-mode 'gnus-group-mode))))
1309
1310 (defun gnus-remove-if (predicate list)
1311   "Return a copy of LIST with all items satisfying PREDICATE removed."
1312   (let (out)
1313     (while list
1314       (unless (funcall predicate (car list))
1315         (push (car list) out))
1316       (setq list (cdr list)))
1317     (nreverse out)))
1318
1319 (if (fboundp 'assq-delete-all)
1320     (defalias 'gnus-delete-alist 'assq-delete-all)
1321   (defun gnus-delete-alist (key alist)
1322     "Delete from ALIST all elements whose car is KEY.
1323 Return the modified alist."
1324     (let (entry)
1325       (while (setq entry (assq key alist))
1326         (setq alist (delq entry alist)))
1327       alist)))
1328
1329 (defun gnus-grep-in-list (word list)
1330   "Find if a WORD matches any regular expression in the given LIST."
1331   (when (and word list)
1332     (catch 'found
1333       (dolist (r list)
1334         (when (string-match r word)
1335           (throw 'found r))))))
1336
1337 (defmacro gnus-pull (key alist &optional assoc-p)
1338   "Modify ALIST to be without KEY."
1339   (unless (symbolp alist)
1340     (error "Not a symbol: %s" alist))
1341   (let ((fun (if assoc-p 'assoc 'assq)))
1342     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1343
1344 (defun gnus-globalify-regexp (re)
1345   "Return a regexp that matches a whole line, if RE matches a part of it."
1346   (concat (unless (string-match "^\\^" re) "^.*")
1347           re
1348           (unless (string-match "\\$$" re) ".*$")))
1349
1350 (defun gnus-set-window-start (&optional point)
1351   "Set the window start to POINT, or (point) if nil."
1352   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1353     (when win
1354       (set-window-start win (or point (point))))))
1355
1356 (defun gnus-annotation-in-region-p (b e)
1357   (if (= b e)
1358       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1359     (text-property-any b e 'gnus-undeletable t)))
1360
1361 (defun gnus-or (&rest elems)
1362   "Return non-nil if any of the elements are non-nil."
1363   (catch 'found
1364     (while elems
1365       (when (pop elems)
1366         (throw 'found t)))))
1367
1368 (defun gnus-and (&rest elems)
1369   "Return non-nil if all of the elements are non-nil."
1370   (catch 'found
1371     (while elems
1372       (unless (pop elems)
1373         (throw 'found nil)))
1374     t))
1375
1376 ;; gnus.el requires mm-util.
1377 (declare-function mm-disable-multibyte "mm-util")
1378
1379 (defun gnus-write-active-file (file hashtb &optional full-names)
1380   ;; `coding-system-for-write' should be `raw-text' or equivalent.
1381   (let ((coding-system-for-write nnmail-active-file-coding-system))
1382     (with-temp-file file
1383       ;; The buffer should be in the unibyte mode because group names
1384       ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1385       (mm-disable-multibyte)
1386       (mapatoms
1387        (lambda (sym)
1388          (when (and sym
1389                     (boundp sym)
1390                     (symbol-value sym))
1391            (insert (format "%S %d %d y\n"
1392                            (if full-names
1393                                sym
1394                              (intern (gnus-group-real-name (symbol-name sym))))
1395                            (or (cdr (symbol-value sym))
1396                                (car (symbol-value sym)))
1397                            (car (symbol-value sym))))))
1398        hashtb)
1399       (goto-char (point-max))
1400       (while (search-backward "\\." nil t)
1401         (delete-char 1)))))
1402
1403 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1404 (defmacro gnus-with-output-to-file (file &rest body)
1405   (let ((buffer (make-symbol "output-buffer"))
1406         (size (make-symbol "output-buffer-size"))
1407         (leng (make-symbol "output-buffer-length"))
1408         (append (make-symbol "output-buffer-append")))
1409     `(let* ((,size 131072)
1410             (,buffer (make-string ,size 0))
1411             (,leng 0)
1412             (,append nil)
1413             (standard-output
1414              (lambda (c)
1415                (aset ,buffer ,leng c)
1416
1417                (if (= ,size (setq ,leng (1+ ,leng)))
1418                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1419                           (setq ,leng 0
1420                                 ,append t))))))
1421        ,@body
1422        (when (> ,leng 0)
1423          (let ((coding-system-for-write 'no-conversion))
1424          (write-region (substring ,buffer 0 ,leng) nil ,file
1425                        ,append 'no-msg))))))
1426
1427 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1428 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1429
1430 (if (fboundp 'union)
1431     (defalias 'gnus-union 'union)
1432   (defun gnus-union (l1 l2)
1433     "Set union of lists L1 and L2."
1434     (cond ((null l1) l2)
1435           ((null l2) l1)
1436           ((equal l1 l2) l1)
1437           (t
1438            (or (>= (length l1) (length l2))
1439                (setq l1 (prog1 l2 (setq l2 l1))))
1440            (while l2
1441              (or (member (car l2) l1)
1442                  (push (car l2) l1))
1443              (pop l2))
1444            l1))))
1445
1446 (declare-function gnus-add-text-properties "gnus"
1447                   (start end properties &optional object))
1448
1449 (defun gnus-add-text-properties-when
1450   (property value start end properties &optional object)
1451   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1452   (let (point)
1453     (while (and start
1454                 (< start end) ;; XEmacs will loop for every when start=end.
1455                 (setq point (text-property-not-all start end property value)))
1456       (gnus-add-text-properties start point properties object)
1457       (setq start (text-property-any point end property value)))
1458     (if start
1459         (gnus-add-text-properties start end properties object))))
1460
1461 (defun gnus-remove-text-properties-when
1462   (property value start end properties &optional object)
1463   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1464   (let (point)
1465     (while (and start
1466                 (< start end)
1467                 (setq point (text-property-not-all start end property value)))
1468       (remove-text-properties start point properties object)
1469       (setq start (text-property-any point end property value)))
1470     (if start
1471         (remove-text-properties start end properties object))
1472     t))
1473
1474 (defun gnus-string-remove-all-properties (string)
1475   (condition-case ()
1476       (let ((s string))
1477         (set-text-properties 0 (length string) nil string)
1478         s)
1479     (error string)))
1480
1481 ;; This might use `compare-strings' to reduce consing in the
1482 ;; case-insensitive case, but it has to cope with null args.
1483 ;; (`string-equal' uses symbol print names.)
1484 (defun gnus-string-equal (x y)
1485   "Like `string-equal', except it compares case-insensitively."
1486   (and (= (length x) (length y))
1487        (or (string-equal x y)
1488            (string-equal (downcase x) (downcase y)))))
1489
1490 (defcustom gnus-use-byte-compile t
1491   "If non-nil, byte-compile crucial run-time code.
1492 Setting it to nil has no effect after the first time `gnus-byte-compile'
1493 is run."
1494   :type 'boolean
1495   :version "22.1"
1496   :group 'gnus-various)
1497
1498 (defun gnus-byte-compile (form)
1499   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1500   (if gnus-use-byte-compile
1501       (progn
1502         (condition-case nil
1503             ;; Work around a bug in XEmacs 21.4
1504             (require 'byte-optimize)
1505           (error))
1506         (require 'bytecomp)
1507         (defalias 'gnus-byte-compile
1508           (lambda (form)
1509             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1510               (byte-compile form))))
1511         (gnus-byte-compile form))
1512     form))
1513
1514 (defun gnus-remassoc (key alist)
1515   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1516 The modified LIST is returned.  If the first member
1517 of LIST has a car that is `equal' to KEY, there is no way to remove it
1518 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1519 sure of changing the value of `foo'."
1520   (when alist
1521     (if (equal key (caar alist))
1522         (cdr alist)
1523       (setcdr alist (gnus-remassoc key (cdr alist)))
1524       alist)))
1525
1526 (defun gnus-update-alist-soft (key value alist)
1527   (if value
1528       (cons (cons key value) (gnus-remassoc key alist))
1529     (gnus-remassoc key alist)))
1530
1531 (defun gnus-create-info-command (node)
1532   "Create a command that will go to info NODE."
1533   `(lambda ()
1534      (interactive)
1535      ,(concat "Enter the info system at node " node)
1536      (Info-goto-node ,node)
1537      (setq gnus-info-buffer (current-buffer))
1538      (gnus-configure-windows 'info)))
1539
1540 (defun gnus-not-ignore (&rest args)
1541   t)
1542
1543 (defvar gnus-directory-sep-char-regexp "/"
1544   "The regexp of directory separator character.
1545 If you find some problem with the directory separator character, try
1546 \"[/\\\\\]\" for some systems.")
1547
1548 (defun gnus-url-unhex (x)
1549   (if (> x ?9)
1550       (if (>= x ?a)
1551           (+ 10 (- x ?a))
1552         (+ 10 (- x ?A)))
1553     (- x ?0)))
1554
1555 ;; Fixme: Do it like QP.
1556 (defun gnus-url-unhex-string (str &optional allow-newlines)
1557   "Remove %XX, embedded spaces, etc in a url.
1558 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1559 decoding of carriage returns and line feeds in the string, which is normally
1560 forbidden in URL encoding."
1561   (let ((tmp "")
1562         (case-fold-search t))
1563     (while (string-match "%[0-9a-f][0-9a-f]" str)
1564       (let* ((start (match-beginning 0))
1565              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1566              (code (+ (* 16 ch1)
1567                       (gnus-url-unhex (elt str (+ start 2))))))
1568         (setq tmp (concat
1569                    tmp (substring str 0 start)
1570                    (cond
1571                     (allow-newlines
1572                      (char-to-string code))
1573                     ((or (= code ?\n) (= code ?\r))
1574                      " ")
1575                     (t (char-to-string code))))
1576               str (substring str (match-end 0)))))
1577     (setq tmp (concat tmp str))
1578     tmp))
1579
1580 (defun gnus-make-predicate (spec)
1581   "Transform SPEC into a function that can be called.
1582 SPEC is a predicate specifier that contains stuff like `or', `and',
1583 `not', lists and functions.  The functions all take one parameter."
1584   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1585
1586 (defun gnus-make-predicate-1 (spec)
1587   (cond
1588    ((symbolp spec)
1589     `(,spec elem))
1590    ((listp spec)
1591     (if (memq (car spec) '(or and not))
1592         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1593       (error "Invalid predicate specifier: %s" spec)))))
1594
1595 (defun gnus-completing-read (prompt collection &optional require-match
1596                                     initial-input history def)
1597   "Call `gnus-completing-read-function'."
1598   (funcall gnus-completing-read-function
1599            (concat prompt (when def
1600                             (concat " (default " def ")"))
1601                    ": ")
1602            collection require-match initial-input history def))
1603
1604 (defun gnus-emacs-completing-read (prompt collection &optional require-match
1605                                           initial-input history def)
1606   "Call standard `completing-read-function'."
1607   (let ((completion-styles gnus-completion-styles))
1608     (completing-read prompt
1609                      ;; Old XEmacs (at least 21.4) expect an alist for
1610                      ;; collection.
1611                      (mapcar 'list collection)
1612                      nil require-match initial-input history def)))
1613
1614 (autoload 'ido-completing-read "ido")
1615 (defun gnus-ido-completing-read (prompt collection &optional require-match
1616                                         initial-input history def)
1617   "Call `ido-completing-read-function'."
1618   (ido-completing-read prompt collection nil require-match initial-input history def))
1619
1620
1621 (autoload 'iswitchb-read-buffer "iswitchb")
1622 (defun gnus-iswitchb-completing-read (prompt collection &optional require-match
1623                                             initial-input history def)
1624   "`iswitchb' based completing-read function."
1625   (let ((iswitchb-make-buflist-hook
1626          (lambda ()
1627            (setq iswitchb-temp-buflist
1628                  (let ((choices (append
1629                                  (when initial-input (list initial-input))
1630                                  (symbol-value history) collection))
1631                        filtered-choices)
1632                    (dolist (x choices)
1633                      (setq filtered-choices (adjoin x filtered-choices)))
1634                    (nreverse filtered-choices))))))
1635     (unwind-protect
1636         (progn
1637           (when (not iswitchb-mode)
1638             (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup))
1639           (iswitchb-read-buffer prompt def require-match))
1640       (when (not iswitchb-mode)
1641         (remove-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)))))
1642
1643 (defun gnus-graphic-display-p ()
1644   (if (featurep 'xemacs)
1645       (device-on-window-system-p)
1646     (display-graphic-p)))
1647
1648 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1649 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1650
1651 (defmacro gnus-parse-without-error (&rest body)
1652   "Allow continuing onto the next line even if an error occurs."
1653   `(while (not (eobp))
1654      (condition-case ()
1655          (progn
1656            ,@body
1657            (goto-char (point-max)))
1658        (error
1659         (gnus-error 4 "Invalid data on line %d"
1660                     (count-lines (point-min) (point)))
1661         (forward-line 1)))))
1662
1663 (defun gnus-cache-file-contents (file variable function)
1664   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1665   (let ((time (nth 5 (file-attributes file)))
1666         contents value)
1667     (if (or (null (setq value (symbol-value variable)))
1668             (not (equal (car value) file))
1669             (not (equal (nth 1 value) time)))
1670         (progn
1671           (setq contents (funcall function file))
1672           (set variable (list file time contents))
1673           contents)
1674       (nth 2 value))))
1675
1676 (defun gnus-multiple-choice (prompt choice &optional idx)
1677   "Ask user a multiple choice question.
1678 CHOICE is a list of the choice char and help message at IDX."
1679   (let (tchar buf)
1680     (save-window-excursion
1681       (save-excursion
1682         (while (not tchar)
1683           (message "%s (%s): "
1684                    prompt
1685                    (concat
1686                     (mapconcat (lambda (s) (char-to-string (car s)))
1687                                choice ", ") ", ?"))
1688           (setq tchar (read-char))
1689           (when (not (assq tchar choice))
1690             (setq tchar nil)
1691             (setq buf (get-buffer-create "*Gnus Help*"))
1692             (pop-to-buffer buf)
1693             (fundamental-mode)          ; for Emacs 20.4+
1694             (buffer-disable-undo)
1695             (erase-buffer)
1696             (insert prompt ":\n\n")
1697             (let ((max -1)
1698                   (list choice)
1699                   (alist choice)
1700                   (idx (or idx 1))
1701                   (i 0)
1702                   n width pad format)
1703               ;; find the longest string to display
1704               (while list
1705                 (setq n (length (nth idx (car list))))
1706                 (unless (> max n)
1707                   (setq max n))
1708                 (setq list (cdr list)))
1709               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1710               (setq n (/ (1- (window-width)) max)) ; items per line
1711               (setq width (/ (1- (window-width)) n)) ; width of each item
1712               ;; insert `n' items, each in a field of width `width'
1713               (while alist
1714                 (if (< i n)
1715                     ()
1716                   (setq i 0)
1717                   (delete-char -1)              ; the `\n' takes a char
1718                   (insert "\n"))
1719                 (setq pad (- width 3))
1720                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1721                 (insert (format format (caar alist) (nth idx (car alist))))
1722                 (setq alist (cdr alist))
1723                 (setq i (1+ i))))))))
1724     (if (buffer-live-p buf)
1725         (kill-buffer buf))
1726     tchar))
1727
1728 (if (fboundp 'select-frame-set-input-focus)
1729     (defalias 'gnus-select-frame-set-input-focus 'select-frame-set-input-focus)
1730   ;; XEmacs 21.4, SXEmacs
1731   (defun gnus-select-frame-set-input-focus (frame)
1732     "Select FRAME, raise it, and set input focus, if possible."
1733     (raise-frame frame)
1734     (select-frame frame)
1735     (focus-frame frame)))
1736
1737 (defun gnus-frame-or-window-display-name (object)
1738   "Given a frame or window, return the associated display name.
1739 Return nil otherwise."
1740   (if (featurep 'xemacs)
1741       (device-connection (dfw-device object))
1742     (if (or (framep object)
1743             (and (windowp object)
1744                  (setq object (window-frame object))))
1745         (let ((display (frame-parameter object 'display)))
1746           (if (and (stringp display)
1747                    ;; Exclude invalid display names.
1748                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1749                                  display))
1750               display)))))
1751
1752 (defvar tool-bar-mode)
1753
1754 (defun gnus-tool-bar-update (&rest ignore)
1755   "Update the tool bar."
1756   (when (and (boundp 'tool-bar-mode)
1757              tool-bar-mode)
1758     (let* ((args nil)
1759            (func (cond ((featurep 'xemacs)
1760                         'ignore)
1761                        ((fboundp 'tool-bar-update)
1762                         'tool-bar-update)
1763                        ((fboundp 'force-window-update)
1764                         'force-window-update)
1765                        ((fboundp 'redraw-frame)
1766                         (setq args (list (selected-frame)))
1767                         'redraw-frame)
1768                        (t 'ignore))))
1769       (apply func args))))
1770
1771 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1772 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1773   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1774 If there are several sequences, FUNCTION is called with that many arguments,
1775 and mapping stops as soon as the shortest sequence runs out.  With just one
1776 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1777 `mapcar' function extended to arbitrary sequence types."
1778
1779   (if seqs2_n
1780       (let* ((seqs (cons seq1 seqs2_n))
1781              (cnt 0)
1782              (heads (mapcar (lambda (seq)
1783                               (make-symbol (concat "head"
1784                                                    (int-to-string
1785                                                     (setq cnt (1+ cnt))))))
1786                             seqs))
1787              (result (make-symbol "result"))
1788              (result-tail (make-symbol "result-tail")))
1789         `(let* ,(let* ((bindings (cons nil nil))
1790                        (heads heads))
1791                   (nconc bindings (list (list result '(cons nil nil))))
1792                   (nconc bindings (list (list result-tail result)))
1793                   (while heads
1794                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1795                   (cdr bindings))
1796            (while (and ,@heads)
1797              (setcdr ,result-tail (cons (funcall ,function
1798                                                  ,@(mapcar (lambda (h) (list 'car h))
1799                                                            heads))
1800                                         nil))
1801              (setq ,result-tail (cdr ,result-tail)
1802                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1803            (cdr ,result)))
1804     `(mapcar ,function ,seq1)))
1805
1806 (if (fboundp 'merge)
1807     (defalias 'gnus-merge 'merge)
1808   ;; Adapted from cl-seq.el
1809   (defun gnus-merge (type list1 list2 pred)
1810     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1811 Argument TYPE is for compatibility and ignored.
1812 Ordering of the elements is preserved according to PRED, a `less-than'
1813 predicate on the elements."
1814     (let ((res nil))
1815       (while (and list1 list2)
1816         (if (funcall pred (car list2) (car list1))
1817             (push (pop list2) res)
1818           (push (pop list1) res)))
1819       (nconc (nreverse res) list1 list2))))
1820
1821 (defvar xemacs-codename)
1822 (defvar sxemacs-codename)
1823 (defvar emacs-program-version)
1824
1825 (defun gnus-emacs-version ()
1826   "Stringified Emacs version."
1827   (let* ((lst (if (listp gnus-user-agent)
1828                   gnus-user-agent
1829                 '(gnus emacs type)))
1830          (system-v (cond ((memq 'config lst)
1831                           system-configuration)
1832                          ((memq 'type lst)
1833                           (symbol-name system-type))
1834                          (t nil)))
1835          codename emacsname)
1836     (cond ((featurep 'sxemacs)
1837            (setq emacsname "SXEmacs"
1838                  codename sxemacs-codename))
1839           ((featurep 'xemacs)
1840            (setq emacsname "XEmacs"
1841                  codename xemacs-codename))
1842           (t
1843            (setq emacsname "Emacs")))
1844     (cond
1845      ((not (memq 'emacs lst))
1846       nil)
1847      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1848       ;; Emacs:
1849       (concat "Emacs/" (match-string 1 emacs-version)
1850               (if system-v
1851                   (concat " (" system-v ")")
1852                 "")))
1853      ((or (featurep 'sxemacs) (featurep 'xemacs))
1854       ;; XEmacs or SXEmacs:
1855       (concat emacsname "/" emacs-program-version
1856               (let (plst)
1857                 (when (memq 'codename lst)
1858                   (push codename plst))
1859                 (when system-v
1860                   (push system-v plst))
1861                 (unless (featurep 'mule)
1862                   (push "no MULE" plst))
1863                 (when (> (length plst) 0)
1864                   (concat
1865                    " (" (mapconcat 'identity (reverse plst) ", ") ")")))))
1866      (t emacs-version))))
1867
1868 (defun gnus-rename-file (old-path new-path &optional trim)
1869   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1870 empty directories from OLD-PATH."
1871   (when (file-exists-p old-path)
1872     (let* ((old-dir (file-name-directory old-path))
1873            (old-name (file-name-nondirectory old-path))
1874            (new-dir (file-name-directory new-path))
1875            (new-name (file-name-nondirectory new-path))
1876            temp)
1877       (gnus-make-directory new-dir)
1878       (rename-file old-path new-path t)
1879       (when trim
1880         (while (progn (setq temp (directory-files old-dir))
1881                       (while (member (car temp) '("." ".."))
1882                         (setq temp (cdr temp)))
1883                       (= (length temp) 0))
1884           (delete-directory old-dir)
1885           (setq old-dir (file-name-as-directory
1886                          (file-truename
1887                           (concat old-dir "..")))))))))
1888
1889 (defun gnus-set-file-modes (filename mode)
1890   "Wrapper for set-file-modes."
1891   (ignore-errors
1892     (set-file-modes filename mode)))
1893
1894 (if (fboundp 'set-process-query-on-exit-flag)
1895     (defalias 'gnus-set-process-query-on-exit-flag
1896       'set-process-query-on-exit-flag)
1897   (defalias 'gnus-set-process-query-on-exit-flag
1898     'process-kill-without-query))
1899
1900 (if (fboundp 'with-local-quit)
1901     (defalias 'gnus-with-local-quit 'with-local-quit)
1902   (defmacro gnus-with-local-quit (&rest body)
1903     "Execute BODY, allowing quits to terminate BODY but not escape further.
1904 When a quit terminates BODY, `gnus-with-local-quit' returns nil but
1905 requests another quit.  That quit will be processed as soon as quitting
1906 is allowed once again.  (Immediately, if `inhibit-quit' is nil.)"
1907     ;;(declare (debug t) (indent 0))
1908     `(condition-case nil
1909          (let ((inhibit-quit nil))
1910            ,@body)
1911        (quit (setq quit-flag t)
1912              ;; This call is to give a chance to handle quit-flag
1913              ;; in case inhibit-quit is nil.
1914              ;; Without this, it will not be handled until the next function
1915              ;; call, and that might allow it to exit thru a condition-case
1916              ;; that intends to handle the quit signal next time.
1917              (eval '(ignore nil))))))
1918
1919 (defalias 'gnus-read-shell-command
1920   (if (fboundp 'read-shell-command) 'read-shell-command 'read-string))
1921
1922 (defmacro gnus-put-display-table (range value display-table)
1923   "Set the value for char RANGE to VALUE in DISPLAY-TABLE.  "
1924   (if (featurep 'xemacs)
1925       (progn
1926         `(if (fboundp 'put-display-table)
1927           (put-display-table ,range ,value ,display-table)
1928           (if (sequencep ,display-table)
1929               (aset ,display-table ,range ,value)
1930             (put-char-table ,range ,value ,display-table))))
1931     `(aset ,display-table ,range ,value)))
1932
1933 (defmacro gnus-get-display-table (character display-table)
1934   "Find value for CHARACTER in DISPLAY-TABLE.  "
1935   (if (featurep 'xemacs)
1936       `(if (fboundp 'get-display-table)
1937           (get-display-table ,character ,display-table)
1938           (if (sequencep ,display-table)
1939               (aref ,display-table ,character)
1940             (get-char-table ,character ,display-table)))
1941     `(aref ,display-table ,character)))
1942
1943 (defun gnus-rescale-image (image size)
1944   "Rescale IMAGE to SIZE if possible.
1945 SIZE is in format (WIDTH . HEIGHT). Return a new image.
1946 Sizes are in pixels."
1947   (if (or (not (fboundp 'imagemagick-types))
1948           (not (get-buffer-window (current-buffer))))
1949       image
1950     (let ((new-width (car size))
1951           (new-height (cdr size)))
1952       (when (> (cdr (image-size image t)) new-height)
1953         (setq image (or (create-image (plist-get (cdr image) :data) 'imagemagick t
1954                                       :height new-height)
1955                         image)))
1956       (when (> (car (image-size image t)) new-width)
1957         (setq image (or
1958                    (create-image (plist-get (cdr image) :data) 'imagemagick t
1959                                  :width new-width)
1960                    image)))
1961       image)))
1962
1963 (provide 'gnus-util)
1964
1965 ;;; gnus-util.el ends here