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