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