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