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