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