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