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