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