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