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