* spam-stat.el (spam-stat-process-directory-age): New option.
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Nothing in this file depends on any other parts of Gnus -- all
28 ;; functions and macros in this file are utility functions that are
29 ;; used by Gnus and may be used by any other package without loading
30 ;; Gnus first.
31
32 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
33 ;; autoloads below...]
34
35 ;;; Code:
36
37 (eval-when-compile
38   (require 'cl)
39   ;; Fixme: this should be a gnus variable, not nnmail-.
40   (defvar nnmail-pathname-coding-system))
41 (require 'time-date)
42 (require 'netrc)
43
44 (eval-and-compile
45   (autoload 'message-fetch-field "message")
46   (autoload 'gnus-get-buffer-window "gnus-win")
47   (autoload 'rmail-insert-rmail-file-header "rmail")
48   (autoload 'rmail-count-new-messages "rmail")
49   (autoload 'rmail-show-message "rmail")
50   (autoload 'nnheader-narrow-to-headers "nnheader")
51   (autoload 'nnheader-replace-chars-in-string "nnheader"))
52
53 (eval-and-compile
54   (cond
55    ((fboundp 'replace-in-string)
56     (defalias 'gnus-replace-in-string 'replace-in-string))
57    ((fboundp 'replace-regexp-in-string)
58     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
59       (replace-regexp-in-string regexp newtext string nil literal)))))
60
61 ;;; bring in the netrc functions as aliases
62 (defalias 'gnus-netrc-get 'netrc-get)
63 (defalias 'gnus-netrc-machine 'netrc-machine)
64 (defalias 'gnus-parse-netrc 'netrc-parse)
65
66 (defun gnus-boundp (variable)
67   "Return non-nil if VARIABLE is bound and non-nil."
68   (and (boundp variable)
69        (symbol-value variable)))
70
71 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
72   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
73   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
74         (w (make-symbol "w"))
75         (buf (make-symbol "buf")))
76     `(let* ((,tempvar (selected-window))
77             (,buf ,buffer)
78             (,w (gnus-get-buffer-window ,buf 'visible)))
79        (unwind-protect
80            (progn
81              (if ,w
82                  (progn
83                    (select-window ,w)
84                    (set-buffer (window-buffer ,w)))
85                (pop-to-buffer ,buf))
86              ,@forms)
87          (select-window ,tempvar)))))
88
89 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
90 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
91
92 (defmacro gnus-intern-safe (string hashtable)
93   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
94   `(let ((symbol (intern ,string ,hashtable)))
95      (or (boundp symbol)
96          (set symbol nil))
97      symbol))
98
99 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
100 ;; to limit the length of a string.  This function is necessary since
101 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
102 ;; Fixme: Why not `truncate-string-to-width'?
103 (defsubst gnus-limit-string (str width)
104   (if (> (length str) width)
105       (substring str 0 width)
106     str))
107
108 (defsubst gnus-goto-char (point)
109   (and point (goto-char point)))
110
111 (defmacro gnus-buffer-exists-p (buffer)
112   `(let ((buffer ,buffer))
113      (when buffer
114        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
115                 buffer))))
116
117 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
118 ;; XEmacs.  In Emacs we don't need to call `make-local-hook' first.
119 ;; It's harmless, though, so the main purpose of this alias is to shut
120 ;; up the byte compiler.
121 (defalias 'gnus-make-local-hook
122   (if (eq (get 'make-local-hook 'byte-compile)
123           'byte-compile-obsolete)
124       'ignore                           ; Emacs
125     'make-local-hook))                  ; XEmacs
126
127 (defun gnus-delete-first (elt list)
128   "Delete by side effect the first occurrence of ELT as a member of LIST."
129   (if (equal (car list) elt)
130       (cdr list)
131     (let ((total list))
132       (while (and (cdr list)
133                   (not (equal (cadr list) elt)))
134         (setq list (cdr list)))
135       (when (cdr list)
136         (setcdr list (cddr list)))
137       total)))
138
139 ;; Delete the current line (and the next N lines).
140 (defmacro gnus-delete-line (&optional n)
141   `(delete-region (point-at-bol)
142                   (progn (forward-line ,(or n 1)) (point))))
143
144 (defun gnus-byte-code (func)
145   "Return a form that can be `eval'ed based on FUNC."
146   (let ((fval (indirect-function func)))
147     (if (byte-code-function-p fval)
148         (let ((flist (append fval nil)))
149           (setcar flist 'byte-code)
150           flist)
151       (cons 'progn (cddr fval)))))
152
153 (defun gnus-extract-address-components (from)
154   "Extract address components from a From header.
155 Given an RFC-822 address FROM, extract full name and canonical address.
156 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).  Much more simple
157 solution than `mail-extract-address-components', which works much better, but
158 is slower."
159   (let (name address)
160     ;; First find the address - the thing with the @ in it.  This may
161     ;; not be accurate in mail addresses, but does the trick most of
162     ;; the time in news messages.
163     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
164       (setq address (substring from (match-beginning 0) (match-end 0))))
165     ;; Then we check whether the "name <address>" format is used.
166     (and address
167          ;; Linear white space is not required.
168          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
169          (and (setq name (substring from 0 (match-beginning 0)))
170               ;; Strip any quotes from the name.
171               (string-match "^\".*\"$" name)
172               (setq name (substring name 1 (1- (match-end 0))))))
173     ;; If not, then "address (name)" is used.
174     (or name
175         (and (string-match "(.+)" from)
176              (setq name (substring from (1+ (match-beginning 0))
177                                    (1- (match-end 0)))))
178         (and (string-match "()" from)
179              (setq name address))
180         ;; XOVER might not support folded From headers.
181         (and (string-match "(.*" from)
182              (setq name (substring from (1+ (match-beginning 0))
183                                    (match-end 0)))))
184     (list (if (string= name "") nil name) (or address from))))
185
186
187 (defun gnus-fetch-field (field)
188   "Return the value of the header FIELD of current article."
189   (save-excursion
190     (save-restriction
191       (let ((inhibit-point-motion-hooks t))
192         (nnheader-narrow-to-headers)
193         (message-fetch-field field)))))
194
195 (defun gnus-fetch-original-field (field)
196   "Fetch FIELD from the original version of the current article."
197   (with-current-buffer gnus-original-article-buffer
198     (gnus-fetch-field field)))
199
200
201 (defun gnus-goto-colon ()
202   (beginning-of-line)
203   (let ((eol (point-at-eol)))
204     (goto-char (or (text-property-any (point) eol 'gnus-position t)
205                    (search-forward ":" eol t)
206                    (point)))))
207
208 (defun gnus-decode-newsgroups (newsgroups group &optional method)
209   (let ((method (or method (gnus-find-method-for-group group))))
210     (mapconcat (lambda (group)
211                  (gnus-group-name-decode group (gnus-group-name-charset
212                                                 method group)))
213                (message-tokenize-header newsgroups)
214                ",")))
215
216 (defun gnus-remove-text-with-property (prop)
217   "Delete all text in the current buffer with text property PROP."
218   (save-excursion
219     (goto-char (point-min))
220     (while (not (eobp))
221       (while (get-text-property (point) prop)
222         (delete-char 1))
223       (goto-char (next-single-property-change (point) prop nil (point-max))))))
224
225 (defun gnus-newsgroup-directory-form (newsgroup)
226   "Make hierarchical directory name from NEWSGROUP name."
227   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
228          (idx (string-match ":" newsgroup)))
229     (concat
230      (if idx (substring newsgroup 0 idx))
231      (if idx "/")
232      (nnheader-replace-chars-in-string
233       (if idx (substring newsgroup (1+ idx)) newsgroup)
234       ?. ?/))))
235
236 (defun gnus-newsgroup-savable-name (group)
237   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
238   ;; with dots.
239   (nnheader-replace-chars-in-string group ?/ ?.))
240
241 (defun gnus-string> (s1 s2)
242   (not (or (string< s1 s2)
243            (string= s1 s2))))
244
245 ;;; Time functions.
246
247 (defun gnus-file-newer-than (file date)
248   (let ((fdate (nth 5 (file-attributes file))))
249     (or (> (car fdate) (car date))
250         (and (= (car fdate) (car date))
251              (> (nth 1 fdate) (nth 1 date))))))
252
253 ;;; Keymap macros.
254
255 (defmacro gnus-local-set-keys (&rest plist)
256   "Set the keys in PLIST in the current keymap."
257   `(gnus-define-keys-1 (current-local-map) ',plist))
258
259 (defmacro gnus-define-keys (keymap &rest plist)
260   "Define all keys in PLIST in KEYMAP."
261   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
262
263 (defmacro gnus-define-keys-safe (keymap &rest plist)
264   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
265   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
266
267 (put 'gnus-define-keys 'lisp-indent-function 1)
268 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
269 (put 'gnus-local-set-keys 'lisp-indent-function 1)
270
271 (defmacro gnus-define-keymap (keymap &rest plist)
272   "Define all keys in PLIST in KEYMAP."
273   `(gnus-define-keys-1 ,keymap (quote ,plist)))
274
275 (put 'gnus-define-keymap 'lisp-indent-function 1)
276
277 (defun gnus-define-keys-1 (keymap plist &optional safe)
278   (when (null keymap)
279     (error "Can't set keys in a null keymap"))
280   (cond ((symbolp keymap)
281          (setq keymap (symbol-value keymap)))
282         ((keymapp keymap))
283         ((listp keymap)
284          (set (car keymap) nil)
285          (define-prefix-command (car keymap))
286          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
287          (setq keymap (symbol-value (car keymap)))))
288   (let (key)
289     (while plist
290       (when (symbolp (setq key (pop plist)))
291         (setq key (symbol-value key)))
292       (if (or (not safe)
293               (eq (lookup-key keymap key) 'undefined))
294           (define-key keymap key (pop plist))
295         (pop plist)))))
296
297 (defun gnus-completing-read-with-default (default prompt &rest args)
298   ;; Like `completing-read', except that DEFAULT is the default argument.
299   (let* ((prompt (if default
300                      (concat prompt " (default " default ") ")
301                    (concat prompt " ")))
302          (answer (apply 'completing-read prompt args)))
303     (if (or (null answer) (zerop (length answer)))
304         default
305       answer)))
306
307 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
308 ;; the echo area.
309 (defun gnus-y-or-n-p (prompt)
310   (prog1
311       (y-or-n-p prompt)
312     (message "")))
313
314 (defun gnus-yes-or-no-p (prompt)
315   (prog1
316       (yes-or-no-p prompt)
317     (message "")))
318
319 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
320 ;; age-depending date representations. (e.g. just the time if it's
321 ;; from today, the day of the week if it's within the last 7 days and
322 ;; the full date if it's older)
323
324 (defun gnus-seconds-today ()
325   "Return the number of seconds passed today."
326   (let ((now (decode-time (current-time))))
327     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
328
329 (defun gnus-seconds-month ()
330   "Return the number of seconds passed this month."
331   (let ((now (decode-time (current-time))))
332     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
333        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
334
335 (defun gnus-seconds-year ()
336   "Return the number of seconds passed this year."
337   (let ((now (decode-time (current-time)))
338         (days (format-time-string "%j" (current-time))))
339     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
340        (* (- (string-to-number days) 1) 3600 24))))
341
342 (defvar gnus-user-date-format-alist
343   '(((gnus-seconds-today) . "%k:%M")
344     (604800 . "%a %k:%M")                   ;;that's one week
345     ((gnus-seconds-month) . "%a %d")
346     ((gnus-seconds-year) . "%b %d")
347     (t . "%b %d '%y"))                      ;;this one is used when no
348                                             ;;other does match
349   "Specifies date format depending on age of article.
350 This is an alist of items (AGE . FORMAT).  AGE can be a number (of
351 seconds) or a Lisp expression evaluating to a number.  When the age of
352 the article is less than this number, then use `format-time-string'
353 with the corresponding FORMAT for displaying the date of the article.
354 If AGE is not a number or a Lisp expression evaluating to a
355 non-number, then the corresponding FORMAT is used as a default value.
356
357 Note that the list is processed from the beginning, so it should be
358 sorted by ascending AGE.  Also note that items following the first
359 non-number AGE will be ignored.
360
361 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
362 and `gnus-seconds-year' in the AGE spec.  They return the number of
363 seconds passed since the start of today, of this month, of this year,
364 respectively.")
365
366 (defun gnus-user-date (messy-date)
367   "Format the messy-date according to gnus-user-date-format-alist.
368 Returns \"  ?  \" if there's bad input or if an other error occurs.
369 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
370   (condition-case ()
371       (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
372              (now (time-to-seconds (current-time)))
373              ;;If we don't find something suitable we'll use this one
374              (my-format "%b %d '%y"))
375         (let* ((difference (- now messy-date))
376                (templist gnus-user-date-format-alist)
377                (top (eval (caar templist))))
378           (while (if (numberp top) (< top difference) (not top))
379             (progn
380               (setq templist (cdr templist))
381               (setq top (eval (caar templist)))))
382           (if (stringp (cdr (car templist)))
383               (setq my-format (cdr (car templist)))))
384         (format-time-string (eval my-format) (seconds-to-time messy-date)))
385     (error "  ?   ")))
386
387 (defun gnus-dd-mmm (messy-date)
388   "Return a string like DD-MMM from a big messy string."
389   (condition-case ()
390       (format-time-string "%d-%b" (safe-date-to-time messy-date))
391     (error "  -   ")))
392
393 (defmacro gnus-date-get-time (date)
394   "Convert DATE string to Emacs time.
395 Cache the result as a text property stored in DATE."
396   ;; Either return the cached value...
397   `(let ((d ,date))
398      (if (equal "" d)
399          '(0 0)
400        (or (get-text-property 0 'gnus-time d)
401            ;; or compute the value...
402            (let ((time (safe-date-to-time d)))
403              ;; and store it back in the string.
404              (put-text-property 0 1 'gnus-time time d)
405              time)))))
406
407 (defsubst gnus-time-iso8601 (time)
408   "Return a string of TIME in YYYYMMDDTHHMMSS format."
409   (format-time-string "%Y%m%dT%H%M%S" time))
410
411 (defun gnus-date-iso8601 (date)
412   "Convert the DATE to YYYYMMDDTHHMMSS."
413   (condition-case ()
414       (gnus-time-iso8601 (gnus-date-get-time date))
415     (error "")))
416
417 (defun gnus-mode-string-quote (string)
418   "Quote all \"%\"'s in STRING."
419   (gnus-replace-in-string string "%" "%%"))
420
421 ;; Make a hash table (default and minimum size is 256).
422 ;; Optional argument HASHSIZE specifies the table size.
423 (defun gnus-make-hashtable (&optional hashsize)
424   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
425
426 ;; Make a number that is suitable for hashing; bigger than MIN and
427 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
428 ;; hardware modulo operation, so they implement it in software.  On
429 ;; many sparcs over 50% of the time to intern is spent in the modulo.
430 ;; Yes, it's slower than actually computing the hash from the string!
431 ;; So we use powers of 2 so people can optimize the modulo to a mask.
432 (defun gnus-create-hash-size (min)
433   (let ((i 1))
434     (while (< i min)
435       (setq i (* 2 i)))
436     i))
437
438 (defcustom gnus-verbose 7
439   "*Integer that says how verbose Gnus should be.
440 The higher the number, the more messages Gnus will flash to say what
441 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
442 display most important messages; and at ten, Gnus will keep on
443 jabbering all the time."
444   :group 'gnus-start
445   :type 'integer)
446
447 (defun gnus-message (level &rest args)
448   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
449
450 Guideline for numbers:
451 1 - error messages, 3 - non-serious error messages, 5 - messages for things
452 that take a long time, 7 - not very important messages on stuff, 9 - messages
453 inside loops."
454   (if (<= level gnus-verbose)
455       (apply 'message args)
456     ;; We have to do this format thingy here even if the result isn't
457     ;; shown - the return value has to be the same as the return value
458     ;; from `message'.
459     (apply 'format args)))
460
461 (defun gnus-error (level &rest args)
462   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
463   (when (<= (floor level) gnus-verbose)
464     (apply 'message args)
465     (ding)
466     (let (duration)
467       (when (and (floatp level)
468                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
469         (sit-for duration))))
470   nil)
471
472 (defun gnus-split-references (references)
473   "Return a list of Message-IDs in REFERENCES."
474   (let ((beg 0)
475         ids)
476     (while (string-match "<[^<]+[^< \t]" references beg)
477       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
478             ids))
479     (nreverse ids)))
480
481 (defsubst gnus-parent-id (references &optional n)
482   "Return the last Message-ID in REFERENCES.
483 If N, return the Nth ancestor instead."
484   (when (and references
485              (not (zerop (length references))))
486     (if n
487         (let ((ids (inline (gnus-split-references references))))
488           (while (nthcdr n ids)
489             (setq ids (cdr ids)))
490           (car ids))
491       (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
492         (match-string 1 references)))))
493
494 (defun gnus-buffer-live-p (buffer)
495   "Say whether BUFFER is alive or not."
496   (and buffer
497        (get-buffer buffer)
498        (buffer-name (get-buffer buffer))))
499
500 (defun gnus-horizontal-recenter ()
501   "Recenter the current buffer horizontally."
502   (if (< (current-column) (/ (window-width) 2))
503       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
504     (let* ((orig (point))
505            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
506            (max 0))
507       (when end
508         ;; Find the longest line currently displayed in the window.
509         (goto-char (window-start))
510         (while (and (not (eobp))
511                     (< (point) end))
512           (end-of-line)
513           (setq max (max max (current-column)))
514           (forward-line 1))
515         (goto-char orig)
516         ;; Scroll horizontally to center (sort of) the point.
517         (if (> max (window-width))
518             (set-window-hscroll
519              (gnus-get-buffer-window (current-buffer) t)
520              (min (- (current-column) (/ (window-width) 3))
521                   (+ 2 (- max (window-width)))))
522           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
523         max))))
524
525 (defun gnus-read-event-char (&optional prompt)
526   "Get the next event."
527   (let ((event (read-event prompt)))
528     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
529     (cons (and (numberp event) event) event)))
530
531 (defun gnus-sortable-date (date)
532   "Make string suitable for sorting from DATE."
533   (gnus-time-iso8601 (date-to-time date)))
534
535 (defun gnus-copy-file (file &optional to)
536   "Copy FILE to TO."
537   (interactive
538    (list (read-file-name "Copy file: " default-directory)
539          (read-file-name "Copy file to: " default-directory)))
540   (unless to
541     (setq to (read-file-name "Copy file to: " default-directory)))
542   (when (file-directory-p to)
543     (setq to (concat (file-name-as-directory to)
544                      (file-name-nondirectory file))))
545   (copy-file file to))
546
547 (defvar gnus-work-buffer " *gnus work*")
548
549 (defun gnus-set-work-buffer ()
550   "Put point in the empty Gnus work buffer."
551   (if (get-buffer gnus-work-buffer)
552       (progn
553         (set-buffer gnus-work-buffer)
554         (erase-buffer))
555     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
556     (kill-all-local-variables)
557     (mm-enable-multibyte)))
558
559 (defmacro gnus-group-real-name (group)
560   "Find the real name of a foreign newsgroup."
561   `(let ((gname ,group))
562      (if (string-match "^[^:]+:" gname)
563          (substring gname (match-end 0))
564        gname)))
565
566 (defun gnus-make-sort-function (funs)
567   "Return a composite sort condition based on the functions in FUNS."
568   (cond
569    ;; Just a simple function.
570    ((functionp funs) funs)
571    ;; No functions at all.
572    ((null funs) funs)
573    ;; A list of functions.
574    ((or (cdr funs)
575         (listp (car funs)))
576     (gnus-byte-compile
577      `(lambda (t1 t2)
578         ,(gnus-make-sort-function-1 (reverse funs)))))
579    ;; A list containing just one function.
580    (t
581     (car funs))))
582
583 (defun gnus-make-sort-function-1 (funs)
584   "Return a composite sort condition based on the functions in FUNS."
585   (let ((function (car funs))
586         (first 't1)
587         (last 't2))
588     (when (consp function)
589       (cond
590        ;; Reversed spec.
591        ((eq (car function) 'not)
592         (setq function (cadr function)
593               first 't2
594               last 't1))
595        ((functionp function)
596         ;; Do nothing.
597         )
598        (t
599         (error "Invalid sort spec: %s" function))))
600     (if (cdr funs)
601         `(or (,function ,first ,last)
602              (and (not (,function ,last ,first))
603                   ,(gnus-make-sort-function-1 (cdr funs))))
604       `(,function ,first ,last))))
605
606 (defun gnus-turn-off-edit-menu (type)
607   "Turn off edit menu in `gnus-TYPE-mode-map'."
608   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
609     [menu-bar edit] 'undefined))
610
611 (defun gnus-prin1 (form)
612   "Use `prin1' on FORM in the current buffer.
613 Bind `print-quoted' and `print-readably' to t while printing."
614   (let ((print-quoted t)
615         (print-readably t)
616         (print-escape-multibyte nil)
617         print-level print-length)
618     (prin1 form (current-buffer))))
619
620 (defun gnus-prin1-to-string (form)
621   "The same as `prin1'.
622 Bind `print-quoted' and `print-readably' to t, and `print-length'
623 and `print-level' to nil."
624   (let ((print-quoted t)
625         (print-readably t)
626         (print-length nil)
627         (print-level nil))
628     (prin1-to-string form)))
629
630 (defun gnus-make-directory (directory)
631   "Make DIRECTORY (and all its parents) if it doesn't exist."
632   (require 'nnmail)
633   (let ((file-name-coding-system nnmail-pathname-coding-system))
634     (when (and directory
635                (not (file-exists-p directory)))
636       (make-directory directory t)))
637   t)
638
639 (defun gnus-write-buffer (file)
640   "Write the current buffer's contents to FILE."
641   ;; Make sure the directory exists.
642   (gnus-make-directory (file-name-directory file))
643   (let ((file-name-coding-system nnmail-pathname-coding-system))
644     ;; Write the buffer.
645     (write-region (point-min) (point-max) file nil 'quietly)))
646
647 (defun gnus-delete-file (file)
648   "Delete FILE if it exists."
649   (when (file-exists-p file)
650     (delete-file file)))
651
652 (defun gnus-strip-whitespace (string)
653   "Return STRING stripped of all whitespace."
654   (while (string-match "[\r\n\t ]+" string)
655     (setq string (replace-match "" t t string)))
656   string)
657
658 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
659   "The same as `put-text-property', but don't put this prop on any newlines in the region."
660   (save-match-data
661     (save-excursion
662       (save-restriction
663         (goto-char beg)
664         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
665           (gnus-put-text-property beg (match-beginning 0) prop val)
666           (setq beg (point)))
667         (gnus-put-text-property beg (point) prop val)))))
668
669 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
670   "The same as `put-text-property', but don't put this prop on any newlines in the region."
671   (save-match-data
672     (save-excursion
673       (save-restriction
674         (goto-char beg)
675         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
676           (gnus-overlay-put
677            (gnus-make-overlay beg (match-beginning 0))
678            prop val)
679           (setq beg (point)))
680         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
681
682 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
683                                                                    prop val)
684   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
685   (let ((b beg))
686     (while (/= b end)
687       (when (get-text-property b 'gnus-face)
688         (setq b (next-single-property-change b 'gnus-face nil end)))
689       (when (/= b end)
690         (inline
691           (gnus-put-text-property
692            b (setq b (next-single-property-change b 'gnus-face nil end))
693            prop val))))))
694
695 (defmacro gnus-faces-at (position)
696   "Return a list of faces at POSITION."
697   (if (featurep 'xemacs)
698       `(let ((pos ,position))
699          (mapcar-extents 'extent-face
700                          nil (current-buffer) pos pos nil 'face))
701     `(let ((pos ,position))
702        (delq nil (cons (get-text-property pos 'face)
703                        (mapcar
704                         (lambda (overlay)
705                           (overlay-get overlay 'face))
706                         (overlays-at pos)))))))
707
708 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
709 ;;; The primary idea here is to try to protect internal datastructures
710 ;;; from becoming corrupted when the user hits C-g, or if a hook or
711 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
712 ;;; updated at the same time, or information can be lost.
713
714 (defvar gnus-atomic-be-safe t
715   "If t, certain operations will be protected from interruption by C-g.")
716
717 (defmacro gnus-atomic-progn (&rest forms)
718   "Evaluate FORMS atomically, which means to protect the evaluation
719 from being interrupted by the user.  An error from the forms themselves
720 will return without finishing the operation.  Since interrupts from
721 the user are disabled, it is recommended that only the most minimal
722 operations are performed by FORMS.  If you wish to assign many
723 complicated values atomically, compute the results into temporary
724 variables and then do only the assignment atomically."
725   `(let ((inhibit-quit gnus-atomic-be-safe))
726      ,@forms))
727
728 (put 'gnus-atomic-progn 'lisp-indent-function 0)
729
730 (defmacro gnus-atomic-progn-assign (protect &rest forms)
731   "Evaluate FORMS, but insure that the variables listed in PROTECT
732 are not changed if anything in FORMS signals an error or otherwise
733 non-locally exits.  The variables listed in PROTECT are updated atomically.
734 It is safe to use gnus-atomic-progn-assign with long computations.
735
736 Note that if any of the symbols in PROTECT were unbound, they will be
737 set to nil on a successful assignment.  In case of an error or other
738 non-local exit, it will still be unbound."
739   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
740                                                   (concat (symbol-name x)
741                                                           "-tmp"))
742                                                  x))
743                                protect))
744          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
745                                temp-sym-map))
746          (temp-sym-let (mapcar (lambda (x) (list (car x)
747                                                  `(and (boundp ',(cadr x))
748                                                        ,(cadr x))))
749                                temp-sym-map))
750          (sym-temp-let sym-temp-map)
751          (temp-sym-assign (apply 'append temp-sym-map))
752          (sym-temp-assign (apply 'append sym-temp-map))
753          (result (make-symbol "result-tmp")))
754     `(let (,@temp-sym-let
755            ,result)
756        (let ,sym-temp-let
757          (setq ,result (progn ,@forms))
758          (setq ,@temp-sym-assign))
759        (let ((inhibit-quit gnus-atomic-be-safe))
760          (setq ,@sym-temp-assign))
761        ,result)))
762
763 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
764 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
765
766 (defmacro gnus-atomic-setq (&rest pairs)
767   "Similar to setq, except that the real symbols are only assigned when
768 there are no errors.  And when the real symbols are assigned, they are
769 done so atomically.  If other variables might be changed via side-effect,
770 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
771 with potentially long computations."
772   (let ((tpairs pairs)
773         syms)
774     (while tpairs
775       (push (car tpairs) syms)
776       (setq tpairs (cddr tpairs)))
777     `(gnus-atomic-progn-assign ,syms
778        (setq ,@pairs))))
779
780 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
781
782
783 ;;; Functions for saving to babyl/mail files.
784
785 (eval-when-compile
786   (condition-case nil
787       (progn
788         (require 'rmail)
789         (autoload 'rmail-update-summary "rmailsum"))
790     (error
791      (define-compiler-macro rmail-select-summary (&rest body)
792        ;; Rmail of the XEmacs version is supplied by the package, and
793        ;; requires tm and apel packages.  However, there may be those
794        ;; who haven't installed those packages.  This macro helps such
795        ;; people even if they install those packages later.
796        `(eval '(rmail-select-summary ,@body)))
797      ;; If there's rmail but there's no tm (or there's apel of the
798      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
799      ;; version fails halfway, however it provides the rmail-select-summary
800      ;; macro which uses the following functions:
801      (autoload 'rmail-summary-displayed "rmail")
802      (autoload 'rmail-maybe-display-summary "rmail")))
803   (defvar rmail-default-rmail-file)
804   (defvar mm-text-coding-system))
805
806 (defun gnus-output-to-rmail (filename &optional ask)
807   "Append the current article to an Rmail file named FILENAME."
808   (require 'rmail)
809   (require 'mm-util)
810   ;; Most of these codes are borrowed from rmailout.el.
811   (setq filename (expand-file-name filename))
812   (setq rmail-default-rmail-file filename)
813   (let ((artbuf (current-buffer))
814         (tmpbuf (get-buffer-create " *Gnus-output*")))
815     (save-excursion
816       (or (get-file-buffer filename)
817           (file-exists-p filename)
818           (if (or (not ask)
819                   (gnus-yes-or-no-p
820                    (concat "\"" filename "\" does not exist, create it? ")))
821               (let ((file-buffer (create-file-buffer filename)))
822                 (save-excursion
823                   (set-buffer file-buffer)
824                   (rmail-insert-rmail-file-header)
825                   (let ((require-final-newline nil)
826                         (coding-system-for-write mm-text-coding-system))
827                     (gnus-write-buffer filename)))
828                 (kill-buffer file-buffer))
829             (error "Output file does not exist")))
830       (set-buffer tmpbuf)
831       (erase-buffer)
832       (insert-buffer-substring artbuf)
833       (gnus-convert-article-to-rmail)
834       ;; Decide whether to append to a file or to an Emacs buffer.
835       (let ((outbuf (get-file-buffer filename)))
836         (if (not outbuf)
837             (let ((file-name-coding-system nnmail-pathname-coding-system))
838               (mm-append-to-file (point-min) (point-max) filename))
839           ;; File has been visited, in buffer OUTBUF.
840           (set-buffer outbuf)
841           (let ((buffer-read-only nil)
842                 (msg (and (boundp 'rmail-current-message)
843                           (symbol-value 'rmail-current-message))))
844             ;; If MSG is non-nil, buffer is in RMAIL mode.
845             (when msg
846               (widen)
847               (narrow-to-region (point-max) (point-max)))
848             (insert-buffer-substring tmpbuf)
849             (when msg
850               (goto-char (point-min))
851               (widen)
852               (search-backward "\n\^_")
853               (narrow-to-region (point) (point-max))
854               (rmail-count-new-messages t)
855               (when (rmail-summary-exists)
856                 (rmail-select-summary
857                  (rmail-update-summary)))
858               (rmail-count-new-messages t)
859               (rmail-show-message msg))
860             (save-buffer)))))
861     (kill-buffer tmpbuf)))
862
863 (defun gnus-output-to-mail (filename &optional ask)
864   "Append the current article to a mail file named FILENAME."
865   (setq filename (expand-file-name filename))
866   (let ((artbuf (current-buffer))
867         (tmpbuf (get-buffer-create " *Gnus-output*")))
868     (save-excursion
869       ;; Create the file, if it doesn't exist.
870       (when (and (not (get-file-buffer filename))
871                  (not (file-exists-p filename)))
872         (if (or (not ask)
873                 (gnus-y-or-n-p
874                  (concat "\"" filename "\" does not exist, create it? ")))
875             (let ((file-buffer (create-file-buffer filename)))
876               (save-excursion
877                 (set-buffer file-buffer)
878                 (let ((require-final-newline nil)
879                       (coding-system-for-write mm-text-coding-system))
880                   (gnus-write-buffer filename)))
881               (kill-buffer file-buffer))
882           (error "Output file does not exist")))
883       (set-buffer tmpbuf)
884       (erase-buffer)
885       (insert-buffer-substring artbuf)
886       (goto-char (point-min))
887       (if (looking-at "From ")
888           (forward-line 1)
889         (insert "From nobody " (current-time-string) "\n"))
890       (let (case-fold-search)
891         (while (re-search-forward "^From " nil t)
892           (beginning-of-line)
893           (insert ">")))
894       ;; Decide whether to append to a file or to an Emacs buffer.
895       (let ((outbuf (get-file-buffer filename)))
896         (if (not outbuf)
897             (let ((buffer-read-only nil))
898               (save-excursion
899                 (goto-char (point-max))
900                 (forward-char -2)
901                 (unless (looking-at "\n\n")
902                   (goto-char (point-max))
903                   (unless (bolp)
904                     (insert "\n"))
905                   (insert "\n"))
906                 (goto-char (point-max))
907                 (let ((file-name-coding-system nnmail-pathname-coding-system))
908                   (mm-append-to-file (point-min) (point-max) filename))))
909           ;; File has been visited, in buffer OUTBUF.
910           (set-buffer outbuf)
911           (let ((buffer-read-only nil))
912             (goto-char (point-max))
913             (unless (eobp)
914               (insert "\n"))
915             (insert "\n")
916             (insert-buffer-substring tmpbuf)))))
917     (kill-buffer tmpbuf)))
918
919 (defun gnus-convert-article-to-rmail ()
920   "Convert article in current buffer to Rmail message format."
921   (let ((buffer-read-only nil))
922     ;; Convert article directly into Babyl format.
923     (goto-char (point-min))
924     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
925     (while (search-forward "\n\^_" nil t) ;single char
926       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
927     (goto-char (point-max))
928     (insert "\^_")))
929
930 (defun gnus-map-function (funs arg)
931   "Apply the result of the first function in FUNS to the second, and so on.
932 ARG is passed to the first function."
933   (while funs
934     (setq arg (funcall (pop funs) arg)))
935   arg)
936
937 (defun gnus-run-hooks (&rest funcs)
938   "Does the same as `run-hooks', but saves the current buffer."
939   (save-current-buffer
940     (apply 'run-hooks funcs)))
941
942 ;;; Various
943
944 (defvar gnus-group-buffer)              ; Compiler directive
945 (defun gnus-alive-p ()
946   "Say whether Gnus is running or not."
947   (and (boundp 'gnus-group-buffer)
948        (get-buffer gnus-group-buffer)
949        (save-excursion
950          (set-buffer gnus-group-buffer)
951          (eq major-mode 'gnus-group-mode))))
952
953 (defun gnus-remove-duplicates (list)
954   (let (new)
955     (while list
956       (or (member (car list) new)
957           (setq new (cons (car list) new)))
958       (setq list (cdr list)))
959     (nreverse new)))
960
961 (defun gnus-remove-if (predicate list)
962   "Return a copy of LIST with all items satisfying PREDICATE removed."
963   (let (out)
964     (while list
965       (unless (funcall predicate (car list))
966         (push (car list) out))
967       (setq list (cdr list)))
968     (nreverse out)))
969
970 (if (fboundp 'assq-delete-all)
971     (defalias 'gnus-delete-alist 'assq-delete-all)
972   (defun gnus-delete-alist (key alist)
973     "Delete from ALIST all elements whose car is KEY.
974 Return the modified alist."
975     (let (entry)
976       (while (setq entry (assq key alist))
977         (setq alist (delq entry alist)))
978       alist)))
979
980 (defmacro gnus-pull (key alist &optional assoc-p)
981   "Modify ALIST to be without KEY."
982   (unless (symbolp alist)
983     (error "Not a symbol: %s" alist))
984   (let ((fun (if assoc-p 'assoc 'assq)))
985     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
986
987 (defun gnus-globalify-regexp (re)
988   "Return a regexp that matches a whole line, iff RE matches a part of it."
989   (concat (unless (string-match "^\\^" re) "^.*")
990           re
991           (unless (string-match "\\$$" re) ".*$")))
992
993 (defun gnus-set-window-start (&optional point)
994   "Set the window start to POINT, or (point) if nil."
995   (let ((win (gnus-get-buffer-window (current-buffer) t)))
996     (when win
997       (set-window-start win (or point (point))))))
998
999 (defun gnus-annotation-in-region-p (b e)
1000   (if (= b e)
1001       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1002     (text-property-any b e 'gnus-undeletable t)))
1003
1004 (defun gnus-or (&rest elems)
1005   "Return non-nil if any of the elements are non-nil."
1006   (catch 'found
1007     (while elems
1008       (when (pop elems)
1009         (throw 'found t)))))
1010
1011 (defun gnus-and (&rest elems)
1012   "Return non-nil if all of the elements are non-nil."
1013   (catch 'found
1014     (while elems
1015       (unless (pop elems)
1016         (throw 'found nil)))
1017     t))
1018
1019 (defun gnus-write-active-file (file hashtb &optional full-names)
1020   (let ((coding-system-for-write nnmail-active-file-coding-system))
1021     (with-temp-file file
1022       (mapatoms
1023        (lambda (sym)
1024          (when (and sym
1025                     (boundp sym)
1026                     (symbol-value sym))
1027            (insert (format "%S %d %d y\n"
1028                            (if full-names
1029                                sym
1030                              (intern (gnus-group-real-name (symbol-name sym))))
1031                            (or (cdr (symbol-value sym))
1032                                (car (symbol-value sym)))
1033                            (car (symbol-value sym))))))
1034        hashtb)
1035       (goto-char (point-max))
1036       (while (search-backward "\\." nil t)
1037         (delete-char 1)))))
1038
1039 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1040 (defmacro gnus-with-output-to-file (file &rest body)
1041   (let ((buffer (make-symbol "output-buffer"))
1042         (size (make-symbol "output-buffer-size"))
1043         (leng (make-symbol "output-buffer-length"))
1044         (append (make-symbol "output-buffer-append")))
1045     `(let* ((,size 131072)
1046             (,buffer (make-string ,size 0))
1047             (,leng 0)
1048             (,append nil)
1049             (standard-output
1050              (lambda (c)
1051                (aset ,buffer ,leng c)
1052                    
1053                (if (= ,size (setq ,leng (1+ ,leng)))
1054                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1055                           (setq ,leng 0
1056                                 ,append t))))))
1057        ,@body
1058        (when (> ,leng 0)
1059          (let ((coding-system-for-write 'no-conversion))
1060          (write-region (substring ,buffer 0 ,leng) nil ,file
1061                        ,append 'no-msg))))))
1062
1063 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1064 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1065
1066 (if (fboundp 'union)
1067     (defalias 'gnus-union 'union)
1068   (defun gnus-union (l1 l2)
1069     "Set union of lists L1 and L2."
1070     (cond ((null l1) l2)
1071           ((null l2) l1)
1072           ((equal l1 l2) l1)
1073           (t
1074            (or (>= (length l1) (length l2))
1075                (setq l1 (prog1 l2 (setq l2 l1))))
1076            (while l2
1077              (or (member (car l2) l1)
1078                  (push (car l2) l1))
1079              (pop l2))
1080            l1))))
1081
1082 (defun gnus-add-text-properties-when
1083   (property value start end properties &optional object)
1084   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1085   (let (point)
1086     (while (and start
1087                 (< start end) ;; XEmacs will loop for every when start=end.
1088                 (setq point (text-property-not-all start end property value)))
1089       (gnus-add-text-properties start point properties object)
1090       (setq start (text-property-any point end property value)))
1091     (if start
1092         (gnus-add-text-properties start end properties object))))
1093
1094 (defun gnus-remove-text-properties-when
1095   (property value start end properties &optional object)
1096   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1097   (let (point)
1098     (while (and start
1099                 (< start end)
1100                 (setq point (text-property-not-all start end property value)))
1101       (remove-text-properties start point properties object)
1102       (setq start (text-property-any point end property value)))
1103     (if start
1104         (remove-text-properties start end properties object))
1105     t))
1106
1107 ;; This might use `compare-strings' to reduce consing in the
1108 ;; case-insensitive case, but it has to cope with null args.
1109 ;; (`string-equal' uses symbol print names.)
1110 (defun gnus-string-equal (x y)
1111   "Like `string-equal', except it compares case-insensitively."
1112   (and (= (length x) (length y))
1113        (or (string-equal x y)
1114            (string-equal (downcase x) (downcase y)))))
1115
1116 (defcustom gnus-use-byte-compile t
1117   "If non-nil, byte-compile crucial run-time code.
1118 Setting it to nil has no effect after the first time `gnus-byte-compile'
1119 is run."
1120   :type 'boolean
1121   :version "21.1"
1122   :group 'gnus-various)
1123
1124 (defun gnus-byte-compile (form)
1125   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1126   (if gnus-use-byte-compile
1127       (progn
1128         (condition-case nil
1129             ;; Work around a bug in XEmacs 21.4
1130             (require 'byte-optimize)
1131           (error))
1132         (require 'bytecomp)
1133         (defalias 'gnus-byte-compile
1134           (lambda (form)
1135             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1136               (byte-compile form))))
1137         (gnus-byte-compile form))
1138     form))
1139
1140 (defun gnus-remassoc (key alist)
1141   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1142 The modified LIST is returned.  If the first member
1143 of LIST has a car that is `equal' to KEY, there is no way to remove it
1144 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1145 sure of changing the value of `foo'."
1146   (when alist
1147     (if (equal key (caar alist))
1148         (cdr alist)
1149       (setcdr alist (gnus-remassoc key (cdr alist)))
1150       alist)))
1151
1152 (defun gnus-update-alist-soft (key value alist)
1153   (if value
1154       (cons (cons key value) (gnus-remassoc key alist))
1155     (gnus-remassoc key alist)))
1156
1157 (defun gnus-create-info-command (node)
1158   "Create a command that will go to info NODE."
1159   `(lambda ()
1160      (interactive)
1161      ,(concat "Enter the info system at node " node)
1162      (Info-goto-node ,node)
1163      (setq gnus-info-buffer (current-buffer))
1164      (gnus-configure-windows 'info)))
1165
1166 (defun gnus-not-ignore (&rest args)
1167   t)
1168
1169 (defvar gnus-directory-sep-char-regexp "/"
1170   "The regexp of directory separator character.
1171 If you find some problem with the directory separator character, try
1172 \"[/\\\\\]\" for some systems.")
1173
1174 (defun gnus-url-unhex (x)
1175   (if (> x ?9)
1176       (if (>= x ?a)
1177           (+ 10 (- x ?a))
1178         (+ 10 (- x ?A)))
1179     (- x ?0)))
1180
1181 ;; Fixme: Do it like QP.
1182 (defun gnus-url-unhex-string (str &optional allow-newlines)
1183   "Remove %XX, embedded spaces, etc in a url.
1184 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1185 decoding of carriage returns and line feeds in the string, which is normally
1186 forbidden in URL encoding."
1187   (let ((tmp "")
1188         (case-fold-search t))
1189     (while (string-match "%[0-9a-f][0-9a-f]" str)
1190       (let* ((start (match-beginning 0))
1191              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1192              (code (+ (* 16 ch1)
1193                       (gnus-url-unhex (elt str (+ start 2))))))
1194         (setq tmp (concat
1195                    tmp (substring str 0 start)
1196                    (cond
1197                     (allow-newlines
1198                      (char-to-string code))
1199                     ((or (= code ?\n) (= code ?\r))
1200                      " ")
1201                     (t (char-to-string code))))
1202               str (substring str (match-end 0)))))
1203     (setq tmp (concat tmp str))
1204     tmp))
1205
1206 (defun gnus-make-predicate (spec)
1207   "Transform SPEC into a function that can be called.
1208 SPEC is a predicate specifier that contains stuff like `or', `and',
1209 `not', lists and functions.  The functions all take one parameter."
1210   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1211
1212 (defun gnus-make-predicate-1 (spec)
1213   (cond
1214    ((symbolp spec)
1215     `(,spec elem))
1216    ((listp spec)
1217     (if (memq (car spec) '(or and not))
1218         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1219       (error "Invalid predicate specifier: %s" spec)))))
1220
1221 (defun gnus-completing-read (prompt table &optional predicate require-match
1222                                     history)
1223   (when (and history
1224              (not (boundp history)))
1225     (set history nil))
1226   (completing-read
1227    (if (symbol-value history)
1228        (concat prompt " (" (car (symbol-value history)) "): ")
1229      (concat prompt ": "))
1230    table
1231    predicate
1232    require-match
1233    nil
1234    history
1235    (car (symbol-value history))))
1236
1237 (defun gnus-graphic-display-p ()
1238   (or (and (fboundp 'display-graphic-p)
1239            (display-graphic-p))
1240       ;;;!!!This is bogus.  Fixme!
1241       (and (featurep 'xemacs)
1242            t)))
1243
1244 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1245 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1246
1247 (defmacro gnus-parse-without-error (&rest body)
1248   "Allow continuing onto the next line even if an error occurs."
1249   `(while (not (eobp))
1250      (condition-case ()
1251          (progn
1252            ,@body
1253            (goto-char (point-max)))
1254        (error
1255         (gnus-error 4 "Invalid data on line %d"
1256                     (count-lines (point-min) (point)))
1257         (forward-line 1)))))
1258
1259 (defun gnus-cache-file-contents (file variable function)
1260   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1261   (let ((time (nth 5 (file-attributes file)))
1262         contents value)
1263     (if (or (null (setq value (symbol-value variable)))
1264             (not (equal (car value) file))
1265             (not (equal (nth 1 value) time)))
1266         (progn
1267           (setq contents (funcall function file))
1268           (set variable (list file time contents))
1269           contents)
1270       (nth 2 value))))
1271
1272 (defun gnus-multiple-choice (prompt choice &optional idx)
1273   "Ask user a multiple choice question.
1274 CHOICE is a list of the choice char and help message at IDX."
1275   (let (tchar buf)
1276     (save-window-excursion
1277       (save-excursion
1278         (while (not tchar)
1279           (message "%s (%s): "
1280                    prompt
1281                    (concat
1282                     (mapconcat (lambda (s) (char-to-string (car s)))
1283                                choice ", ") ", ?"))
1284           (setq tchar (read-char))
1285           (when (not (assq tchar choice))
1286             (setq tchar nil)
1287             (setq buf (get-buffer-create "*Gnus Help*"))
1288             (pop-to-buffer buf)
1289             (fundamental-mode)          ; for Emacs 20.4+
1290             (buffer-disable-undo)
1291             (erase-buffer)
1292             (insert prompt ":\n\n")
1293             (let ((max -1)
1294                   (list choice)
1295                   (alist choice)
1296                   (idx (or idx 1))
1297                   (i 0)
1298                   n width pad format)
1299               ;; find the longest string to display
1300               (while list
1301                 (setq n (length (nth idx (car list))))
1302                 (unless (> max n)
1303                   (setq max n))
1304                 (setq list (cdr list)))
1305               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1306               (setq n (/ (1- (window-width)) max)) ; items per line
1307               (setq width (/ (1- (window-width)) n)) ; width of each item
1308               ;; insert `n' items, each in a field of width `width'
1309               (while alist
1310                 (if (< i n)
1311                     ()
1312                   (setq i 0)
1313                   (delete-char -1)              ; the `\n' takes a char
1314                   (insert "\n"))
1315                 (setq pad (- width 3))
1316                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1317                 (insert (format format (caar alist) (nth idx (car alist))))
1318                 (setq alist (cdr alist))
1319                 (setq i (1+ i))))))))
1320     (if (buffer-live-p buf)
1321         (kill-buffer buf))
1322     tchar))
1323
1324 (defun gnus-select-frame-set-input-focus (frame)
1325   "Select FRAME, raise it, and set input focus, if possible."
1326   (cond ((featurep 'xemacs)
1327          (raise-frame frame)
1328          (select-frame frame)
1329          (focus-frame frame))
1330         ;; The function `select-frame-set-input-focus' won't set
1331         ;; the input focus under Emacs 21.2 and X window system.
1332         ;;((fboundp 'select-frame-set-input-focus)
1333         ;; (defalias 'gnus-select-frame-set-input-focus
1334         ;;   'select-frame-set-input-focus)
1335         ;; (select-frame-set-input-focus frame))
1336         (t
1337          (raise-frame frame)
1338          (select-frame frame)
1339          (cond ((and (eq window-system 'x)
1340                      (fboundp 'x-focus-frame))
1341                 (x-focus-frame frame))
1342                ((eq window-system 'w32)
1343                 (w32-focus-frame frame)))
1344          (when focus-follows-mouse
1345            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1346
1347 (defun gnus-frame-or-window-display-name (object)
1348   "Given a frame or window, return the associated display name.
1349 Return nil otherwise."
1350   (if (featurep 'xemacs)
1351       (device-connection (dfw-device object))
1352     (if (or (framep object)
1353             (and (windowp object)
1354                  (setq object (window-frame object))))
1355         (let ((display (frame-parameter object 'display)))
1356           (if (and (stringp display)
1357                    ;; Exclude invalid display names.
1358                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1359                                  display))
1360               display)))))
1361
1362 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1363 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1364   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1365 If there are several sequences, FUNCTION is called with that many arguments,
1366 and mapping stops as soon as the shortest sequence runs out.  With just one
1367 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1368 `mapcar' function extended to arbitrary sequence types."
1369
1370   (if seqs2_n
1371       (let* ((seqs (cons seq1 seqs2_n))
1372              (cnt 0)
1373              (heads (mapcar (lambda (seq)
1374                               (make-symbol (concat "head"
1375                                                    (int-to-string
1376                                                     (setq cnt (1+ cnt))))))
1377                             seqs))
1378              (result (make-symbol "result"))
1379              (result-tail (make-symbol "result-tail")))
1380         `(let* ,(let* ((bindings (cons nil nil))
1381                        (heads heads))
1382                   (nconc bindings (list (list result '(cons nil nil))))
1383                   (nconc bindings (list (list result-tail result)))
1384                   (while heads
1385                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1386                   (cdr bindings))
1387            (while (and ,@heads)
1388              (setcdr ,result-tail (cons (funcall ,function
1389                                                  ,@(mapcar (lambda (h) (list 'car h))
1390                                                            heads))
1391                                         nil))
1392              (setq ,result-tail (cdr ,result-tail)
1393                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1394            (cdr ,result)))
1395     `(mapcar ,function ,seq1)))
1396
1397 (if (fboundp 'merge)
1398     (defalias 'gnus-merge 'merge)
1399   ;; Adapted from cl-seq.el
1400   (defun gnus-merge (type list1 list2 pred)
1401     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1402 Argument TYPE is for compatibility and ignored.
1403 Ordering of the elements is preserved according to PRED, a `less-than'
1404 predicate on the elements."
1405     (let ((res nil))
1406       (while (and list1 list2)
1407         (if (funcall pred (car list2) (car list1))
1408             (push (pop list2) res)
1409           (push (pop list1) res)))
1410       (nconc (nreverse res) list1 list2))))
1411
1412 (eval-when-compile
1413   (defvar xemacs-codename))
1414
1415 (defun gnus-emacs-version ()
1416   "Stringified Emacs version."
1417   (let ((system-v
1418          (cond
1419           ((eq gnus-user-agent 'emacs-gnus-config)
1420            system-configuration)
1421           ((eq gnus-user-agent 'emacs-gnus-type)
1422            (symbol-name system-type))
1423           (t nil))))
1424     (cond
1425      ((eq gnus-user-agent 'gnus)
1426       nil)
1427      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1428       (concat "Emacs/" (match-string 1 emacs-version)
1429               (if system-v
1430                   (concat " (" system-v ")")
1431                 "")))
1432      ((string-match
1433        "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1434        emacs-version)
1435       (concat
1436        (match-string 1 emacs-version)
1437        (format "/%d.%d" emacs-major-version emacs-minor-version)
1438        (if (match-beginning 3)
1439            (match-string 3 emacs-version)
1440          "")
1441        (if (boundp 'xemacs-codename)
1442            (concat
1443             " (" xemacs-codename
1444             (if system-v
1445                 (concat ", " system-v ")")
1446               ")"))
1447          "")))
1448      (t emacs-version))))
1449
1450 (provide 'gnus-util)
1451
1452 ;;; gnus-util.el ends here