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