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