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