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