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