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