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