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