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