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