93d2c573259ba1d46e326f0bc2ddb0f864c9990f
[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   "Alist of time in seconds and format specification used to display dates not older.
381 The first element must be a number or a function returning a
382 number. The second element is a format-specification as described in
383 the documentation for format-time-string.  The list must be ordered
384 smallest number up. When there is an element, which is not a number,
385 the corresponding format-specification will be used, disregarding any
386 following elements.  You can use the functions gnus-seconds-today,
387 gnus-seconds-month, gnus-seconds-year which will return the number of
388 seconds which passed today/this month/this year.")
389
390 (defun gnus-user-date (messy-date)
391   "Format the messy-date acording to gnus-user-date-format-alist.
392 Returns \"  ?  \" if there's bad input or if an other error occurs.
393 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
394   (condition-case ()
395       (let* ((messy-date (safe-date-to-time messy-date))
396              (now (current-time))
397              ;;If we don't find something suitable we'll use this one
398              (my-format "%b %m '%y")
399              (high (lsh (- (car now) (car messy-date)) 16)))
400         (if (and (> high -1) (= (logand high 65535) 0))
401             ;;overflow and bad input
402             (let* ((difference (+ high (- (car (cdr now))
403                                           (car (cdr messy-date)))))
404                    (templist gnus-user-date-format-alist)
405                    (top (eval (caar templist))))
406               (while (if (numberp top) (< top difference) (not top))
407                 (progn
408                   (setq templist (cdr templist))
409                   (setq top (eval (caar templist)))))
410               (if (stringp (cdr (car templist)))
411                   (setq my-format (cdr (car templist))))))
412         (format-time-string (eval my-format) messy-date))
413     (error "  ?   ")))
414 ;;end of Frank's code
415
416 (defun gnus-dd-mmm (messy-date)
417   "Return a string like DD-MMM from a big messy string."
418   (condition-case ()
419       (format-time-string "%d-%b" (safe-date-to-time messy-date))
420     (error "  -   ")))
421
422 (defmacro gnus-date-get-time (date)
423   "Convert DATE string to Emacs time.
424 Cache the result as a text property stored in DATE."
425   ;; Either return the cached value...
426   `(let ((d ,date))
427      (if (equal "" d)
428          '(0 0)
429        (or (get-text-property 0 'gnus-time d)
430            ;; or compute the value...
431            (let ((time (safe-date-to-time d)))
432              ;; and store it back in the string.
433              (put-text-property 0 1 'gnus-time time d)
434              time)))))
435
436 (defsubst gnus-time-iso8601 (time)
437   "Return a string of TIME in YYYYMMDDTHHMMSS format."
438   (format-time-string "%Y%m%dT%H%M%S" time))
439
440 (defun gnus-date-iso8601 (date)
441   "Convert the DATE to YYYYMMDDTHHMMSS."
442   (condition-case ()
443       (gnus-time-iso8601 (gnus-date-get-time date))
444     (error "")))
445
446 (defun gnus-mode-string-quote (string)
447   "Quote all \"%\"'s in STRING."
448   (gnus-replace-in-string string "%" "%%"))
449
450 ;; Make a hash table (default and minimum size is 256).
451 ;; Optional argument HASHSIZE specifies the table size.
452 (defun gnus-make-hashtable (&optional hashsize)
453   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
454
455 ;; Make a number that is suitable for hashing; bigger than MIN and
456 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
457 ;; hardware modulo operation, so they implement it in software.  On
458 ;; many sparcs over 50% of the time to intern is spent in the modulo.
459 ;; Yes, it's slower than actually computing the hash from the string!
460 ;; So we use powers of 2 so people can optimize the modulo to a mask.
461 (defun gnus-create-hash-size (min)
462   (let ((i 1))
463     (while (< i min)
464       (setq i (* 2 i)))
465     i))
466
467 (defcustom gnus-verbose 7
468   "*Integer that says how verbose Gnus should be.
469 The higher the number, the more messages Gnus will flash to say what
470 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
471 display most important messages; and at ten, Gnus will keep on
472 jabbering all the time."
473   :group 'gnus-start
474   :type 'integer)
475
476 ;; Show message if message has a lower level than `gnus-verbose'.
477 ;; Guideline for numbers:
478 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
479 ;; for things that take a long time, 7 - not very important messages
480 ;; on stuff, 9 - messages inside loops.
481 (defun gnus-message (level &rest args)
482   (if (<= level gnus-verbose)
483       (apply 'message args)
484     ;; We have to do this format thingy here even if the result isn't
485     ;; shown - the return value has to be the same as the return value
486     ;; from `message'.
487     (apply 'format args)))
488
489 (defun gnus-error (level &rest args)
490   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
491   (when (<= (floor level) gnus-verbose)
492     (apply 'message args)
493     (ding)
494     (let (duration)
495       (when (and (floatp level)
496                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
497         (sit-for duration))))
498   nil)
499
500 (defun gnus-split-references (references)
501   "Return a list of Message-IDs in REFERENCES."
502   (let ((beg 0)
503         ids)
504     (while (string-match "<[^<]+[^< \t]" references beg)
505       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
506             ids))
507     (nreverse ids)))
508
509 (defsubst gnus-parent-id (references &optional n)
510   "Return the last Message-ID in REFERENCES.
511 If N, return the Nth ancestor instead."
512   (when (and references
513              (not (zerop (length references))))
514     (if n
515         (let ((ids (inline (gnus-split-references references))))
516           (while (nthcdr n ids)
517             (setq ids (cdr ids)))
518           (car ids))
519       (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
520         (match-string 1 references)))))
521
522 (defun gnus-buffer-live-p (buffer)
523   "Say whether BUFFER is alive or not."
524   (and buffer
525        (get-buffer buffer)
526        (buffer-name (get-buffer buffer))))
527
528 (defun gnus-horizontal-recenter ()
529   "Recenter the current buffer horizontally."
530   (if (< (current-column) (/ (window-width) 2))
531       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
532     (let* ((orig (point))
533            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
534            (max 0))
535       (when end
536         ;; Find the longest line currently displayed in the window.
537         (goto-char (window-start))
538         (while (and (not (eobp))
539                     (< (point) end))
540           (end-of-line)
541           (setq max (max max (current-column)))
542           (forward-line 1))
543         (goto-char orig)
544         ;; Scroll horizontally to center (sort of) the point.
545         (if (> max (window-width))
546             (set-window-hscroll
547              (gnus-get-buffer-window (current-buffer) t)
548              (min (- (current-column) (/ (window-width) 3))
549                   (+ 2 (- max (window-width)))))
550           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
551         max))))
552
553 (defun gnus-read-event-char ()
554   "Get the next event."
555   (let ((event (read-event)))
556     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
557     (cons (and (numberp event) event) event)))
558
559 (defun gnus-sortable-date (date)
560   "Make string suitable for sorting from DATE."
561   (gnus-time-iso8601 (date-to-time date)))
562
563 (defun gnus-copy-file (file &optional to)
564   "Copy FILE to TO."
565   (interactive
566    (list (read-file-name "Copy file: " default-directory)
567          (read-file-name "Copy file to: " default-directory)))
568   (unless to
569     (setq to (read-file-name "Copy file to: " default-directory)))
570   (when (file-directory-p to)
571     (setq to (concat (file-name-as-directory to)
572                      (file-name-nondirectory file))))
573   (copy-file file to))
574
575 (defvar gnus-work-buffer " *gnus work*")
576
577 (defun gnus-set-work-buffer ()
578   "Put point in the empty Gnus work buffer."
579   (if (get-buffer gnus-work-buffer)
580       (progn
581         (set-buffer gnus-work-buffer)
582         (erase-buffer))
583     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
584     (kill-all-local-variables)))
585
586 (defmacro gnus-group-real-name (group)
587   "Find the real name of a foreign newsgroup."
588   `(let ((gname ,group))
589      (if (string-match "^[^:]+:" gname)
590          (substring gname (match-end 0))
591        gname)))
592
593 (defun gnus-make-sort-function (funs)
594   "Return a composite sort condition based on the functions in FUNC."
595   (cond
596    ;; Just a simple function.
597    ((gnus-functionp funs) funs)
598    ;; No functions at all.
599    ((null funs) funs)
600    ;; A list of functions.
601    ((or (cdr funs)
602         (listp (car funs)))
603     (gnus-byte-compile
604      `(lambda (t1 t2)
605         ,(gnus-make-sort-function-1 (reverse funs)))))
606    ;; A list containing just one function.
607    (t
608     (car funs))))
609
610 (defun gnus-make-sort-function-1 (funs)
611   "Return a composite sort condition based on the functions in FUNC."
612   (let ((function (car funs))
613         (first 't1)
614         (last 't2))
615     (when (consp function)
616       (cond
617        ;; Reversed spec.
618        ((eq (car function) 'not)
619         (setq function (cadr function)
620               first 't2
621               last 't1))
622        ((gnus-functionp function)
623         ;; Do nothing.
624         )
625        (t
626         (error "Invalid sort spec: %s" function))))
627     (if (cdr funs)
628         `(or (,function ,first ,last)
629              (and (not (,function ,last ,first))
630                   ,(gnus-make-sort-function-1 (cdr funs))))
631       `(,function ,first ,last))))
632
633 (defun gnus-turn-off-edit-menu (type)
634   "Turn off edit menu in `gnus-TYPE-mode-map'."
635   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
636     [menu-bar edit] 'undefined))
637
638 (defun gnus-prin1 (form)
639   "Use `prin1' on FORM in the current buffer.
640 Bind `print-quoted' and `print-readably' to t while printing."
641   (let ((print-quoted t)
642         (print-readably t)
643         (print-escape-multibyte nil)
644         print-level print-length)
645     (prin1 form (current-buffer))))
646
647 (defun gnus-prin1-to-string (form)
648   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
649   (let ((print-quoted t)
650         (print-readably t))
651     (prin1-to-string form)))
652
653 (defun gnus-make-directory (directory)
654   "Make DIRECTORY (and all its parents) if it doesn't exist."
655   (require 'nnmail)
656   (let ((file-name-coding-system nnmail-pathname-coding-system)
657         (pathname-coding-system nnmail-pathname-coding-system))
658     (when (and directory
659                (not (file-exists-p directory)))
660       (make-directory directory t)))
661   t)
662
663 (defun gnus-write-buffer (file)
664   "Write the current buffer's contents to FILE."
665   ;; Make sure the directory exists.
666   (gnus-make-directory (file-name-directory file))
667   (let ((file-name-coding-system nnmail-pathname-coding-system)
668         (pathname-coding-system nnmail-pathname-coding-system))
669     ;; Write the buffer.
670     (write-region (point-min) (point-max) file nil 'quietly)))
671
672 (defun gnus-write-buffer-as-binary (file)
673   "Write the current buffer's contents to FILE without code conversion."
674   ;; Make sure the directory exists.
675   (gnus-make-directory (file-name-directory file))
676   ;; Write the buffer.
677   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
678
679 (defun gnus-write-buffer-as-coding-system (coding-system file)
680   "Write the current buffer's contents to FILE with code conversion."
681   ;; Make sure the directory exists.
682   (gnus-make-directory (file-name-directory file))
683   ;; Write the buffer.
684   (write-region-as-coding-system
685    coding-system (point-min) (point-max) file nil 'quietly))
686
687 (defun gnus-delete-file (file)
688   "Delete FILE if it exists."
689   (when (file-exists-p file)
690     (delete-file file)))
691
692 (defun gnus-strip-whitespace (string)
693   "Return STRING stripped of all whitespace."
694   (while (string-match "[\r\n\t ]+" string)
695     (setq string (replace-match "" t t string)))
696   string)
697
698 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
699   "The same as `put-text-property', but don't put this prop on any newlines in the region."
700   (save-match-data
701     (save-excursion
702       (save-restriction
703         (goto-char beg)
704         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
705           (gnus-put-text-property beg (match-beginning 0) prop val)
706           (setq beg (point)))
707         (gnus-put-text-property beg (point) prop val)))))
708
709 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
710   "The same as `put-text-property', but don't put this prop on any newlines in the region."
711   (save-match-data
712     (save-excursion
713       (save-restriction
714         (goto-char beg)
715         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
716           (gnus-overlay-put
717            (gnus-make-overlay beg (match-beginning 0))
718            prop val)
719           (setq beg (point)))
720         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
721
722 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
723                                                                    prop val)
724   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
725   (let ((b beg))
726     (while (/= b end)
727       (when (get-text-property b 'gnus-face)
728         (setq b (next-single-property-change b 'gnus-face nil end)))
729       (when (/= b end)
730         (inline
731           (gnus-put-text-property
732            b (setq b (next-single-property-change b 'gnus-face nil end))
733            prop val))))))
734
735 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
736 ;;; The primary idea here is to try to protect internal datastructures
737 ;;; from becoming corrupted when the user hits C-g, or if a hook or
738 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
739 ;;; updated at the same time, or information can be lost.
740
741 (defvar gnus-atomic-be-safe t
742   "If t, certain operations will be protected from interruption by C-g.")
743
744 (defmacro gnus-atomic-progn (&rest forms)
745   "Evaluate FORMS atomically, which means to protect the evaluation
746 from being interrupted by the user.  An error from the forms themselves
747 will return without finishing the operation.  Since interrupts from
748 the user are disabled, it is recommended that only the most minimal
749 operations are performed by FORMS.  If you wish to assign many
750 complicated values atomically, compute the results into temporary
751 variables and then do only the assignment atomically."
752   `(let ((inhibit-quit gnus-atomic-be-safe))
753      ,@forms))
754
755 (put 'gnus-atomic-progn 'lisp-indent-function 0)
756
757 (defmacro gnus-atomic-progn-assign (protect &rest forms)
758   "Evaluate FORMS, but insure that the variables listed in PROTECT
759 are not changed if anything in FORMS signals an error or otherwise
760 non-locally exits.  The variables listed in PROTECT are updated atomically.
761 It is safe to use gnus-atomic-progn-assign with long computations.
762
763 Note that if any of the symbols in PROTECT were unbound, they will be
764 set to nil on a sucessful assignment.  In case of an error or other
765 non-local exit, it will still be unbound."
766   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
767                                                   (concat (symbol-name x)
768                                                           "-tmp"))
769                                                  x))
770                                protect))
771          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
772                                temp-sym-map))
773          (temp-sym-let (mapcar (lambda (x) (list (car x)
774                                                  `(and (boundp ',(cadr x))
775                                                        ,(cadr x))))
776                                temp-sym-map))
777          (sym-temp-let sym-temp-map)
778          (temp-sym-assign (apply 'append temp-sym-map))
779          (sym-temp-assign (apply 'append sym-temp-map))
780          (result (make-symbol "result-tmp")))
781     `(let (,@temp-sym-let
782            ,result)
783        (let ,sym-temp-let
784          (setq ,result (progn ,@forms))
785          (setq ,@temp-sym-assign))
786        (let ((inhibit-quit gnus-atomic-be-safe))
787          (setq ,@sym-temp-assign))
788        ,result)))
789
790 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
791 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
792
793 (defmacro gnus-atomic-setq (&rest pairs)
794   "Similar to setq, except that the real symbols are only assigned when
795 there are no errors.  And when the real symbols are assigned, they are
796 done so atomically.  If other variables might be changed via side-effect,
797 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
798 with potentially long computations."
799   (let ((tpairs pairs)
800         syms)
801     (while tpairs
802       (push (car tpairs) syms)
803       (setq tpairs (cddr tpairs)))
804     `(gnus-atomic-progn-assign ,syms
805        (setq ,@pairs))))
806
807 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
808
809
810 ;;; Functions for saving to babyl/mail files.
811
812 (defvar rmail-default-rmail-file)
813 (defun gnus-output-to-rmail (filename &optional ask)
814   "Append the current article to an Rmail file named FILENAME."
815   (require 'rmail)
816   ;; Most of these codes are borrowed from rmailout.el.
817   (setq filename (expand-file-name filename))
818   (setq rmail-default-rmail-file filename)
819   (let ((artbuf (current-buffer))
820         (tmpbuf (get-buffer-create " *Gnus-output*")))
821     (save-excursion
822       (or (get-file-buffer filename)
823           (file-exists-p filename)
824           (if (or (not ask)
825                   (gnus-yes-or-no-p
826                    (concat "\"" filename "\" does not exist, create it? ")))
827               (let ((file-buffer (create-file-buffer filename)))
828                 (save-excursion
829                   (set-buffer file-buffer)
830                   (rmail-insert-rmail-file-header)
831                   (let ((require-final-newline nil))
832                     (gnus-write-buffer-as-coding-system
833                      nnheader-text-coding-system filename)))
834                 (kill-buffer file-buffer))
835             (error "Output file does not exist")))
836       (set-buffer tmpbuf)
837       (erase-buffer)
838       (insert-buffer-substring artbuf)
839       (gnus-convert-article-to-rmail)
840       ;; Decide whether to append to a file or to an Emacs buffer.
841       (let ((outbuf (get-file-buffer filename)))
842         (if (not outbuf)
843             (let ((file-name-coding-system nnmail-pathname-coding-system)
844                   (pathname-coding-system nnmail-pathname-coding-system))
845               (write-region-as-binary (point-min) (point-max)
846                                       filename 'append))
847           ;; File has been visited, in buffer OUTBUF.
848           (set-buffer outbuf)
849           (let ((buffer-read-only nil)
850                 (msg (and (boundp 'rmail-current-message)
851                           (symbol-value 'rmail-current-message))))
852             ;; If MSG is non-nil, buffer is in RMAIL mode.
853             (when msg
854               (widen)
855               (narrow-to-region (point-max) (point-max)))
856             (insert-buffer-substring tmpbuf)
857             (when msg
858               (goto-char (point-min))
859               (widen)
860               (search-backward "\n\^_")
861               (narrow-to-region (point) (point-max))
862               (rmail-count-new-messages t)
863               (when (rmail-summary-exists)
864                 (rmail-select-summary
865                  (rmail-update-summary)))
866               (rmail-count-new-messages t)
867               (rmail-show-message msg))
868             (save-buffer)))))
869     (kill-buffer tmpbuf)))
870
871 (defun gnus-output-to-mail (filename &optional ask)
872   "Append the current article to a mail file named FILENAME."
873   (setq filename (expand-file-name filename))
874   (let ((artbuf (current-buffer))
875         (tmpbuf (get-buffer-create " *Gnus-output*")))
876     (save-excursion
877       ;; Create the file, if it doesn't exist.
878       (when (and (not (get-file-buffer filename))
879                  (not (file-exists-p filename)))
880         (if (or (not ask)
881                 (gnus-y-or-n-p
882                  (concat "\"" filename "\" does not exist, create it? ")))
883             (let ((file-buffer (create-file-buffer filename)))
884               (save-excursion
885                 (set-buffer file-buffer)
886                 (let ((require-final-newline nil))
887                   (gnus-write-buffer-as-coding-system
888                    nnheader-text-coding-system filename)))
889               (kill-buffer file-buffer))
890           (error "Output file does not exist")))
891       (set-buffer tmpbuf)
892       (erase-buffer)
893       (insert-buffer-substring artbuf)
894       (goto-char (point-min))
895       (if (looking-at "From ")
896           (forward-line 1)
897         (insert "From nobody " (current-time-string) "\n"))
898       (let (case-fold-search)
899         (while (re-search-forward "^From " nil t)
900           (beginning-of-line)
901           (insert ">")))
902       ;; Decide whether to append to a file or to an Emacs buffer.
903       (let ((outbuf (get-file-buffer filename)))
904         (if (not outbuf)
905             (let ((buffer-read-only nil))
906               (save-excursion
907                 (goto-char (point-max))
908                 (forward-char -2)
909                 (unless (looking-at "\n\n")
910                   (goto-char (point-max))
911                   (unless (bolp)
912                     (insert "\n"))
913                   (insert "\n"))
914                 (goto-char (point-max))
915                 (let ((file-name-coding-system nnmail-pathname-coding-system)
916                       (pathname-coding-system nnmail-pathname-coding-system))
917                   (write-region-as-binary (point-min) (point-max)
918                                           filename 'append))))
919           ;; File has been visited, in buffer OUTBUF.
920           (set-buffer outbuf)
921           (let ((buffer-read-only nil))
922             (goto-char (point-max))
923             (unless (eobp)
924               (insert "\n"))
925             (insert "\n")
926             (insert-buffer-substring tmpbuf)))))
927     (kill-buffer tmpbuf)))
928
929 (defun gnus-convert-article-to-rmail ()
930   "Convert article in current buffer to Rmail message format."
931   (let ((buffer-read-only nil))
932     ;; Convert article directly into Babyl format.
933     (goto-char (point-min))
934     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
935     (while (search-forward "\n\^_" nil t) ;single char
936       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
937     (goto-char (point-max))
938     (insert "\^_")))
939
940 (defun gnus-map-function (funs arg)
941   "Applies the result of the first function in FUNS to the second, and so on.
942 ARG is passed to the first function."
943   (let ((myfuns funs))
944     (while myfuns
945       (setq arg (funcall (pop myfuns) arg)))
946     arg))
947
948 (defun gnus-run-hooks (&rest funcs)
949   "Does the same as `run-hooks', but saves excursion."
950   (let ((buf (current-buffer)))
951     (unwind-protect
952         (apply 'run-hooks funcs)
953       (set-buffer buf))))
954
955 ;;; Various
956
957 (defvar gnus-group-buffer)              ; Compiler directive
958 (defun gnus-alive-p ()
959   "Say whether Gnus is running or not."
960   (and (boundp 'gnus-group-buffer)
961        (get-buffer gnus-group-buffer)
962        (save-excursion
963          (set-buffer gnus-group-buffer)
964          (eq major-mode 'gnus-group-mode))))
965
966 (defun gnus-remove-duplicates (list)
967   (let (new (tail list))
968     (while tail
969       (or (member (car tail) new)
970           (setq new (cons (car tail) new)))
971       (setq tail (cdr tail)))
972     (nreverse new)))
973
974 (defun gnus-delete-if (predicate list)
975   "Delete elements from LIST that satisfy PREDICATE."
976   (let (out)
977     (while list
978       (unless (funcall predicate (car list))
979         (push (car list) out))
980       (pop list))
981     (nreverse out)))
982
983 (if (fboundp 'assq-delete-all)
984     (defalias 'gnus-delete-alist 'assq-delete-all)
985   (defun gnus-delete-alist (key alist)
986     "Delete from ALIST all elements whose car is KEY.
987 Return the modified alist."
988     (let (entry)
989       (while (setq entry (assq key alist))
990         (setq alist (delq entry alist)))
991       alist)))
992
993 (defmacro gnus-pull (key alist &optional assoc-p)
994   "Modify ALIST to be without KEY."
995   (unless (symbolp alist)
996     (error "Not a symbol: %s" alist))
997   (let ((fun (if assoc-p 'assoc 'assq)))
998     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
999
1000 (defun gnus-globalify-regexp (re)
1001   "Returns a regexp that matches a whole line, iff RE matches a part of it."
1002   (concat (unless (string-match "^\\^" re) "^.*")
1003           re
1004           (unless (string-match "\\$$" re) ".*$")))
1005
1006 (defun gnus-set-window-start (&optional point)
1007   "Set the window start to POINT, or (point) if nil."
1008   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1009     (when win
1010       (set-window-start win (or point (point))))))
1011
1012 (defun gnus-annotation-in-region-p (b e)
1013   (if (= b e)
1014       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1015     (text-property-any b e 'gnus-undeletable t)))
1016
1017 (defun gnus-or (&rest elems)
1018   "Return non-nil if any of the elements are non-nil."
1019   (catch 'found
1020     (while elems
1021       (when (pop elems)
1022         (throw 'found t)))))
1023
1024 (defun gnus-and (&rest elems)
1025   "Return non-nil if all of the elements are non-nil."
1026   (catch 'found
1027     (while elems
1028       (unless (pop elems)
1029         (throw 'found nil)))
1030     t))
1031
1032 (defun gnus-write-active-file (file hashtb &optional full-names)
1033   (let ((output-coding-system nnmail-active-file-coding-system)
1034         (coding-system-for-write nnmail-active-file-coding-system))
1035     (with-temp-file file
1036       (mapatoms
1037        (lambda (sym)
1038          (when (and sym
1039                     (boundp sym)
1040                     (symbol-value sym))
1041            (insert (format "%S %d %d y\n"
1042                            (if full-names
1043                                sym
1044                              (intern (gnus-group-real-name (symbol-name sym))))
1045                            (or (cdr (symbol-value sym))
1046                                (car (symbol-value sym)))
1047                            (car (symbol-value sym))))))
1048        hashtb)
1049       (goto-char (point-max))
1050       (while (search-backward "\\." nil t)
1051         (delete-char 1)))))
1052
1053 (if (fboundp 'union)
1054     (defalias 'gnus-union 'union)
1055   (defun gnus-union (l1 l2)
1056     "Set union of lists L1 and L2."
1057     (cond ((null l1) l2)
1058           ((null l2) l1)
1059           ((equal l1 l2) l1)
1060           (t
1061            (or (>= (length l1) (length l2))
1062                (setq l1 (prog1 l2 (setq l2 l1))))
1063            (while l2
1064              (or (member (car l2) l1)
1065                  (push (car l2) l1))
1066              (pop l2))
1067            l1))))
1068
1069 (defun gnus-add-text-properties-when
1070   (property value start end properties &optional object)
1071   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1072   (let (point)
1073     (while (and start
1074                 (< start end) ;; XEmacs will loop for every when start=end.
1075                 (setq point (text-property-not-all start end property value)))
1076       (gnus-add-text-properties start point properties object)
1077       (setq start (text-property-any point end property value)))
1078     (if start
1079         (gnus-add-text-properties start end properties object))))
1080
1081 (defun gnus-remove-text-properties-when
1082   (property value start end properties &optional object)
1083   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1084   (let (point)
1085     (while (and start
1086                 (< start end)
1087                 (setq point (text-property-not-all start end property value)))
1088       (remove-text-properties start point properties object)
1089       (setq start (text-property-any point end property value)))
1090     (if start
1091         (remove-text-properties start end properties object))
1092     t))
1093
1094 (defun gnus-string-equal (x y)
1095   "Like `string-equal', except it compares case-insensitively."
1096   (and (= (length x) (length y))
1097        (or (string-equal x y)
1098            (string-equal (downcase x) (downcase y)))))
1099
1100 (defcustom gnus-use-byte-compile t
1101   "If non-nil, byte-compile crucial run-time codes.
1102 Setting it to `nil' has no effect after first time running
1103 `gnus-byte-compile'."
1104   :type 'boolean
1105   :version "21.1"
1106   :group 'gnus-various)
1107
1108 (defun gnus-byte-compile (form)
1109   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1110   (if gnus-use-byte-compile
1111       (progn
1112         (condition-case nil
1113             ;; Work around a bug in XEmacs 21.4
1114             (require 'byte-optimize)
1115           (error))
1116         (require 'bytecomp)
1117         (defalias 'gnus-byte-compile 'byte-compile)
1118         (byte-compile form))
1119     form))
1120
1121 (defun gnus-remassoc (key alist)
1122   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1123 The modified LIST is returned.  If the first member
1124 of LIST has a car that is `equal' to KEY, there is no way to remove it
1125 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1126 sure of changing the value of `foo'."
1127   (when alist
1128     (if (equal key (caar alist))
1129         (cdr alist)
1130       (setcdr alist (gnus-remassoc key (cdr alist)))
1131       alist)))
1132
1133 (defun gnus-update-alist-soft (key value alist)
1134   (if value
1135       (cons (cons key value) (gnus-remassoc key alist))
1136     (gnus-remassoc key alist)))
1137
1138 (defun gnus-create-info-command (node)
1139   "Create a command that will go to info NODE."
1140   `(lambda ()
1141      (interactive)
1142      ,(concat "Enter the info system at node " node)
1143      (Info-goto-node ,node)
1144      (setq gnus-info-buffer (current-buffer))
1145      (gnus-configure-windows 'info)))
1146
1147 (defun gnus-not-ignore (&rest args)
1148   t)
1149
1150 (defvar gnus-directory-sep-char-regexp "/"
1151   "The regexp of directory separator character.
1152 If you find some problem with the directory separator character, try
1153 \"[/\\\\\]\" for some systems.")
1154
1155 (defun gnus-url-unhex (x)
1156   (if (> x ?9)
1157       (if (>= x ?a)
1158           (+ 10 (- x ?a))
1159         (+ 10 (- x ?A)))
1160     (- x ?0)))
1161
1162 (defun gnus-url-unhex-string (str &optional allow-newlines)
1163   "Remove %XXX embedded spaces, etc in a url.
1164 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1165 decoding of carriage returns and line feeds in the string, which is normally
1166 forbidden in URL encoding."
1167   (setq str (or (mm-subst-char-in-string ?+ ?  str) ""))
1168   (let ((tmp "")
1169         (case-fold-search t))
1170     (while (string-match "%[0-9a-f][0-9a-f]" str)
1171       (let* ((start (match-beginning 0))
1172              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1173              (code (+ (* 16 ch1)
1174                       (gnus-url-unhex (elt str (+ start 2))))))
1175         (setq tmp (concat
1176                    tmp (substring str 0 start)
1177                    (cond
1178                     (allow-newlines
1179                      (char-to-string code))
1180                     ((or (= code ?\n) (= code ?\r))
1181                      " ")
1182                     (t (char-to-string code))))
1183               str (substring str (match-end 0)))))
1184     (setq tmp (concat tmp str))
1185     tmp))
1186
1187 (defun gnus-make-predicate (spec)
1188   "Transform SPEC into a function that can be called.
1189 SPEC is a predicate specifier that contains stuff like `or', `and',
1190 `not', lists and functions.  The functions all take one parameter."
1191   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1192
1193 (defun gnus-make-predicate-1 (spec)
1194   (cond
1195    ((symbolp spec)
1196     `(,spec elem))
1197    ((listp spec)
1198     (if (memq (car spec) '(or and not))
1199         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1200       (error "Invalid predicate specifier: %s" spec)))))
1201
1202 (defun gnus-local-map-property (map)
1203   "Return a list suitable for a text property list specifying keymap MAP."
1204   (cond
1205    ((featurep 'xemacs)
1206     (list 'keymap map))
1207    ((>= emacs-major-version 21)
1208     (list 'keymap map))
1209    (t
1210     (list 'local-map map))))
1211
1212 (defun gnus-completing-read (prompt table &optional predicate require-match
1213                                     history)
1214   (when (and history
1215              (not (boundp history)))
1216     (set history nil))
1217   (completing-read
1218    (if (symbol-value history)
1219        (concat prompt " (" (car (symbol-value history)) "): ")
1220      (concat prompt ": "))
1221    table
1222    predicate
1223    require-match
1224    nil
1225    history
1226    (car (symbol-value history))))
1227
1228 (defun gnus-graphic-display-p ()
1229   (or (and (fboundp 'display-graphic-p)
1230            (display-graphic-p))
1231       ;;;!!!This is bogus.  Fixme!
1232       (and (featurep 'xemacs)
1233            t)))
1234
1235 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1236 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1237
1238 (defmacro gnus-parse-without-error (&rest body)
1239   "Allow continuing onto the next line even if an error occurs."
1240   `(while (not (eobp))
1241      (condition-case ()
1242          (progn
1243            ,@body
1244            (goto-char (point-max)))
1245        (error
1246         (gnus-error 4 "Invalid data on line %d"
1247                     (count-lines (point-min) (point)))
1248         (forward-line 1)))))
1249
1250 (defun gnus-cache-file-contents (file variable function)
1251   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1252   (let ((time (nth 5 (file-attributes file)))
1253         contents value)
1254     (if (or (null (setq value (symbol-value variable)))
1255             (not (equal (car value) file))
1256             (not (equal (nth 1 value) time)))
1257         (progn
1258           (setq contents (funcall function file))
1259           (set variable (list file time contents))
1260           contents)
1261       (nth 2 value))))
1262
1263 (defun gnus-multiple-choice (prompt choice &optional idx)
1264   "Ask user a multiple choice question.
1265 CHOICE is a list of the choice char and help message at IDX."
1266   (let (tchar buf)
1267     (save-window-excursion
1268       (save-excursion
1269         (while (not tchar)
1270           (message "%s (%s?): "
1271                    prompt
1272                    (mapconcat (lambda (s) (char-to-string (car s)))
1273                               choice ""))
1274           (setq tchar (read-char))
1275           (when (not (assq tchar choice))
1276             (setq tchar nil)
1277             (setq buf (get-buffer-create "*Gnus Help*"))
1278             (pop-to-buffer buf)
1279             (fundamental-mode)          ; for Emacs 20.4+
1280             (buffer-disable-undo)
1281             (erase-buffer)
1282             (insert prompt ":\n\n")
1283             (let ((max -1)
1284                   (list choice)
1285                   (alist choice)
1286                   (idx (or idx 1))
1287                   (i 0)
1288                   n width pad format)
1289               ;; find the longest string to display
1290               (while list
1291                 (setq n (length (nth idx (car list))))
1292                 (unless (> max n)
1293                   (setq max n))
1294                 (setq list (cdr list)))
1295               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1296               (setq n (/ (1- (window-width)) max)) ; items per line
1297               (setq width (/ (1- (window-width)) n)) ; width of each item
1298               ;; insert `n' items, each in a field of width `width'
1299               (while alist
1300                 (if (< i n)
1301                     ()
1302                   (setq i 0)
1303                   (delete-char -1)              ; the `\n' takes a char
1304                   (insert "\n"))
1305                 (setq pad (- width 3))
1306                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1307                 (insert (format format (caar alist) (nth idx (car alist))))
1308                 (setq alist (cdr alist))
1309                 (setq i (1+ i))))))))
1310     (if (buffer-live-p buf)
1311         (kill-buffer buf))
1312     tchar))
1313
1314 (provide 'gnus-util)
1315
1316 ;;; gnus-util.el ends here