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