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