abd382d92f9c67ac1234d2f00e98b7ce67703b11
[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   (condition-case nil
807       (progn
808         (require 'rmail)
809         (autoload 'rmail-update-summary "rmailsum"))
810     (error
811      (define-compiler-macro rmail-select-summary (&rest body)
812        ;; Rmail of the XEmacs version is supplied by the package, and
813        ;; requires tm and apel packages.  However, there may be those
814        ;; who haven't installed those packages.  This macro helps such
815        ;; people even if they install those packages later.
816        `(eval '(rmail-select-summary ,@body)))
817      ;; If there's rmail but there's no tm (or there's apel of the
818      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
819      ;; version fails halfway, however it provides the rmail-select-summary
820      ;; macro which uses the following functions:
821      (autoload 'rmail-summary-displayed "rmail")
822      (autoload 'rmail-maybe-display-summary "rmail")))
823   (defvar rmail-default-rmail-file)
824   (defvar mm-text-coding-system))
825
826 (defun gnus-output-to-rmail (filename &optional ask)
827   "Append the current article to an Rmail file named FILENAME."
828   (require 'rmail)
829   (require 'mm-util)
830   ;; Most of these codes are borrowed from rmailout.el.
831   (setq filename (expand-file-name filename))
832   (setq rmail-default-rmail-file filename)
833   (let ((artbuf (current-buffer))
834         (tmpbuf (get-buffer-create " *Gnus-output*")))
835     (save-excursion
836       (or (get-file-buffer filename)
837           (file-exists-p filename)
838           (if (or (not ask)
839                   (gnus-yes-or-no-p
840                    (concat "\"" filename "\" does not exist, create it? ")))
841               (let ((file-buffer (create-file-buffer filename)))
842                 (save-excursion
843                   (set-buffer file-buffer)
844                   (rmail-insert-rmail-file-header)
845                   (let ((require-final-newline nil)
846                         (coding-system-for-write mm-text-coding-system))
847                     (gnus-write-buffer filename)))
848                 (kill-buffer file-buffer))
849             (error "Output file does not exist")))
850       (set-buffer tmpbuf)
851       (erase-buffer)
852       (insert-buffer-substring artbuf)
853       (gnus-convert-article-to-rmail)
854       ;; Decide whether to append to a file or to an Emacs buffer.
855       (let ((outbuf (get-file-buffer filename)))
856         (if (not outbuf)
857             (let ((file-name-coding-system nnmail-pathname-coding-system))
858               (mm-append-to-file (point-min) (point-max) filename))
859           ;; File has been visited, in buffer OUTBUF.
860           (set-buffer outbuf)
861           (let ((buffer-read-only nil)
862                 (msg (and (boundp 'rmail-current-message)
863                           (symbol-value 'rmail-current-message))))
864             ;; If MSG is non-nil, buffer is in RMAIL mode.
865             (when msg
866               (widen)
867               (narrow-to-region (point-max) (point-max)))
868             (insert-buffer-substring tmpbuf)
869             (when msg
870               (goto-char (point-min))
871               (widen)
872               (search-backward "\n\^_")
873               (narrow-to-region (point) (point-max))
874               (rmail-count-new-messages t)
875               (when (rmail-summary-exists)
876                 (rmail-select-summary
877                  (rmail-update-summary)))
878               (rmail-count-new-messages t)
879               (rmail-show-message msg))
880             (save-buffer)))))
881     (kill-buffer tmpbuf)))
882
883 (defun gnus-output-to-mail (filename &optional ask)
884   "Append the current article to a mail file named FILENAME."
885   (setq filename (expand-file-name filename))
886   (let ((artbuf (current-buffer))
887         (tmpbuf (get-buffer-create " *Gnus-output*")))
888     (save-excursion
889       ;; Create the file, if it doesn't exist.
890       (when (and (not (get-file-buffer filename))
891                  (not (file-exists-p filename)))
892         (if (or (not ask)
893                 (gnus-y-or-n-p
894                  (concat "\"" filename "\" does not exist, create it? ")))
895             (let ((file-buffer (create-file-buffer filename)))
896               (save-excursion
897                 (set-buffer file-buffer)
898                 (let ((require-final-newline nil)
899                       (coding-system-for-write mm-text-coding-system))
900                   (gnus-write-buffer filename)))
901               (kill-buffer file-buffer))
902           (error "Output file does not exist")))
903       (set-buffer tmpbuf)
904       (erase-buffer)
905       (insert-buffer-substring artbuf)
906       (goto-char (point-min))
907       (if (looking-at "From ")
908           (forward-line 1)
909         (insert "From nobody " (current-time-string) "\n"))
910       (let (case-fold-search)
911         (while (re-search-forward "^From " nil t)
912           (beginning-of-line)
913           (insert ">")))
914       ;; Decide whether to append to a file or to an Emacs buffer.
915       (let ((outbuf (get-file-buffer filename)))
916         (if (not outbuf)
917             (let ((buffer-read-only nil))
918               (save-excursion
919                 (goto-char (point-max))
920                 (forward-char -2)
921                 (unless (looking-at "\n\n")
922                   (goto-char (point-max))
923                   (unless (bolp)
924                     (insert "\n"))
925                   (insert "\n"))
926                 (goto-char (point-max))
927                 (let ((file-name-coding-system nnmail-pathname-coding-system))
928                   (mm-append-to-file (point-min) (point-max) filename))))
929           ;; File has been visited, in buffer OUTBUF.
930           (set-buffer outbuf)
931           (let ((buffer-read-only nil))
932             (goto-char (point-max))
933             (unless (eobp)
934               (insert "\n"))
935             (insert "\n")
936             (insert-buffer-substring tmpbuf)))))
937     (kill-buffer tmpbuf)))
938
939 (defun gnus-convert-article-to-rmail ()
940   "Convert article in current buffer to Rmail message format."
941   (let ((buffer-read-only nil))
942     ;; Convert article directly into Babyl format.
943     (goto-char (point-min))
944     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
945     (while (search-forward "\n\^_" nil t) ;single char
946       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
947     (goto-char (point-max))
948     (insert "\^_")))
949
950 (defun gnus-map-function (funs arg)
951   "Apply the result of the first function in FUNS to the second, and so on.
952 ARG is passed to the first function."
953   (while funs
954     (setq arg (funcall (pop funs) arg)))
955   arg)
956
957 (defun gnus-run-hooks (&rest funcs)
958   "Does the same as `run-hooks', but saves the current buffer."
959   (save-current-buffer
960     (apply 'run-hooks funcs)))
961
962 ;;; Various
963
964 (defvar gnus-group-buffer)              ; Compiler directive
965 (defun gnus-alive-p ()
966   "Say whether Gnus is running or not."
967   (and (boundp 'gnus-group-buffer)
968        (get-buffer gnus-group-buffer)
969        (save-excursion
970          (set-buffer gnus-group-buffer)
971          (eq major-mode 'gnus-group-mode))))
972
973 (defun gnus-remove-duplicates (list)
974   (let (new)
975     (while list
976       (or (member (car list) new)
977           (setq new (cons (car list) new)))
978       (setq list (cdr list)))
979     (nreverse new)))
980
981 (defun gnus-remove-if (predicate list)
982   "Return a copy of LIST with all items satisfying PREDICATE removed."
983   (let (out)
984     (while list
985       (unless (funcall predicate (car list))
986         (push (car list) out))
987       (setq list (cdr list)))
988     (nreverse out)))
989
990 (if (fboundp 'assq-delete-all)
991     (defalias 'gnus-delete-alist 'assq-delete-all)
992   (defun gnus-delete-alist (key alist)
993     "Delete from ALIST all elements whose car is KEY.
994 Return the modified alist."
995     (let (entry)
996       (while (setq entry (assq key alist))
997         (setq alist (delq entry alist)))
998       alist)))
999
1000 (defmacro gnus-pull (key alist &optional assoc-p)
1001   "Modify ALIST to be without KEY."
1002   (unless (symbolp alist)
1003     (error "Not a symbol: %s" alist))
1004   (let ((fun (if assoc-p 'assoc 'assq)))
1005     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1006
1007 (defun gnus-globalify-regexp (re)
1008   "Return a regexp that matches a whole line, iff RE matches a part of it."
1009   (concat (unless (string-match "^\\^" re) "^.*")
1010           re
1011           (unless (string-match "\\$$" re) ".*$")))
1012
1013 (defun gnus-set-window-start (&optional point)
1014   "Set the window start to POINT, or (point) if nil."
1015   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1016     (when win
1017       (set-window-start win (or point (point))))))
1018
1019 (defun gnus-annotation-in-region-p (b e)
1020   (if (= b e)
1021       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1022     (text-property-any b e 'gnus-undeletable t)))
1023
1024 (defun gnus-or (&rest elems)
1025   "Return non-nil if any of the elements are non-nil."
1026   (catch 'found
1027     (while elems
1028       (when (pop elems)
1029         (throw 'found t)))))
1030
1031 (defun gnus-and (&rest elems)
1032   "Return non-nil if all of the elements are non-nil."
1033   (catch 'found
1034     (while elems
1035       (unless (pop elems)
1036         (throw 'found nil)))
1037     t))
1038
1039 (defun gnus-write-active-file (file hashtb &optional full-names)
1040   (let ((coding-system-for-write nnmail-active-file-coding-system))
1041     (with-temp-file file
1042       (mapatoms
1043        (lambda (sym)
1044          (when (and sym
1045                     (boundp sym)
1046                     (symbol-value sym))
1047            (insert (format "%S %d %d y\n"
1048                            (if full-names
1049                                sym
1050                              (intern (gnus-group-real-name (symbol-name sym))))
1051                            (or (cdr (symbol-value sym))
1052                                (car (symbol-value sym)))
1053                            (car (symbol-value sym))))))
1054        hashtb)
1055       (goto-char (point-max))
1056       (while (search-backward "\\." nil t)
1057         (delete-char 1)))))
1058
1059 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1060 (defmacro gnus-with-output-to-file (file &rest body)
1061   (let ((buffer (make-symbol "output-buffer"))
1062         (size (make-symbol "output-buffer-size"))
1063         (leng (make-symbol "output-buffer-length"))
1064         (append (make-symbol "output-buffer-append")))
1065     `(let* ((,size 131072)
1066             (,buffer (make-string ,size 0))
1067             (,leng 0)
1068             (,append nil)
1069             (standard-output
1070              (lambda (c)
1071                (aset ,buffer ,leng c)
1072                    
1073                (if (= ,size (setq ,leng (1+ ,leng)))
1074                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1075                           (setq ,leng 0
1076                                 ,append t))))))
1077        ,@body
1078        (when (> ,leng 0)
1079          (let ((coding-system-for-write 'no-conversion))
1080          (write-region (substring ,buffer 0 ,leng) nil ,file
1081                        ,append 'no-msg))))))
1082
1083 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1084 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1085
1086 (if (fboundp 'union)
1087     (defalias 'gnus-union 'union)
1088   (defun gnus-union (l1 l2)
1089     "Set union of lists L1 and L2."
1090     (cond ((null l1) l2)
1091           ((null l2) l1)
1092           ((equal l1 l2) l1)
1093           (t
1094            (or (>= (length l1) (length l2))
1095                (setq l1 (prog1 l2 (setq l2 l1))))
1096            (while l2
1097              (or (member (car l2) l1)
1098                  (push (car l2) l1))
1099              (pop l2))
1100            l1))))
1101
1102 (defun gnus-add-text-properties-when
1103   (property value start end properties &optional object)
1104   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1105   (let (point)
1106     (while (and start
1107                 (< start end) ;; XEmacs will loop for every when start=end.
1108                 (setq point (text-property-not-all start end property value)))
1109       (gnus-add-text-properties start point properties object)
1110       (setq start (text-property-any point end property value)))
1111     (if start
1112         (gnus-add-text-properties start end properties object))))
1113
1114 (defun gnus-remove-text-properties-when
1115   (property value start end properties &optional object)
1116   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1117   (let (point)
1118     (while (and start
1119                 (< start end)
1120                 (setq point (text-property-not-all start end property value)))
1121       (remove-text-properties start point properties object)
1122       (setq start (text-property-any point end property value)))
1123     (if start
1124         (remove-text-properties start end properties object))
1125     t))
1126
1127 ;; This might use `compare-strings' to reduce consing in the
1128 ;; case-insensitive case, but it has to cope with null args.
1129 ;; (`string-equal' uses symbol print names.)
1130 (defun gnus-string-equal (x y)
1131   "Like `string-equal', except it compares case-insensitively."
1132   (and (= (length x) (length y))
1133        (or (string-equal x y)
1134            (string-equal (downcase x) (downcase y)))))
1135
1136 (defcustom gnus-use-byte-compile t
1137   "If non-nil, byte-compile crucial run-time code.
1138 Setting it to nil has no effect after the first time `gnus-byte-compile'
1139 is run."
1140   :type 'boolean
1141   :version "21.1"
1142   :group 'gnus-various)
1143
1144 (defun gnus-byte-compile (form)
1145   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1146   (if gnus-use-byte-compile
1147       (progn
1148         (condition-case nil
1149             ;; Work around a bug in XEmacs 21.4
1150             (require 'byte-optimize)
1151           (error))
1152         (require 'bytecomp)
1153         (defalias 'gnus-byte-compile
1154           (lambda (form)
1155             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1156               (byte-compile form))))
1157         (gnus-byte-compile form))
1158     form))
1159
1160 (defun gnus-remassoc (key alist)
1161   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1162 The modified LIST is returned.  If the first member
1163 of LIST has a car that is `equal' to KEY, there is no way to remove it
1164 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1165 sure of changing the value of `foo'."
1166   (when alist
1167     (if (equal key (caar alist))
1168         (cdr alist)
1169       (setcdr alist (gnus-remassoc key (cdr alist)))
1170       alist)))
1171
1172 (defun gnus-update-alist-soft (key value alist)
1173   (if value
1174       (cons (cons key value) (gnus-remassoc key alist))
1175     (gnus-remassoc key alist)))
1176
1177 (defun gnus-create-info-command (node)
1178   "Create a command that will go to info NODE."
1179   `(lambda ()
1180      (interactive)
1181      ,(concat "Enter the info system at node " node)
1182      (Info-goto-node ,node)
1183      (setq gnus-info-buffer (current-buffer))
1184      (gnus-configure-windows 'info)))
1185
1186 (defun gnus-not-ignore (&rest args)
1187   t)
1188
1189 (defvar gnus-directory-sep-char-regexp "/"
1190   "The regexp of directory separator character.
1191 If you find some problem with the directory separator character, try
1192 \"[/\\\\\]\" for some systems.")
1193
1194 (defun gnus-url-unhex (x)
1195   (if (> x ?9)
1196       (if (>= x ?a)
1197           (+ 10 (- x ?a))
1198         (+ 10 (- x ?A)))
1199     (- x ?0)))
1200
1201 ;; Fixme: Do it like QP.
1202 (defun gnus-url-unhex-string (str &optional allow-newlines)
1203   "Remove %XX, embedded spaces, etc in a url.
1204 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1205 decoding of carriage returns and line feeds in the string, which is normally
1206 forbidden in URL encoding."
1207   (let ((tmp "")
1208         (case-fold-search t))
1209     (while (string-match "%[0-9a-f][0-9a-f]" str)
1210       (let* ((start (match-beginning 0))
1211              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1212              (code (+ (* 16 ch1)
1213                       (gnus-url-unhex (elt str (+ start 2))))))
1214         (setq tmp (concat
1215                    tmp (substring str 0 start)
1216                    (cond
1217                     (allow-newlines
1218                      (char-to-string code))
1219                     ((or (= code ?\n) (= code ?\r))
1220                      " ")
1221                     (t (char-to-string code))))
1222               str (substring str (match-end 0)))))
1223     (setq tmp (concat tmp str))
1224     tmp))
1225
1226 (defun gnus-make-predicate (spec)
1227   "Transform SPEC into a function that can be called.
1228 SPEC is a predicate specifier that contains stuff like `or', `and',
1229 `not', lists and functions.  The functions all take one parameter."
1230   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1231
1232 (defun gnus-make-predicate-1 (spec)
1233   (cond
1234    ((symbolp spec)
1235     `(,spec elem))
1236    ((listp spec)
1237     (if (memq (car spec) '(or and not))
1238         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1239       (error "Invalid predicate specifier: %s" spec)))))
1240
1241 (defun gnus-local-map-property (map)
1242   "Return a list suitable for a text property list specifying keymap MAP."
1243   (cond
1244    ((featurep 'xemacs)
1245     (list 'keymap map))
1246    ((>= emacs-major-version 21)
1247     (list 'keymap map))
1248    (t
1249     (list 'local-map map))))
1250
1251 (defmacro gnus-completing-read-maybe-default (prompt table &optional predicate
1252                                               require-match initial-contents
1253                                               history default)
1254   "Like `completing-read', allowing for non-existent 7th arg in older XEmacsen."
1255   `(completing-read ,prompt ,table ,predicate ,require-match
1256                     ,initial-contents ,history
1257                     ,@(if (and (featurep 'xemacs) (< emacs-minor-version 2))
1258                           ()
1259                         (list default))))
1260
1261 (defun gnus-completing-read (prompt table &optional predicate require-match
1262                                     history)
1263   (when (and history
1264              (not (boundp history)))
1265     (set history nil))
1266   (gnus-completing-read-maybe-default
1267    (if (symbol-value history)
1268        (concat prompt " (" (car (symbol-value history)) "): ")
1269      (concat prompt ": "))
1270    table
1271    predicate
1272    require-match
1273    nil
1274    history
1275    (car (symbol-value history))))
1276
1277 (defun gnus-graphic-display-p ()
1278   (or (and (fboundp 'display-graphic-p)
1279            (display-graphic-p))
1280       ;;;!!!This is bogus.  Fixme!
1281       (and (featurep 'xemacs)
1282            t)))
1283
1284 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1285 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1286
1287 (defmacro gnus-parse-without-error (&rest body)
1288   "Allow continuing onto the next line even if an error occurs."
1289   `(while (not (eobp))
1290      (condition-case ()
1291          (progn
1292            ,@body
1293            (goto-char (point-max)))
1294        (error
1295         (gnus-error 4 "Invalid data on line %d"
1296                     (count-lines (point-min) (point)))
1297         (forward-line 1)))))
1298
1299 (defun gnus-cache-file-contents (file variable function)
1300   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1301   (let ((time (nth 5 (file-attributes file)))
1302         contents value)
1303     (if (or (null (setq value (symbol-value variable)))
1304             (not (equal (car value) file))
1305             (not (equal (nth 1 value) time)))
1306         (progn
1307           (setq contents (funcall function file))
1308           (set variable (list file time contents))
1309           contents)
1310       (nth 2 value))))
1311
1312 (defun gnus-multiple-choice (prompt choice &optional idx)
1313   "Ask user a multiple choice question.
1314 CHOICE is a list of the choice char and help message at IDX."
1315   (let (tchar buf)
1316     (save-window-excursion
1317       (save-excursion
1318         (while (not tchar)
1319           (message "%s (%s): "
1320                    prompt
1321                    (concat
1322                     (mapconcat (lambda (s) (char-to-string (car s)))
1323                                choice ", ") ", ?"))
1324           (setq tchar (read-char))
1325           (when (not (assq tchar choice))
1326             (setq tchar nil)
1327             (setq buf (get-buffer-create "*Gnus Help*"))
1328             (pop-to-buffer buf)
1329             (fundamental-mode)          ; for Emacs 20.4+
1330             (buffer-disable-undo)
1331             (erase-buffer)
1332             (insert prompt ":\n\n")
1333             (let ((max -1)
1334                   (list choice)
1335                   (alist choice)
1336                   (idx (or idx 1))
1337                   (i 0)
1338                   n width pad format)
1339               ;; find the longest string to display
1340               (while list
1341                 (setq n (length (nth idx (car list))))
1342                 (unless (> max n)
1343                   (setq max n))
1344                 (setq list (cdr list)))
1345               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1346               (setq n (/ (1- (window-width)) max)) ; items per line
1347               (setq width (/ (1- (window-width)) n)) ; width of each item
1348               ;; insert `n' items, each in a field of width `width'
1349               (while alist
1350                 (if (< i n)
1351                     ()
1352                   (setq i 0)
1353                   (delete-char -1)              ; the `\n' takes a char
1354                   (insert "\n"))
1355                 (setq pad (- width 3))
1356                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1357                 (insert (format format (caar alist) (nth idx (car alist))))
1358                 (setq alist (cdr alist))
1359                 (setq i (1+ i))))))))
1360     (if (buffer-live-p buf)
1361         (kill-buffer buf))
1362     tchar))
1363
1364 (defun gnus-select-frame-set-input-focus (frame)
1365   "Select FRAME, raise it, and set input focus, if possible."
1366   (cond ((featurep 'xemacs)
1367          (raise-frame frame)
1368          (select-frame frame)
1369          (focus-frame frame))
1370         ;; The function `select-frame-set-input-focus' won't set
1371         ;; the input focus under Emacs 21.2 and X window system.
1372         ;;((fboundp 'select-frame-set-input-focus)
1373         ;; (defalias 'gnus-select-frame-set-input-focus
1374         ;;   'select-frame-set-input-focus)
1375         ;; (select-frame-set-input-focus frame))
1376         (t
1377          (raise-frame frame)
1378          (select-frame frame)
1379          (cond ((and (eq window-system 'x)
1380                      (fboundp 'x-focus-frame))
1381                 (x-focus-frame frame))
1382                ((eq window-system 'w32)
1383                 (w32-focus-frame frame)))
1384          (when focus-follows-mouse
1385            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1386
1387 (defun gnus-frame-or-window-display-name (object)
1388   "Given a frame or window, return the associated display name.
1389 Return nil otherwise."
1390   (if (featurep 'xemacs)
1391       (device-connection (dfw-device object))
1392     (if (or (framep object)
1393             (and (windowp object)
1394                  (setq object (window-frame object))))
1395         (let ((display (frame-parameter object 'display)))
1396           (if (and (stringp display)
1397                    ;; Exclude invalid display names.
1398                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1399                                  display))
1400               display)))))
1401
1402 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1403 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1404   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1405 If there are several sequences, FUNCTION is called with that many arguments,
1406 and mapping stops as soon as the shortest sequence runs out.  With just one
1407 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1408 `mapcar' function extended to arbitrary sequence types."
1409
1410   (if seqs2_n
1411       (let* ((seqs (cons seq1 seqs2_n))
1412              (cnt 0)
1413              (heads (mapcar (lambda (seq)
1414                               (make-symbol (concat "head"
1415                                                    (int-to-string
1416                                                     (setq cnt (1+ cnt))))))
1417                             seqs))
1418              (result (make-symbol "result"))
1419              (result-tail (make-symbol "result-tail")))
1420         `(let* ,(let* ((bindings (cons nil nil))
1421                        (heads heads))
1422                   (nconc bindings (list (list result '(cons nil nil))))
1423                   (nconc bindings (list (list result-tail result)))
1424                   (while heads
1425                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1426                   (cdr bindings))
1427            (while (and ,@heads)
1428              (setcdr ,result-tail (cons (funcall ,function
1429                                                  ,@(mapcar (lambda (h) (list 'car h))
1430                                                            heads))
1431                                         nil))
1432              (setq ,result-tail (cdr ,result-tail)
1433                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1434            (cdr ,result)))
1435     `(mapcar ,function ,seq1)))
1436
1437 (if (fboundp 'merge)
1438     (defalias 'gnus-merge 'merge)
1439   ;; Adapted from cl-seq.el
1440   (defun gnus-merge (type list1 list2 pred)
1441     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1442 Argument TYPE is for compatibility and ignored.
1443 Ordering of the elements is preserved according to PRED, a `less-than'
1444 predicate on the elements."
1445     (let ((res nil))
1446       (while (and list1 list2)
1447         (if (funcall pred (car list2) (car list1))
1448             (push (pop list2) res)
1449           (push (pop list1) res)))
1450       (nconc (nreverse res) list1 list2))))
1451
1452 (eval-when-compile
1453   (defvar xemacs-codename))
1454
1455 (defun gnus-emacs-version ()
1456   (let ((system-v
1457          (cond
1458           ((eq gnus-user-agent 'emacs-gnus-config)
1459            system-configuration)
1460           ((eq gnus-user-agent 'emacs-gnus-type)
1461            (symbol-name system-type))
1462           (t nil))))
1463     (cond
1464      ((eq gnus-user-agent 'gnus)
1465       nil)
1466      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1467       (concat "Emacs/" (match-string 1 emacs-version)
1468               (if system-v
1469                   (concat " (" system-v ")")
1470                 "")))
1471      ((string-match
1472        "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1473        emacs-version)
1474       (concat
1475        (match-string 1 emacs-version)
1476        (format "/%d.%d" emacs-major-version emacs-minor-version)
1477        (if (match-beginning 3)
1478            (match-string 3 emacs-version)
1479          "")
1480        (if (boundp 'xemacs-codename)
1481            (concat
1482             " (" xemacs-codename
1483             (if system-v
1484                 (concat ", " system-v ")")
1485               ")"))
1486          "")))
1487      (t emacs-version))))
1488
1489 (provide 'gnus-util)
1490
1491 ;;; gnus-util.el ends here