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