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