Synch to No Gnus 200402240748.
[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 'time-date)
45 (require 'netrc)
46
47 (eval-and-compile
48   (autoload 'message-fetch-field "message")
49   (autoload 'gnus-get-buffer-window "gnus-win")
50   (autoload 'rmail-insert-rmail-file-header "rmail")
51   (autoload 'rmail-count-new-messages "rmail")
52   (autoload 'rmail-show-message "rmail")
53   (autoload 'nnheader-narrow-to-headers "nnheader")
54   (autoload 'nnheader-replace-chars-in-string "nnheader"))
55
56 (eval-and-compile
57   (cond
58    ((fboundp 'replace-in-string)
59     (defalias 'gnus-replace-in-string 'replace-in-string))
60    ((fboundp 'replace-regexp-in-string)
61     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
62       (replace-regexp-in-string regexp newtext string nil literal)))))
63
64 ;;; bring in the netrc functions as aliases
65 (defalias 'gnus-netrc-get 'netrc-get)
66 (defalias 'gnus-netrc-machine 'netrc-machine)
67 (defalias 'gnus-parse-netrc 'netrc-parse)
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
565 (defmacro gnus-group-real-name (group)
566   "Find the real name of a foreign newsgroup."
567   `(let ((gname ,group))
568      (if (string-match "^[^:]+:" gname)
569          (substring gname (match-end 0))
570        gname)))
571
572 (defun gnus-make-sort-function (funs)
573   "Return a composite sort condition based on the functions in FUNS."
574   (cond
575    ;; Just a simple function.
576    ((functionp funs) funs)
577    ;; No functions at all.
578    ((null funs) funs)
579    ;; A list of functions.
580    ((or (cdr funs)
581         (listp (car funs)))
582     (gnus-byte-compile
583      `(lambda (t1 t2)
584         ,(gnus-make-sort-function-1 (reverse funs)))))
585    ;; A list containing just one function.
586    (t
587     (car funs))))
588
589 (defun gnus-make-sort-function-1 (funs)
590   "Return a composite sort condition based on the functions in FUNS."
591   (let ((function (car funs))
592         (first 't1)
593         (last 't2))
594     (when (consp function)
595       (cond
596        ;; Reversed spec.
597        ((eq (car function) 'not)
598         (setq function (cadr function)
599               first 't2
600               last 't1))
601        ((functionp function)
602         ;; Do nothing.
603         )
604        (t
605         (error "Invalid sort spec: %s" function))))
606     (if (cdr funs)
607         `(or (,function ,first ,last)
608              (and (not (,function ,last ,first))
609                   ,(gnus-make-sort-function-1 (cdr funs))))
610       `(,function ,first ,last))))
611
612 (defun gnus-turn-off-edit-menu (type)
613   "Turn off edit menu in `gnus-TYPE-mode-map'."
614   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
615     [menu-bar edit] 'undefined))
616
617 (defun gnus-prin1 (form)
618   "Use `prin1' on FORM in the current buffer.
619 Bind `print-quoted' and `print-readably' to t while printing."
620   (let ((print-quoted t)
621         (print-readably t)
622         (print-escape-multibyte nil)
623         print-level print-length)
624     (prin1 form (current-buffer))))
625
626 (defun gnus-prin1-to-string (form)
627   "The same as `prin1'.
628 Bind `print-quoted' and `print-readably' to t, and `print-length'
629 and `print-level' to nil."
630   (let ((print-quoted t)
631         (print-readably t)
632         (print-length nil)
633         (print-level nil))
634     (prin1-to-string form)))
635
636 (defun gnus-make-directory (directory)
637   "Make DIRECTORY (and all its parents) if it doesn't exist."
638   (require 'nnmail)
639   (let ((file-name-coding-system nnmail-pathname-coding-system))
640     (when (and directory
641                (not (file-exists-p directory)))
642       (make-directory directory t)))
643   t)
644
645 (defun gnus-write-buffer (file)
646   "Write the current buffer's contents to FILE."
647   ;; Make sure the directory exists.
648   (gnus-make-directory (file-name-directory file))
649   (let ((file-name-coding-system nnmail-pathname-coding-system))
650     ;; Write the buffer.
651     (write-region (point-min) (point-max) file nil 'quietly)))
652
653 (defun gnus-write-buffer-as-binary (file)
654   "Write the current buffer's contents to FILE without code conversion."
655   ;; Make sure the directory exists.
656   (gnus-make-directory (file-name-directory file))
657   ;; Write the buffer.
658   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
659
660 (defun gnus-write-buffer-as-coding-system (coding-system file)
661   "Write the current buffer's contents to FILE with code conversion."
662   ;; Make sure the directory exists.
663   (gnus-make-directory (file-name-directory file))
664   ;; Write the buffer.
665   (write-region-as-coding-system
666    coding-system (point-min) (point-max) file nil 'quietly))
667
668 (defun gnus-delete-file (file)
669   "Delete FILE if it exists."
670   (when (file-exists-p file)
671     (delete-file file)))
672
673 (defun gnus-strip-whitespace (string)
674   "Return STRING stripped of all whitespace."
675   (while (string-match "[\r\n\t ]+" string)
676     (setq string (replace-match "" t t string)))
677   string)
678
679 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
680   "The same as `put-text-property', but don't put this prop on any newlines in the region."
681   (save-match-data
682     (save-excursion
683       (save-restriction
684         (goto-char beg)
685         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
686           (gnus-put-text-property beg (match-beginning 0) prop val)
687           (setq beg (point)))
688         (gnus-put-text-property beg (point) prop val)))))
689
690 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
691   "The same as `put-text-property', but don't put this prop on any newlines in the region."
692   (save-match-data
693     (save-excursion
694       (save-restriction
695         (goto-char beg)
696         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
697           (gnus-overlay-put
698            (gnus-make-overlay beg (match-beginning 0))
699            prop val)
700           (setq beg (point)))
701         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
702
703 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
704                                                                    prop val)
705   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
706   (let ((b beg))
707     (while (/= b end)
708       (when (get-text-property b 'gnus-face)
709         (setq b (next-single-property-change b 'gnus-face nil end)))
710       (when (/= b end)
711         (inline
712           (gnus-put-text-property
713            b (setq b (next-single-property-change b 'gnus-face nil end))
714            prop val))))))
715
716 (defmacro gnus-faces-at (position)
717   "Return a list of faces at POSITION."
718   (if (featurep 'xemacs)
719       `(let ((pos ,position))
720          (mapcar-extents 'extent-face
721                          nil (current-buffer) pos pos nil 'face))
722     `(let ((pos ,position))
723        (delq nil (cons (get-text-property pos 'face)
724                        (mapcar
725                         (lambda (overlay)
726                           (overlay-get overlay 'face))
727                         (overlays-at pos)))))))
728
729 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
730 ;;; The primary idea here is to try to protect internal datastructures
731 ;;; from becoming corrupted when the user hits C-g, or if a hook or
732 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
733 ;;; updated at the same time, or information can be lost.
734
735 (defvar gnus-atomic-be-safe t
736   "If t, certain operations will be protected from interruption by C-g.")
737
738 (defmacro gnus-atomic-progn (&rest forms)
739   "Evaluate FORMS atomically, which means to protect the evaluation
740 from being interrupted by the user.  An error from the forms themselves
741 will return without finishing the operation.  Since interrupts from
742 the user are disabled, it is recommended that only the most minimal
743 operations are performed by FORMS.  If you wish to assign many
744 complicated values atomically, compute the results into temporary
745 variables and then do only the assignment atomically."
746   `(let ((inhibit-quit gnus-atomic-be-safe))
747      ,@forms))
748
749 (put 'gnus-atomic-progn 'lisp-indent-function 0)
750
751 (defmacro gnus-atomic-progn-assign (protect &rest forms)
752   "Evaluate FORMS, but insure that the variables listed in PROTECT
753 are not changed if anything in FORMS signals an error or otherwise
754 non-locally exits.  The variables listed in PROTECT are updated atomically.
755 It is safe to use gnus-atomic-progn-assign with long computations.
756
757 Note that if any of the symbols in PROTECT were unbound, they will be
758 set to nil on a successful assignment.  In case of an error or other
759 non-local exit, it will still be unbound."
760   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
761                                                   (concat (symbol-name x)
762                                                           "-tmp"))
763                                                  x))
764                                protect))
765          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
766                                temp-sym-map))
767          (temp-sym-let (mapcar (lambda (x) (list (car x)
768                                                  `(and (boundp ',(cadr x))
769                                                        ,(cadr x))))
770                                temp-sym-map))
771          (sym-temp-let sym-temp-map)
772          (temp-sym-assign (apply 'append temp-sym-map))
773          (sym-temp-assign (apply 'append sym-temp-map))
774          (result (make-symbol "result-tmp")))
775     `(let (,@temp-sym-let
776            ,result)
777        (let ,sym-temp-let
778          (setq ,result (progn ,@forms))
779          (setq ,@temp-sym-assign))
780        (let ((inhibit-quit gnus-atomic-be-safe))
781          (setq ,@sym-temp-assign))
782        ,result)))
783
784 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
785 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
786
787 (defmacro gnus-atomic-setq (&rest pairs)
788   "Similar to setq, except that the real symbols are only assigned when
789 there are no errors.  And when the real symbols are assigned, they are
790 done so atomically.  If other variables might be changed via side-effect,
791 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
792 with potentially long computations."
793   (let ((tpairs pairs)
794         syms)
795     (while tpairs
796       (push (car tpairs) syms)
797       (setq tpairs (cddr tpairs)))
798     `(gnus-atomic-progn-assign ,syms
799        (setq ,@pairs))))
800
801 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
802
803
804 ;;; Functions for saving to babyl/mail files.
805
806 (eval-when-compile
807   (condition-case nil
808       (progn
809         (require 'rmail)
810         (autoload 'rmail-update-summary "rmailsum"))
811     (error
812      (define-compiler-macro rmail-select-summary (&rest body)
813        ;; Rmail of the XEmacs version is supplied by the package, and
814        ;; requires tm and apel packages.  However, there may be those
815        ;; who haven't installed those packages.  This macro helps such
816        ;; people even if they install those packages later.
817        `(eval '(rmail-select-summary ,@body)))
818      ;; If there's rmail but there's no tm (or there's apel of the
819      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
820      ;; version fails halfway, however it provides the rmail-select-summary
821      ;; macro which uses the following functions:
822      (autoload 'rmail-summary-displayed "rmail")
823      (autoload 'rmail-maybe-display-summary "rmail")))
824   (defvar rmail-default-rmail-file)
825   (defvar mm-text-coding-system))
826
827 (defun gnus-output-to-rmail (filename &optional ask)
828   "Append the current article to an Rmail file named FILENAME."
829   (require 'rmail)
830   (require 'mm-util)
831   ;; Most of these codes are borrowed from rmailout.el.
832   (setq filename (expand-file-name filename))
833   (setq rmail-default-rmail-file filename)
834   (let ((artbuf (current-buffer))
835         (tmpbuf (get-buffer-create " *Gnus-output*")))
836     (save-excursion
837       (or (get-file-buffer filename)
838           (file-exists-p filename)
839           (if (or (not ask)
840                   (gnus-yes-or-no-p
841                    (concat "\"" filename "\" does not exist, create it? ")))
842               (let ((file-buffer (create-file-buffer filename)))
843                 (save-excursion
844                   (set-buffer file-buffer)
845                   (rmail-insert-rmail-file-header)
846                   (let ((require-final-newline nil))
847                     (gnus-write-buffer-as-coding-system
848                      nnheader-text-coding-system filename)))
849                 (kill-buffer file-buffer))
850             (error "Output file does not exist")))
851       (set-buffer tmpbuf)
852       (erase-buffer)
853       (insert-buffer-substring artbuf)
854       (gnus-convert-article-to-rmail)
855       ;; Decide whether to append to a file or to an Emacs buffer.
856       (let ((outbuf (get-file-buffer filename)))
857         (if (not outbuf)
858             (let ((file-name-coding-system nnmail-pathname-coding-system))
859               (write-region-as-binary (point-min) (point-max)
860                                       filename 'append))
861           ;; File has been visited, in buffer OUTBUF.
862           (set-buffer outbuf)
863           (let ((buffer-read-only nil)
864                 (msg (and (boundp 'rmail-current-message)
865                           (symbol-value 'rmail-current-message))))
866             ;; If MSG is non-nil, buffer is in RMAIL mode.
867             (when msg
868               (widen)
869               (narrow-to-region (point-max) (point-max)))
870             (insert-buffer-substring tmpbuf)
871             (when msg
872               (goto-char (point-min))
873               (widen)
874               (search-backward "\n\^_")
875               (narrow-to-region (point) (point-max))
876               (rmail-count-new-messages t)
877               (when (rmail-summary-exists)
878                 (rmail-select-summary
879                  (rmail-update-summary)))
880               (rmail-count-new-messages t)
881               (rmail-show-message msg))
882             (save-buffer)))))
883     (kill-buffer tmpbuf)))
884
885 (defun gnus-output-to-mail (filename &optional ask)
886   "Append the current article to a mail file named FILENAME."
887   (setq filename (expand-file-name filename))
888   (let ((artbuf (current-buffer))
889         (tmpbuf (get-buffer-create " *Gnus-output*")))
890     (save-excursion
891       ;; Create the file, if it doesn't exist.
892       (when (and (not (get-file-buffer filename))
893                  (not (file-exists-p filename)))
894         (if (or (not ask)
895                 (gnus-y-or-n-p
896                  (concat "\"" filename "\" does not exist, create it? ")))
897             (let ((file-buffer (create-file-buffer filename)))
898               (save-excursion
899                 (set-buffer file-buffer)
900                 (let ((require-final-newline nil))
901                   (gnus-write-buffer-as-coding-system
902                    nnheader-text-coding-system filename)))
903               (kill-buffer file-buffer))
904           (error "Output file does not exist")))
905       (set-buffer tmpbuf)
906       (erase-buffer)
907       (insert-buffer-substring artbuf)
908       (goto-char (point-min))
909       (if (looking-at "From ")
910           (forward-line 1)
911         (insert "From nobody " (current-time-string) "\n"))
912       (let (case-fold-search)
913         (while (re-search-forward "^From " nil t)
914           (beginning-of-line)
915           (insert ">")))
916       ;; Decide whether to append to a file or to an Emacs buffer.
917       (let ((outbuf (get-file-buffer filename)))
918         (if (not outbuf)
919             (let ((buffer-read-only nil))
920               (save-excursion
921                 (goto-char (point-max))
922                 (forward-char -2)
923                 (unless (looking-at "\n\n")
924                   (goto-char (point-max))
925                   (unless (bolp)
926                     (insert "\n"))
927                   (insert "\n"))
928                 (goto-char (point-max))
929                 (let ((file-name-coding-system nnmail-pathname-coding-system))
930                   (write-region-as-binary (point-min) (point-max)
931                                           filename 'append))))
932           ;; File has been visited, in buffer OUTBUF.
933           (set-buffer outbuf)
934           (let ((buffer-read-only nil))
935             (goto-char (point-max))
936             (unless (eobp)
937               (insert "\n"))
938             (insert "\n")
939             (insert-buffer-substring tmpbuf)))))
940     (kill-buffer tmpbuf)))
941
942 (defun gnus-convert-article-to-rmail ()
943   "Convert article in current buffer to Rmail message format."
944   (let ((buffer-read-only nil))
945     ;; Convert article directly into Babyl format.
946     (goto-char (point-min))
947     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
948     (while (search-forward "\n\^_" nil t) ;single char
949       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
950     (goto-char (point-max))
951     (insert "\^_")))
952
953 (defun gnus-map-function (funs arg)
954   "Apply the result of the first function in FUNS to the second, and so on.
955 ARG is passed to the first function."
956   (while funs
957     (setq arg (funcall (pop funs) arg)))
958   arg)
959
960 (defun gnus-run-hooks (&rest funcs)
961   "Does the same as `run-hooks', but saves the current buffer."
962   (save-current-buffer
963     (apply 'run-hooks funcs)))
964
965 ;;; Various
966
967 (defvar gnus-group-buffer)              ; Compiler directive
968 (defun gnus-alive-p ()
969   "Say whether Gnus is running or not."
970   (and (boundp 'gnus-group-buffer)
971        (get-buffer gnus-group-buffer)
972        (save-excursion
973          (set-buffer gnus-group-buffer)
974          (eq major-mode 'gnus-group-mode))))
975
976 (defun gnus-remove-duplicates (list)
977   (let (new)
978     (while list
979       (or (member (car list) new)
980           (setq new (cons (car list) new)))
981       (setq list (cdr list)))
982     (nreverse new)))
983
984 (defun gnus-remove-if (predicate list)
985   "Return a copy of LIST with all items satisfying PREDICATE removed."
986   (let (out)
987     (while list
988       (unless (funcall predicate (car list))
989         (push (car list) out))
990       (setq list (cdr list)))
991     (nreverse out)))
992
993 (if (fboundp 'assq-delete-all)
994     (defalias 'gnus-delete-alist 'assq-delete-all)
995   (defun gnus-delete-alist (key alist)
996     "Delete from ALIST all elements whose car is KEY.
997 Return the modified alist."
998     (let (entry)
999       (while (setq entry (assq key alist))
1000         (setq alist (delq entry alist)))
1001       alist)))
1002
1003 (defmacro gnus-pull (key alist &optional assoc-p)
1004   "Modify ALIST to be without KEY."
1005   (unless (symbolp alist)
1006     (error "Not a symbol: %s" alist))
1007   (let ((fun (if assoc-p 'assoc 'assq)))
1008     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1009
1010 (defun gnus-globalify-regexp (re)
1011   "Return a regexp that matches a whole line, iff RE matches a part of it."
1012   (concat (unless (string-match "^\\^" re) "^.*")
1013           re
1014           (unless (string-match "\\$$" re) ".*$")))
1015
1016 (defun gnus-set-window-start (&optional point)
1017   "Set the window start to POINT, or (point) if nil."
1018   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1019     (when win
1020       (set-window-start win (or point (point))))))
1021
1022 (defun gnus-annotation-in-region-p (b e)
1023   (if (= b e)
1024       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1025     (text-property-any b e 'gnus-undeletable t)))
1026
1027 (defun gnus-or (&rest elems)
1028   "Return non-nil if any of the elements are non-nil."
1029   (catch 'found
1030     (while elems
1031       (when (pop elems)
1032         (throw 'found t)))))
1033
1034 (defun gnus-and (&rest elems)
1035   "Return non-nil if all of the elements are non-nil."
1036   (catch 'found
1037     (while elems
1038       (unless (pop elems)
1039         (throw 'found nil)))
1040     t))
1041
1042 (defun gnus-write-active-file (file hashtb &optional full-names)
1043   (let ((coding-system-for-write nnmail-active-file-coding-system))
1044     (with-temp-file file
1045       (mapatoms
1046        (lambda (sym)
1047          (when (and sym
1048                     (boundp sym)
1049                     (symbol-value sym))
1050            (insert (format "%S %d %d y\n"
1051                            (if full-names
1052                                sym
1053                              (intern (gnus-group-real-name (symbol-name sym))))
1054                            (or (cdr (symbol-value sym))
1055                                (car (symbol-value sym)))
1056                            (car (symbol-value sym))))))
1057        hashtb)
1058       (goto-char (point-max))
1059       (while (search-backward "\\." nil t)
1060         (delete-char 1)))))
1061
1062 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1063 (defmacro gnus-with-output-to-file (file &rest body)
1064   (let ((buffer (make-symbol "output-buffer"))
1065         (size (make-symbol "output-buffer-size"))
1066         (leng (make-symbol "output-buffer-length"))
1067         (append (make-symbol "output-buffer-append")))
1068     `(let* ((,size 131072)
1069             (,buffer (make-string ,size 0))
1070             (,leng 0)
1071             (,append nil)
1072             (standard-output
1073              (lambda (c)
1074                (aset ,buffer ,leng c)
1075                    
1076                (if (= ,size (setq ,leng (1+ ,leng)))
1077                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1078                           (setq ,leng 0
1079                                 ,append t))))))
1080        ,@body
1081        (when (> ,leng 0)
1082          (let ((coding-system-for-write 'no-conversion))
1083          (write-region (substring ,buffer 0 ,leng) nil ,file
1084                        ,append 'no-msg))))))
1085
1086 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1087 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1088
1089 (if (fboundp 'union)
1090     (defalias 'gnus-union 'union)
1091   (defun gnus-union (l1 l2)
1092     "Set union of lists L1 and L2."
1093     (cond ((null l1) l2)
1094           ((null l2) l1)
1095           ((equal l1 l2) l1)
1096           (t
1097            (or (>= (length l1) (length l2))
1098                (setq l1 (prog1 l2 (setq l2 l1))))
1099            (while l2
1100              (or (member (car l2) l1)
1101                  (push (car l2) l1))
1102              (pop l2))
1103            l1))))
1104
1105 (defun gnus-add-text-properties-when
1106   (property value start end properties &optional object)
1107   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1108   (let (point)
1109     (while (and start
1110                 (< start end) ;; XEmacs will loop for every when start=end.
1111                 (setq point (text-property-not-all start end property value)))
1112       (gnus-add-text-properties start point properties object)
1113       (setq start (text-property-any point end property value)))
1114     (if start
1115         (gnus-add-text-properties start end properties object))))
1116
1117 (defun gnus-remove-text-properties-when
1118   (property value start end properties &optional object)
1119   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1120   (let (point)
1121     (while (and start
1122                 (< start end)
1123                 (setq point (text-property-not-all start end property value)))
1124       (remove-text-properties start point properties object)
1125       (setq start (text-property-any point end property value)))
1126     (if start
1127         (remove-text-properties start end properties object))
1128     t))
1129
1130 ;; This might use `compare-strings' to reduce consing in the
1131 ;; case-insensitive case, but it has to cope with null args.
1132 ;; (`string-equal' uses symbol print names.)
1133 (defun gnus-string-equal (x y)
1134   "Like `string-equal', except it compares case-insensitively."
1135   (and (= (length x) (length y))
1136        (or (string-equal x y)
1137            (string-equal (downcase x) (downcase y)))))
1138
1139 (defcustom gnus-use-byte-compile t
1140   "If non-nil, byte-compile crucial run-time code.
1141 Setting it to nil has no effect after the first time `gnus-byte-compile'
1142 is run."
1143   :type 'boolean
1144   :version "21.1"
1145   :group 'gnus-various)
1146
1147 (defun gnus-byte-compile (form)
1148   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1149   (if gnus-use-byte-compile
1150       (progn
1151         (condition-case nil
1152             ;; Work around a bug in XEmacs 21.4
1153             (require 'byte-optimize)
1154           (error))
1155         (require 'bytecomp)
1156         (defalias 'gnus-byte-compile
1157           (lambda (form)
1158             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1159               (byte-compile form))))
1160         (gnus-byte-compile form))
1161     form))
1162
1163 (defun gnus-remassoc (key alist)
1164   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1165 The modified LIST is returned.  If the first member
1166 of LIST has a car that is `equal' to KEY, there is no way to remove it
1167 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1168 sure of changing the value of `foo'."
1169   (when alist
1170     (if (equal key (caar alist))
1171         (cdr alist)
1172       (setcdr alist (gnus-remassoc key (cdr alist)))
1173       alist)))
1174
1175 (defun gnus-update-alist-soft (key value alist)
1176   (if value
1177       (cons (cons key value) (gnus-remassoc key alist))
1178     (gnus-remassoc key alist)))
1179
1180 (defun gnus-create-info-command (node)
1181   "Create a command that will go to info NODE."
1182   `(lambda ()
1183      (interactive)
1184      ,(concat "Enter the info system at node " node)
1185      (Info-goto-node ,node)
1186      (setq gnus-info-buffer (current-buffer))
1187      (gnus-configure-windows 'info)))
1188
1189 (defun gnus-not-ignore (&rest args)
1190   t)
1191
1192 (defvar gnus-directory-sep-char-regexp "/"
1193   "The regexp of directory separator character.
1194 If you find some problem with the directory separator character, try
1195 \"[/\\\\\]\" for some systems.")
1196
1197 (defun gnus-url-unhex (x)
1198   (if (> x ?9)
1199       (if (>= x ?a)
1200           (+ 10 (- x ?a))
1201         (+ 10 (- x ?A)))
1202     (- x ?0)))
1203
1204 ;; Fixme: Do it like QP.
1205 (defun gnus-url-unhex-string (str &optional allow-newlines)
1206   "Remove %XX, embedded spaces, etc in a url.
1207 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1208 decoding of carriage returns and line feeds in the string, which is normally
1209 forbidden in URL encoding."
1210   (let ((tmp "")
1211         (case-fold-search t))
1212     (while (string-match "%[0-9a-f][0-9a-f]" str)
1213       (let* ((start (match-beginning 0))
1214              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1215              (code (+ (* 16 ch1)
1216                       (gnus-url-unhex (elt str (+ start 2))))))
1217         (setq tmp (concat
1218                    tmp (substring str 0 start)
1219                    (cond
1220                     (allow-newlines
1221                      (char-to-string code))
1222                     ((or (= code ?\n) (= code ?\r))
1223                      " ")
1224                     (t (char-to-string code))))
1225               str (substring str (match-end 0)))))
1226     (setq tmp (concat tmp str))
1227     tmp))
1228
1229 (defun gnus-make-predicate (spec)
1230   "Transform SPEC into a function that can be called.
1231 SPEC is a predicate specifier that contains stuff like `or', `and',
1232 `not', lists and functions.  The functions all take one parameter."
1233   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1234
1235 (defun gnus-make-predicate-1 (spec)
1236   (cond
1237    ((symbolp spec)
1238     `(,spec elem))
1239    ((listp spec)
1240     (if (memq (car spec) '(or and not))
1241         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1242       (error "Invalid predicate specifier: %s" spec)))))
1243
1244 (defun gnus-completing-read (prompt table &optional predicate require-match
1245                                     history)
1246   (when (and history
1247              (not (boundp history)))
1248     (set history nil))
1249   (completing-read
1250    (if (symbol-value history)
1251        (concat prompt " (" (car (symbol-value history)) "): ")
1252      (concat prompt ": "))
1253    table
1254    predicate
1255    require-match
1256    nil
1257    history
1258    (car (symbol-value history))))
1259
1260 (defun gnus-graphic-display-p ()
1261   (or (and (fboundp 'display-graphic-p)
1262            (display-graphic-p))
1263       ;;;!!!This is bogus.  Fixme!
1264       (and (featurep 'xemacs)
1265            t)))
1266
1267 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1268 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1269
1270 (defmacro gnus-parse-without-error (&rest body)
1271   "Allow continuing onto the next line even if an error occurs."
1272   `(while (not (eobp))
1273      (condition-case ()
1274          (progn
1275            ,@body
1276            (goto-char (point-max)))
1277        (error
1278         (gnus-error 4 "Invalid data on line %d"
1279                     (count-lines (point-min) (point)))
1280         (forward-line 1)))))
1281
1282 (defun gnus-cache-file-contents (file variable function)
1283   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1284   (let ((time (nth 5 (file-attributes file)))
1285         contents value)
1286     (if (or (null (setq value (symbol-value variable)))
1287             (not (equal (car value) file))
1288             (not (equal (nth 1 value) time)))
1289         (progn
1290           (setq contents (funcall function file))
1291           (set variable (list file time contents))
1292           contents)
1293       (nth 2 value))))
1294
1295 (defun gnus-multiple-choice (prompt choice &optional idx)
1296   "Ask user a multiple choice question.
1297 CHOICE is a list of the choice char and help message at IDX."
1298   (let (tchar buf)
1299     (save-window-excursion
1300       (save-excursion
1301         (while (not tchar)
1302           (message "%s (%s): "
1303                    prompt
1304                    (concat
1305                     (mapconcat (lambda (s) (char-to-string (car s)))
1306                                choice ", ") ", ?"))
1307           (setq tchar (read-char))
1308           (when (not (assq tchar choice))
1309             (setq tchar nil)
1310             (setq buf (get-buffer-create "*Gnus Help*"))
1311             (pop-to-buffer buf)
1312             (fundamental-mode)          ; for Emacs 20.4+
1313             (buffer-disable-undo)
1314             (erase-buffer)
1315             (insert prompt ":\n\n")
1316             (let ((max -1)
1317                   (list choice)
1318                   (alist choice)
1319                   (idx (or idx 1))
1320                   (i 0)
1321                   n width pad format)
1322               ;; find the longest string to display
1323               (while list
1324                 (setq n (length (nth idx (car list))))
1325                 (unless (> max n)
1326                   (setq max n))
1327                 (setq list (cdr list)))
1328               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1329               (setq n (/ (1- (window-width)) max)) ; items per line
1330               (setq width (/ (1- (window-width)) n)) ; width of each item
1331               ;; insert `n' items, each in a field of width `width'
1332               (while alist
1333                 (if (< i n)
1334                     ()
1335                   (setq i 0)
1336                   (delete-char -1)              ; the `\n' takes a char
1337                   (insert "\n"))
1338                 (setq pad (- width 3))
1339                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1340                 (insert (format format (caar alist) (nth idx (car alist))))
1341                 (setq alist (cdr alist))
1342                 (setq i (1+ i))))))))
1343     (if (buffer-live-p buf)
1344         (kill-buffer buf))
1345     tchar))
1346
1347 (defun gnus-select-frame-set-input-focus (frame)
1348   "Select FRAME, raise it, and set input focus, if possible."
1349   (cond ((featurep 'xemacs)
1350          (raise-frame frame)
1351          (select-frame frame)
1352          (focus-frame frame))
1353         ;; The function `select-frame-set-input-focus' won't set
1354         ;; the input focus under Emacs 21.2 and X window system.
1355         ;;((fboundp 'select-frame-set-input-focus)
1356         ;; (defalias 'gnus-select-frame-set-input-focus
1357         ;;   'select-frame-set-input-focus)
1358         ;; (select-frame-set-input-focus frame))
1359         (t
1360          (raise-frame frame)
1361          (select-frame frame)
1362          (cond ((and (eq window-system 'x)
1363                      (fboundp 'x-focus-frame))
1364                 (x-focus-frame frame))
1365                ((eq window-system 'w32)
1366                 (w32-focus-frame frame)))
1367          (when (or (not (boundp 'focus-follows-mouse))
1368                    (symbol-value 'focus-follows-mouse))
1369            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1370
1371 (unless (fboundp 'frame-parameter)
1372   (defalias 'frame-parameter
1373     (lambda (frame parameter)
1374       "Return FRAME's value for parameter PARAMETER.
1375 If FRAME is nil, describe the currently selected frame."
1376       (cdr (assq parameter (frame-parameters frame))))))
1377
1378 (defun gnus-frame-or-window-display-name (object)
1379   "Given a frame or window, return the associated display name.
1380 Return nil otherwise."
1381   (if (featurep 'xemacs)
1382       (device-connection (dfw-device object))
1383     (if (or (framep object)
1384             (and (windowp object)
1385                  (setq object (window-frame object))))
1386         (let ((display (frame-parameter object 'display)))
1387           (if (and (stringp display)
1388                    ;; Exclude invalid display names.
1389                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1390                                  display))
1391               display)))))
1392
1393 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1394 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1395   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1396 If there are several sequences, FUNCTION is called with that many arguments,
1397 and mapping stops as soon as the shortest sequence runs out.  With just one
1398 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1399 `mapcar' function extended to arbitrary sequence types."
1400
1401   (if seqs2_n
1402       (let* ((seqs (cons seq1 seqs2_n))
1403              (cnt 0)
1404              (heads (mapcar (lambda (seq)
1405                               (make-symbol (concat "head"
1406                                                    (int-to-string
1407                                                     (setq cnt (1+ cnt))))))
1408                             seqs))
1409              (result (make-symbol "result"))
1410              (result-tail (make-symbol "result-tail")))
1411         `(let* ,(let* ((bindings (cons nil nil))
1412                        (heads heads))
1413                   (nconc bindings (list (list result '(cons nil nil))))
1414                   (nconc bindings (list (list result-tail result)))
1415                   (while heads
1416                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1417                   (cdr bindings))
1418            (while (and ,@heads)
1419              (setcdr ,result-tail (cons (funcall ,function
1420                                                  ,@(mapcar (lambda (h) (list 'car h))
1421                                                            heads))
1422                                         nil))
1423              (setq ,result-tail (cdr ,result-tail)
1424                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1425            (cdr ,result)))
1426     `(mapcar ,function ,seq1)))
1427
1428 (if (fboundp 'merge)
1429     (defalias 'gnus-merge 'merge)
1430   ;; Adapted from cl-seq.el
1431   (defun gnus-merge (type list1 list2 pred)
1432     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1433 Argument TYPE is for compatibility and ignored.
1434 Ordering of the elements is preserved according to PRED, a `less-than'
1435 predicate on the elements."
1436     (let ((res nil))
1437       (while (and list1 list2)
1438         (if (funcall pred (car list2) (car list1))
1439             (push (pop list2) res)
1440           (push (pop list1) res)))
1441       (nconc (nreverse res) list1 list2))))
1442
1443 (eval-when-compile
1444   (defvar xemacs-codename))
1445
1446 (defun gnus-emacs-version ()
1447   "Stringified Emacs version."
1448   (let ((system-v
1449          (cond
1450           ((eq gnus-user-agent 'emacs-gnus-config)
1451            system-configuration)
1452           ((eq gnus-user-agent 'emacs-gnus-type)
1453            (symbol-name system-type))
1454           (t nil))))
1455     (cond
1456      ((eq gnus-user-agent 'gnus)
1457       nil)
1458      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1459       (concat "Emacs/" (match-string 1 emacs-version)
1460               (if system-v
1461                   (concat " (" system-v ")")
1462                 "")))
1463      ((string-match
1464        "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1465        emacs-version)
1466       (concat
1467        (match-string 1 emacs-version)
1468        (format "/%d.%d" emacs-major-version emacs-minor-version)
1469        (if (match-beginning 3)
1470            (match-string 3 emacs-version)
1471          "")
1472        (if (boundp 'xemacs-codename)
1473            (concat
1474             " (" xemacs-codename
1475             (if system-v
1476                 (concat ", " system-v ")")
1477               ")"))
1478          "")))
1479      (t emacs-version))))
1480
1481 (provide 'gnus-util)
1482
1483 ;;; gnus-util.el ends here