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