Merge from emacs--devo--0
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; Keywords: news
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Nothing in this file depends on any other parts of Gnus -- all
27 ;; functions and macros in this file are utility functions that are
28 ;; used by Gnus and may be used by any other package without loading
29 ;; Gnus first.
30
31 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
32 ;; autoloads and defvars below...]
33
34 ;;; Code:
35
36 ;; For Emacs < 22.2.
37 (eval-and-compile
38   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
39 (eval-when-compile
40   (require 'cl))
41 ;; Fixme: this should be a gnus variable, not nnmail-.
42 (defvar nnmail-pathname-coding-system)
43 (defvar nnmail-active-file-coding-system)
44
45 ;; Inappropriate references to other parts of Gnus.
46 (defvar gnus-emphasize-whitespace-regexp)
47 (defvar gnus-original-article-buffer)
48 (defvar gnus-user-agent)
49
50 (require 'time-date)
51 (require 'netrc)
52
53 (autoload 'message-fetch-field "message")
54 (autoload 'gnus-get-buffer-window "gnus-win")
55 (autoload 'rmail-insert-rmail-file-header "rmail")
56 (autoload 'rmail-count-new-messages "rmail")
57 (autoload 'rmail-show-message "rmail")
58 (autoload 'nnheader-narrow-to-headers "nnheader")
59 (autoload 'nnheader-replace-chars-in-string "nnheader")
60
61 (eval-and-compile
62   (cond
63    ;; Prefer `replace-regexp-in-string' (present in Emacs, XEmacs 21.5,
64    ;; SXEmacs 22.1.4) over `replace-in-string'.  The latter leads to inf-loops
65    ;; on empty matches:
66    ;;   (replace-in-string "foo" "/*$" "/")
67    ;;   (replace-in-string "xe" "\\(x\\)?" "")
68    ((fboundp 'replace-regexp-in-string)
69     (defun gnus-replace-in-string  (string regexp newtext &optional literal)
70       "Replace all matches for REGEXP with NEWTEXT in STRING.
71 If LITERAL is non-nil, insert NEWTEXT literally.  Return a new
72 string containing the replacements.
73
74 This is a compatibility function for different Emacsen."
75       (replace-regexp-in-string regexp newtext string nil literal)))
76    ((fboundp 'replace-in-string)
77     (defalias 'gnus-replace-in-string 'replace-in-string))))
78
79 (defun gnus-boundp (variable)
80   "Return non-nil if VARIABLE is bound and non-nil."
81   (and (boundp variable)
82        (symbol-value variable)))
83
84 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
85   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
86   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
87         (w (make-symbol "w"))
88         (buf (make-symbol "buf")))
89     `(let* ((,tempvar (selected-window))
90             (,buf ,buffer)
91             (,w (gnus-get-buffer-window ,buf 'visible)))
92        (unwind-protect
93            (progn
94              (if ,w
95                  (progn
96                    (select-window ,w)
97                    (set-buffer (window-buffer ,w)))
98                (pop-to-buffer ,buf))
99              ,@forms)
100          (select-window ,tempvar)))))
101
102 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
103 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
104
105 (defmacro gnus-intern-safe (string hashtable)
106   "Get hash value.  Arguments are STRING and HASHTABLE."
107   `(let ((symbol (intern ,string ,hashtable)))
108      (or (boundp symbol)
109          (set symbol nil))
110      symbol))
111
112 (defsubst gnus-goto-char (point)
113   (and point (goto-char point)))
114
115 (defmacro gnus-buffer-exists-p (buffer)
116   `(let ((buffer ,buffer))
117      (when buffer
118        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
119                 buffer))))
120
121 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
122 ;; XEmacs.  In Emacs we don't need to call `make-local-hook' first.
123 ;; It's harmless, though, so the main purpose of this alias is to shut
124 ;; up the byte compiler.
125 (defalias 'gnus-make-local-hook
126   (if (eq (get 'make-local-hook 'byte-compile)
127           'byte-compile-obsolete)
128       'ignore                           ; Emacs
129     'make-local-hook))                  ; XEmacs
130
131 (defun gnus-delete-first (elt list)
132   "Delete by side effect the first occurrence of ELT as a member of LIST."
133   (if (equal (car list) elt)
134       (cdr list)
135     (let ((total list))
136       (while (and (cdr list)
137                   (not (equal (cadr list) elt)))
138         (setq list (cdr list)))
139       (when (cdr list)
140         (setcdr list (cddr list)))
141       total)))
142
143 ;; Delete the current line (and the next N lines).
144 (defmacro gnus-delete-line (&optional n)
145   `(delete-region (point-at-bol)
146                   (progn (forward-line ,(or n 1)) (point))))
147
148 (defun gnus-byte-code (func)
149   "Return a form that can be `eval'ed based on FUNC."
150   (let ((fval (indirect-function func)))
151     (if (byte-code-function-p fval)
152         (let ((flist (append fval nil)))
153           (setcar flist 'byte-code)
154           flist)
155       (cons 'progn (cddr fval)))))
156
157 (defun gnus-extract-address-components (from)
158   "Extract address components from a From header.
159 Given an RFC-822 address FROM, extract full name and canonical address.
160 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).  Much more simple
161 solution than `mail-extract-address-components', which works much better, but
162 is slower."
163   (let (name address)
164     ;; First find the address - the thing with the @ in it.  This may
165     ;; not be accurate in mail addresses, but does the trick most of
166     ;; the time in news messages.
167     (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
168            ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
169            ;; correctly.
170            (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
171            (setq address (substring from (match-beginning 1) (match-end 1))))
172           ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
173            (setq address (substring from (match-beginning 0) (match-end 0)))))
174     ;; Then we check whether the "name <address>" format is used.
175     (and address
176          ;; Linear white space is not required.
177          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
178          (and (setq name (substring from 0 (match-beginning 0)))
179               ;; Strip any quotes from the name.
180               (string-match "^\".*\"$" name)
181               (setq name (substring name 1 (1- (match-end 0))))))
182     ;; If not, then "address (name)" is used.
183     (or name
184         (and (string-match "(.+)" from)
185              (setq name (substring from (1+ (match-beginning 0))
186                                    (1- (match-end 0)))))
187         (and (string-match "()" from)
188              (setq name address))
189         ;; XOVER might not support folded From headers.
190         (and (string-match "(.*" from)
191              (setq name (substring from (1+ (match-beginning 0))
192                                    (match-end 0)))))
193     (list (if (string= name "") nil name) (or address from))))
194
195 (defun gnus-extract-address-component-name (from)
196   "Extract name from a From header.
197 Uses `gnus-extract-address-components'."
198   (nth 0 (gnus-extract-address-components from)))
199
200 (defun gnus-extract-address-component-email (from)
201   "Extract e-mail address from a From header.
202 Uses `gnus-extract-address-components'."
203   (nth 1 (gnus-extract-address-components from)))
204
205 (defun gnus-fetch-field (field)
206   "Return the value of the header FIELD of current article."
207   (save-excursion
208     (save-restriction
209       (let ((inhibit-point-motion-hooks t))
210         (nnheader-narrow-to-headers)
211         (message-fetch-field field)))))
212
213 (defun gnus-fetch-original-field (field)
214   "Fetch FIELD from the original version of the current article."
215   (with-current-buffer gnus-original-article-buffer
216     (gnus-fetch-field field)))
217
218
219 (defun gnus-goto-colon ()
220   (beginning-of-line)
221   (let ((eol (point-at-eol)))
222     (goto-char (or (text-property-any (point) eol 'gnus-position t)
223                    (search-forward ":" eol t)
224                    (point)))))
225
226 (declare-function gnus-find-method-for-group "gnus" (group &optional info))
227 (autoload 'gnus-group-name-decode "gnus-group")
228 (declare-function gnus-group-name-charset "gnus-group" (method group))
229 ;; gnus-group requires gnus-int which requires message.
230 (declare-function message-tokenize-header "message"
231                   (header &optional separator))
232
233 (defun gnus-decode-newsgroups (newsgroups group &optional method)
234   (let ((method (or method (gnus-find-method-for-group group))))
235     (mapconcat (lambda (group)
236                  (gnus-group-name-decode group (gnus-group-name-charset
237                                                 method group)))
238                (message-tokenize-header newsgroups)
239                ",")))
240
241 (defun gnus-remove-text-with-property (prop)
242   "Delete all text in the current buffer with text property PROP."
243   (let ((start (point-min))
244         end)
245     (unless (get-text-property start prop)
246       (setq start (next-single-property-change start prop)))
247     (while start
248       (setq end (text-property-any start (point-max) prop nil))
249       (delete-region start (or end (point-max)))
250       (setq start (when end
251                     (next-single-property-change start prop))))))
252
253 (defun gnus-newsgroup-directory-form (newsgroup)
254   "Make hierarchical directory name from NEWSGROUP name."
255   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
256          (idx (string-match ":" newsgroup)))
257     (concat
258      (if idx (substring newsgroup 0 idx))
259      (if idx "/")
260      (nnheader-replace-chars-in-string
261       (if idx (substring newsgroup (1+ idx)) newsgroup)
262       ?. ?/))))
263
264 (defun gnus-newsgroup-savable-name (group)
265   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
266   ;; with dots.
267   (nnheader-replace-chars-in-string group ?/ ?.))
268
269 (defun gnus-string> (s1 s2)
270   (not (or (string< s1 s2)
271            (string= s1 s2))))
272
273 (defun gnus-string< (s1 s2)
274   "Return t if first arg string is less than second in lexicographic order.
275 Case is significant if and only if `case-fold-search' is nil.
276 Symbols are also allowed; their print names are used instead."
277   (if case-fold-search
278       (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
279                     (downcase (if (symbolp s2) (symbol-name s2) s2)))
280     (string-lessp s1 s2)))
281
282 ;;; Time functions.
283
284 (defun gnus-file-newer-than (file date)
285   (let ((fdate (nth 5 (file-attributes file))))
286     (or (> (car fdate) (car date))
287         (and (= (car fdate) (car date))
288              (> (nth 1 fdate) (nth 1 date))))))
289
290 ;;; Keymap macros.
291
292 (defmacro gnus-local-set-keys (&rest plist)
293   "Set the keys in PLIST in the current keymap."
294   `(gnus-define-keys-1 (current-local-map) ',plist))
295
296 (defmacro gnus-define-keys (keymap &rest plist)
297   "Define all keys in PLIST in KEYMAP."
298   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
299
300 (defmacro gnus-define-keys-safe (keymap &rest plist)
301   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
302   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
303
304 (put 'gnus-define-keys 'lisp-indent-function 1)
305 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
306 (put 'gnus-local-set-keys 'lisp-indent-function 1)
307
308 (defmacro gnus-define-keymap (keymap &rest plist)
309   "Define all keys in PLIST in KEYMAP."
310   `(gnus-define-keys-1 ,keymap (quote ,plist)))
311
312 (put 'gnus-define-keymap 'lisp-indent-function 1)
313
314 (defun gnus-define-keys-1 (keymap plist &optional safe)
315   (when (null keymap)
316     (error "Can't set keys in a null keymap"))
317   (cond ((symbolp keymap)
318          (setq keymap (symbol-value keymap)))
319         ((keymapp keymap))
320         ((listp keymap)
321          (set (car keymap) nil)
322          (define-prefix-command (car keymap))
323          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
324          (setq keymap (symbol-value (car keymap)))))
325   (let (key)
326     (while plist
327       (when (symbolp (setq key (pop plist)))
328         (setq key (symbol-value key)))
329       (if (or (not safe)
330               (eq (lookup-key keymap key) 'undefined))
331           (define-key keymap key (pop plist))
332         (pop plist)))))
333
334 (defun gnus-completing-read-with-default (default prompt &rest args)
335   ;; Like `completing-read', except that DEFAULT is the default argument.
336   (let* ((prompt (if default
337                      (concat prompt " (default " default "): ")
338                    (concat prompt ": ")))
339          (answer (apply 'completing-read prompt args)))
340     (if (or (null answer) (zerop (length answer)))
341         default
342       answer)))
343
344 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
345 ;; the echo area.
346 ;;
347 ;; Do we really need these functions?  Workarounds for bugs in the corresponding
348 ;; Emacs functions?  Maybe these bugs are no longer present in any supported
349 ;; (X)Emacs version?  Alias them to the original functions and see if anyone
350 ;; reports a problem.  If not, replace with original functions.  --rsteib,
351 ;; 2007-12-14
352 ;;
353 ;; All supported Emacsen clear the echo area after `yes-or-no-p', so we can
354 ;; remove `yes-or-no-p'.  RMS says that not clearing after `y-or-n-p' is
355 ;; intentional (see below), so we could remove `gnus-y-or-n-p' too.
356 ;; Objections?  --rsteib, 2008-02-16
357 ;;
358 ;; ,----[ http://thread.gmane.org/gmane.emacs.gnus.general/65099/focus=66070 ]
359 ;; | From: Richard Stallman
360 ;; | Subject: Re: Do we need gnus-yes-or-no-p and gnus-y-or-n-p?
361 ;; | To: Katsumi Yamaoka [...]
362 ;; | Cc: emacs-devel@[...], xemacs-beta@[...], ding@[...]
363 ;; | Date: Mon, 07 Jan 2008 12:16:05 -0500
364 ;; | Message-ID: <E1JBva1-000528-VY@fencepost.gnu.org>
365 ;; |
366 ;; |     The behavior of `y-or-n-p' that it doesn't clear the question
367 ;; |     and the answer is not serious of course, but I feel it is not
368 ;; |     cool.
369 ;; |
370 ;; | It is intentional.
371 ;; |
372 ;; |     Currently, it is commented out in the trunk by Reiner Steib.  He
373 ;; |     also wrote the benefit of leaving the question and the answer in
374 ;; |     the echo area as follows:
375 ;; |
376 ;; |     (http://article.gmane.org/gmane.emacs.gnus.general/66061)
377 ;; |     > In contrast to yes-or-no-p it is much easier to type y, n,
378 ;; |     > SPC, DEL, etc accidentally, so it might be useful for the user
379 ;; |     > to see what he has typed.
380 ;; |
381 ;; | Yes, that is the reason.
382 ;; `----
383
384 ;; (defun gnus-y-or-n-p (prompt)
385 ;;   (prog1
386 ;;       (y-or-n-p prompt)
387 ;;     (message "")))
388 ;; (defun gnus-yes-or-no-p (prompt)
389 ;;   (prog1
390 ;;       (yes-or-no-p prompt)
391 ;;     (message "")))
392
393 (defalias 'gnus-y-or-n-p 'y-or-n-p)
394 (defalias 'gnus-yes-or-no-p 'yes-or-no-p)
395
396 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
397 ;; age-depending date representations. (e.g. just the time if it's
398 ;; from today, the day of the week if it's within the last 7 days and
399 ;; the full date if it's older)
400
401 (defun gnus-seconds-today ()
402   "Return the number of seconds passed today."
403   (let ((now (decode-time (current-time))))
404     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
405
406 (defun gnus-seconds-month ()
407   "Return the number of seconds passed this month."
408   (let ((now (decode-time (current-time))))
409     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
410        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
411
412 (defun gnus-seconds-year ()
413   "Return the number of seconds passed this year."
414   (let ((now (decode-time (current-time)))
415         (days (format-time-string "%j" (current-time))))
416     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
417        (* (- (string-to-number days) 1) 3600 24))))
418
419 (defvar gnus-user-date-format-alist
420   '(((gnus-seconds-today) . "%k:%M")
421     (604800 . "%a %k:%M")                   ;;that's one week
422     ((gnus-seconds-month) . "%a %d")
423     ((gnus-seconds-year) . "%b %d")
424     (t . "%b %d '%y"))                      ;;this one is used when no
425                                             ;;other does match
426   "Specifies date format depending on age of article.
427 This is an alist of items (AGE . FORMAT).  AGE can be a number (of
428 seconds) or a Lisp expression evaluating to a number.  When the age of
429 the article is less than this number, then use `format-time-string'
430 with the corresponding FORMAT for displaying the date of the article.
431 If AGE is not a number or a Lisp expression evaluating to a
432 non-number, then the corresponding FORMAT is used as a default value.
433
434 Note that the list is processed from the beginning, so it should be
435 sorted by ascending AGE.  Also note that items following the first
436 non-number AGE will be ignored.
437
438 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
439 and `gnus-seconds-year' in the AGE spec.  They return the number of
440 seconds passed since the start of today, of this month, of this year,
441 respectively.")
442
443 (defun gnus-user-date (messy-date)
444   "Format the messy-date according to gnus-user-date-format-alist.
445 Returns \"  ?  \" if there's bad input or if an other error occurs.
446 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
447   (condition-case ()
448       (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
449              (now (time-to-seconds (current-time)))
450              ;;If we don't find something suitable we'll use this one
451              (my-format "%b %d '%y"))
452         (let* ((difference (- now messy-date))
453                (templist gnus-user-date-format-alist)
454                (top (eval (caar templist))))
455           (while (if (numberp top) (< top difference) (not top))
456             (progn
457               (setq templist (cdr templist))
458               (setq top (eval (caar templist)))))
459           (if (stringp (cdr (car templist)))
460               (setq my-format (cdr (car templist)))))
461         (format-time-string (eval my-format) (seconds-to-time messy-date)))
462     (error "  ?   ")))
463
464 (defun gnus-dd-mmm (messy-date)
465   "Return a string like DD-MMM from a big messy string."
466   (condition-case ()
467       (format-time-string "%d-%b" (safe-date-to-time messy-date))
468     (error "  -   ")))
469
470 (defmacro gnus-date-get-time (date)
471   "Convert DATE string to Emacs time.
472 Cache the result as a text property stored in DATE."
473   ;; Either return the cached value...
474   `(let ((d ,date))
475      (if (equal "" d)
476          '(0 0)
477        (or (get-text-property 0 'gnus-time d)
478            ;; or compute the value...
479            (let ((time (safe-date-to-time d)))
480              ;; and store it back in the string.
481              (put-text-property 0 1 'gnus-time time d)
482              time)))))
483
484 (defsubst gnus-time-iso8601 (time)
485   "Return a string of TIME in YYYYMMDDTHHMMSS format."
486   (format-time-string "%Y%m%dT%H%M%S" time))
487
488 (defun gnus-date-iso8601 (date)
489   "Convert the DATE to YYYYMMDDTHHMMSS."
490   (condition-case ()
491       (gnus-time-iso8601 (gnus-date-get-time date))
492     (error "")))
493
494 (defun gnus-mode-string-quote (string)
495   "Quote all \"%\"'s in STRING."
496   (gnus-replace-in-string string "%" "%%"))
497
498 ;; Make a hash table (default and minimum size is 256).
499 ;; Optional argument HASHSIZE specifies the table size.
500 (defun gnus-make-hashtable (&optional hashsize)
501   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
502
503 ;; Make a number that is suitable for hashing; bigger than MIN and
504 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
505 ;; hardware modulo operation, so they implement it in software.  On
506 ;; many sparcs over 50% of the time to intern is spent in the modulo.
507 ;; Yes, it's slower than actually computing the hash from the string!
508 ;; So we use powers of 2 so people can optimize the modulo to a mask.
509 (defun gnus-create-hash-size (min)
510   (let ((i 1))
511     (while (< i min)
512       (setq i (* 2 i)))
513     i))
514
515 (defcustom gnus-verbose 7
516   "*Integer that says how verbose Gnus should be.
517 The higher the number, the more messages Gnus will flash to say what
518 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
519 display most important messages; and at ten, Gnus will keep on
520 jabbering all the time."
521   :group 'gnus-start
522   :type 'integer)
523
524 (defcustom gnus-add-timestamp-to-message nil
525   "Non-nil means add timestamps to messages that Gnus issues.
526 If it is `log', add timestamps to only the messages that go into the
527 \"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
528 If it is neither nil nor `log', add timestamps not only to log messages
529 but also to the ones displayed in the echo area."
530   :version "23.1" ;; No Gnus
531   :group  'gnus-various
532   :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
533                  (const :tag "Logged messages only" log)
534                  (sexp :tag "All messages"
535                        :match (lambda (widget value) value)
536                        :value t)
537                  (const :tag "No timestamp" nil)))
538
539 (eval-when-compile
540   (defmacro gnus-message-with-timestamp-1 (format-string args)
541     (let ((timestamp '((format-time-string "%Y%m%dT%H%M%S" time)
542                        "." (format "%03d" (/ (nth 2 time) 1000)) "> ")))
543       (if (featurep 'xemacs)
544           `(let (str time)
545              (if (or (and (null ,format-string) (null ,args))
546                      (progn
547                        (setq str (apply 'format ,format-string ,args))
548                        (zerop (length str))))
549                  (prog1
550                      (and ,format-string str)
551                    (clear-message nil))
552                (cond ((eq gnus-add-timestamp-to-message 'log)
553                       (setq time (current-time))
554                       (display-message 'no-log str)
555                       (log-message 'message (concat ,@timestamp str)))
556                      (gnus-add-timestamp-to-message
557                       (setq time (current-time))
558                       (display-message 'message (concat ,@timestamp str)))
559                      (t
560                       (display-message 'message str))))
561              str)
562         `(let (str time)
563            (cond ((eq gnus-add-timestamp-to-message 'log)
564                   (setq str (let (message-log-max)
565                               (apply 'message ,format-string ,args)))
566                   (when (and message-log-max
567                              (> message-log-max 0)
568                              (/= (length str) 0))
569                     (setq time (current-time))
570                     (with-current-buffer (get-buffer-create "*Messages*")
571                       (goto-char (point-max))
572                       (insert ,@timestamp str "\n")
573                       (forward-line (- message-log-max))
574                       (delete-region (point-min) (point))
575                       (goto-char (point-max))))
576                   str)
577                  (gnus-add-timestamp-to-message
578                   (if (or (and (null ,format-string) (null ,args))
579                           (progn
580                             (setq str (apply 'format ,format-string ,args))
581                             (zerop (length str))))
582                       (prog1
583                           (and ,format-string str)
584                         (message nil))
585                     (setq time (current-time))
586                     (message "%s" (concat ,@timestamp str))
587                     str))
588                  (t
589                   (apply 'message ,format-string ,args))))))))
590
591 (defun gnus-message-with-timestamp (format-string &rest args)
592   "Display message with timestamp.  Arguments are the same as `message'.
593 The `gnus-add-timestamp-to-message' variable controls how to add
594 timestamp to message."
595   (gnus-message-with-timestamp-1 format-string args))
596
597 (defun gnus-message (level &rest args)
598   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
599
600 Guideline for numbers:
601 1 - error messages, 3 - non-serious error messages, 5 - messages for things
602 that take a long time, 7 - not very important messages on stuff, 9 - messages
603 inside loops."
604   (if (<= level gnus-verbose)
605       (if gnus-add-timestamp-to-message
606           (apply 'gnus-message-with-timestamp args)
607         (apply 'message args))
608     ;; We have to do this format thingy here even if the result isn't
609     ;; shown - the return value has to be the same as the return value
610     ;; from `message'.
611     (apply 'format args)))
612
613 (defun gnus-error (level &rest args)
614   "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
615 ARGS are passed to `message'."
616   (when (<= (floor level) gnus-verbose)
617     (apply 'message args)
618     (ding)
619     (let (duration)
620       (when (and (floatp level)
621                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
622         (sit-for duration))))
623   nil)
624
625 (defun gnus-split-references (references)
626   "Return a list of Message-IDs in REFERENCES."
627   (let ((beg 0)
628         (references (or references ""))
629         ids)
630     (while (string-match "<[^<]+[^< \t]" references beg)
631       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
632             ids))
633     (nreverse ids)))
634
635 (defun gnus-extract-references (references)
636   "Return a list of Message-IDs in REFERENCES (in In-Reply-To
637   format), trimmed to only contain the Message-IDs."
638   (let ((ids (gnus-split-references references))
639         refs)
640     (dolist (id ids)
641       (when (string-match "<[^<>]+>" id)
642         (push (match-string 0 id) refs)))
643     refs))
644
645 (defsubst gnus-parent-id (references &optional n)
646   "Return the last Message-ID in REFERENCES.
647 If N, return the Nth ancestor instead."
648   (when (and references
649              (not (zerop (length references))))
650     (if n
651         (let ((ids (inline (gnus-split-references references))))
652           (while (nthcdr n ids)
653             (setq ids (cdr ids)))
654           (car ids))
655       (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
656         (match-string 1 references)))))
657
658 (defun gnus-buffer-live-p (buffer)
659   "Say whether BUFFER is alive or not."
660   (and buffer
661        (get-buffer buffer)
662        (buffer-name (get-buffer buffer))))
663
664 (defun gnus-horizontal-recenter ()
665   "Recenter the current buffer horizontally."
666   (if (< (current-column) (/ (window-width) 2))
667       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
668     (let* ((orig (point))
669            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
670            (max 0))
671       (when end
672         ;; Find the longest line currently displayed in the window.
673         (goto-char (window-start))
674         (while (and (not (eobp))
675                     (< (point) end))
676           (end-of-line)
677           (setq max (max max (current-column)))
678           (forward-line 1))
679         (goto-char orig)
680         ;; Scroll horizontally to center (sort of) the point.
681         (if (> max (window-width))
682             (set-window-hscroll
683              (gnus-get-buffer-window (current-buffer) t)
684              (min (- (current-column) (/ (window-width) 3))
685                   (+ 2 (- max (window-width)))))
686           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
687         max))))
688
689 (defun gnus-read-event-char (&optional prompt)
690   "Get the next event."
691   (let ((event (read-event prompt)))
692     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
693     (cons (and (numberp event) event) event)))
694
695 (defun gnus-sortable-date (date)
696   "Make string suitable for sorting from DATE."
697   (gnus-time-iso8601 (date-to-time date)))
698
699 (defun gnus-copy-file (file &optional to)
700   "Copy FILE to TO."
701   (interactive
702    (list (read-file-name "Copy file: " default-directory)
703          (read-file-name "Copy file to: " default-directory)))
704   (unless to
705     (setq to (read-file-name "Copy file to: " default-directory)))
706   (when (file-directory-p to)
707     (setq to (concat (file-name-as-directory to)
708                      (file-name-nondirectory file))))
709   (copy-file file to))
710
711 (defvar gnus-work-buffer " *gnus work*")
712
713 (declare-function gnus-get-buffer-create "gnus" (name))
714 ;; gnus.el requires mm-util.
715 (declare-function mm-enable-multibyte "mm-util")
716
717 (defun gnus-set-work-buffer ()
718   "Put point in the empty Gnus work buffer."
719   (if (get-buffer gnus-work-buffer)
720       (progn
721         (set-buffer gnus-work-buffer)
722         (erase-buffer))
723     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
724     (kill-all-local-variables)
725     (mm-enable-multibyte)))
726
727 (defmacro gnus-group-real-name (group)
728   "Find the real name of a foreign newsgroup."
729   `(let ((gname ,group))
730      (if (string-match "^[^:]+:" gname)
731          (substring gname (match-end 0))
732        gname)))
733
734 (defmacro gnus-group-server (group)
735   "Find the server name of a foreign newsgroup.
736 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
737 yield \"nnimap:yxa\"."
738   `(let ((gname ,group))
739      (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
740          (format "%s:%s" (match-string 1 gname) (or
741                                                  (match-string 2 gname)
742                                                  ""))
743        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
744
745 (defun gnus-make-sort-function (funs)
746   "Return a composite sort condition based on the functions in FUNS."
747   (cond
748    ;; Just a simple function.
749    ((functionp funs) funs)
750    ;; No functions at all.
751    ((null funs) funs)
752    ;; A list of functions.
753    ((or (cdr funs)
754         (listp (car funs)))
755     (gnus-byte-compile
756      `(lambda (t1 t2)
757         ,(gnus-make-sort-function-1 (reverse funs)))))
758    ;; A list containing just one function.
759    (t
760     (car funs))))
761
762 (defun gnus-make-sort-function-1 (funs)
763   "Return a composite sort condition based on the functions in FUNS."
764   (let ((function (car funs))
765         (first 't1)
766         (last 't2))
767     (when (consp function)
768       (cond
769        ;; Reversed spec.
770        ((eq (car function) 'not)
771         (setq function (cadr function)
772               first 't2
773               last 't1))
774        ((functionp function)
775         ;; Do nothing.
776         )
777        (t
778         (error "Invalid sort spec: %s" function))))
779     (if (cdr funs)
780         `(or (,function ,first ,last)
781              (and (not (,function ,last ,first))
782                   ,(gnus-make-sort-function-1 (cdr funs))))
783       `(,function ,first ,last))))
784
785 (defun gnus-turn-off-edit-menu (type)
786   "Turn off edit menu in `gnus-TYPE-mode-map'."
787   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
788     [menu-bar edit] 'undefined))
789
790 (defmacro gnus-bind-print-variables (&rest forms)
791   "Bind print-* variables and evaluate FORMS.
792 This macro is used with `prin1', `pp', etc. in order to ensure printed
793 Lisp objects are loadable.  Bind `print-quoted' and `print-readably'
794 to t, and `print-escape-multibyte', `print-escape-newlines',
795 `print-escape-nonascii', `print-length', `print-level' and
796 `print-string-length' to nil."
797   `(let ((print-quoted t)
798          (print-readably t)
799          ;;print-circle
800          ;;print-continuous-numbering
801          print-escape-multibyte
802          print-escape-newlines
803          print-escape-nonascii
804          ;;print-gensym
805          print-length
806          print-level
807          print-string-length)
808      ,@forms))
809
810 (defun gnus-prin1 (form)
811   "Use `prin1' on FORM in the current buffer.
812 Bind `print-quoted' and `print-readably' to t, and `print-length' and
813 `print-level' to nil.  See also `gnus-bind-print-variables'."
814   (gnus-bind-print-variables (prin1 form (current-buffer))))
815
816 (defun gnus-prin1-to-string (form)
817   "The same as `prin1'.
818 Bind `print-quoted' and `print-readably' to t, and `print-length' and
819 `print-level' to nil.  See also `gnus-bind-print-variables'."
820   (gnus-bind-print-variables (prin1-to-string form)))
821
822 (defun gnus-pp (form &optional stream)
823   "Use `pp' on FORM in the current buffer.
824 Bind `print-quoted' and `print-readably' to t, and `print-length' and
825 `print-level' to nil.  See also `gnus-bind-print-variables'."
826   (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
827
828 (defun gnus-pp-to-string (form)
829   "The same as `pp-to-string'.
830 Bind `print-quoted' and `print-readably' to t, and `print-length' and
831 `print-level' to nil.  See also `gnus-bind-print-variables'."
832   (gnus-bind-print-variables (pp-to-string form)))
833
834 (defun gnus-make-directory (directory)
835   "Make DIRECTORY (and all its parents) if it doesn't exist."
836   (require 'nnmail)
837   (let ((file-name-coding-system nnmail-pathname-coding-system))
838     (when (and directory
839                (not (file-exists-p directory)))
840       (make-directory directory t)))
841   t)
842
843 (defun gnus-write-buffer (file)
844   "Write the current buffer's contents to FILE."
845   (let ((file-name-coding-system nnmail-pathname-coding-system))
846     ;; Make sure the directory exists.
847     (gnus-make-directory (file-name-directory file))
848     ;; Write the buffer.
849     (write-region (point-min) (point-max) file nil 'quietly)))
850
851 (defun gnus-delete-file (file)
852   "Delete FILE if it exists."
853   (when (file-exists-p file)
854     (delete-file file)))
855
856 (defun gnus-delete-directory (directory)
857   "Delete files in DIRECTORY.  Subdirectories remain.
858 If there's no subdirectory, delete DIRECTORY as well."
859   (when (file-directory-p directory)
860     (let ((files (directory-files
861                   directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
862           file dir)
863       (while files
864         (setq file (pop files))
865         (if (eq t (car (file-attributes file)))
866             ;; `file' is a subdirectory.
867             (setq dir t)
868           ;; `file' is a file or a symlink.
869           (delete-file file)))
870       (unless dir
871         (delete-directory directory)))))
872
873 ;; The following two functions are used in gnus-registry.
874 ;; They were contributed by Andreas Fuchs <asf@void.at>.
875 (defun gnus-alist-to-hashtable (alist)
876   "Build a hashtable from the values in ALIST."
877   (let ((ht (make-hash-table
878              :size 4096
879              :test 'equal)))
880     (mapc
881      (lambda (kv-pair)
882        (puthash (car kv-pair) (cdr kv-pair) ht))
883      alist)
884      ht))
885
886 (defun gnus-hashtable-to-alist (hash)
887   "Build an alist from the values in HASH."
888   (let ((list nil))
889     (maphash
890      (lambda (key value)
891        (setq list (cons (cons key value) list)))
892      hash)
893     list))
894
895 (defun gnus-strip-whitespace (string)
896   "Return STRING stripped of all whitespace."
897   (while (string-match "[\r\n\t ]+" string)
898     (setq string (replace-match "" t t string)))
899   string)
900
901 (declare-function gnus-put-text-property "gnus"
902                   (start end property value &optional object))
903
904 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
905   "The same as `put-text-property', but don't put this prop on any newlines in the region."
906   (save-match-data
907     (save-excursion
908       (save-restriction
909         (goto-char beg)
910         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
911           (gnus-put-text-property beg (match-beginning 0) prop val)
912           (setq beg (point)))
913         (gnus-put-text-property beg (point) prop val)))))
914
915 (declare-function gnus-overlay-put  "gnus" (overlay prop value))
916 (declare-function gnus-make-overlay "gnus"
917                   (beg end &optional buffer front-advance rear-advance))
918
919 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
920   "The same as `put-text-property', but don't put this prop on any newlines in the region."
921   (save-match-data
922     (save-excursion
923       (save-restriction
924         (goto-char beg)
925         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
926           (gnus-overlay-put
927            (gnus-make-overlay beg (match-beginning 0))
928            prop val)
929           (setq beg (point)))
930         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
931
932 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
933                                                                    prop val)
934   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
935   (let ((b beg))
936     (while (/= b end)
937       (when (get-text-property b 'gnus-face)
938         (setq b (next-single-property-change b 'gnus-face nil end)))
939       (when (/= b end)
940         (inline
941           (gnus-put-text-property
942            b (setq b (next-single-property-change b 'gnus-face nil end))
943            prop val))))))
944
945 (defmacro gnus-faces-at (position)
946   "Return a list of faces at POSITION."
947   (if (featurep 'xemacs)
948       `(let ((pos ,position))
949          (mapcar-extents 'extent-face
950                          nil (current-buffer) pos pos nil 'face))
951     `(let ((pos ,position))
952        (delq nil (cons (get-text-property pos 'face)
953                        (mapcar
954                         (lambda (overlay)
955                           (overlay-get overlay 'face))
956                         (overlays-at pos)))))))
957
958 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
959 ;; The primary idea here is to try to protect internal datastructures
960 ;; from becoming corrupted when the user hits C-g, or if a hook or
961 ;; similar blows up.  Often in Gnus multiple tables/lists need to be
962 ;; updated at the same time, or information can be lost.
963
964 (defvar gnus-atomic-be-safe t
965   "If t, certain operations will be protected from interruption by C-g.")
966
967 (defmacro gnus-atomic-progn (&rest forms)
968   "Evaluate FORMS atomically, which means to protect the evaluation
969 from being interrupted by the user.  An error from the forms themselves
970 will return without finishing the operation.  Since interrupts from
971 the user are disabled, it is recommended that only the most minimal
972 operations are performed by FORMS.  If you wish to assign many
973 complicated values atomically, compute the results into temporary
974 variables and then do only the assignment atomically."
975   `(let ((inhibit-quit gnus-atomic-be-safe))
976      ,@forms))
977
978 (put 'gnus-atomic-progn 'lisp-indent-function 0)
979
980 (defmacro gnus-atomic-progn-assign (protect &rest forms)
981   "Evaluate FORMS, but ensure that the variables listed in PROTECT
982 are not changed if anything in FORMS signals an error or otherwise
983 non-locally exits.  The variables listed in PROTECT are updated atomically.
984 It is safe to use gnus-atomic-progn-assign with long computations.
985
986 Note that if any of the symbols in PROTECT were unbound, they will be
987 set to nil on a successful assignment.  In case of an error or other
988 non-local exit, it will still be unbound."
989   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
990                                                   (concat (symbol-name x)
991                                                           "-tmp"))
992                                                  x))
993                                protect))
994          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
995                                temp-sym-map))
996          (temp-sym-let (mapcar (lambda (x) (list (car x)
997                                                  `(and (boundp ',(cadr x))
998                                                        ,(cadr x))))
999                                temp-sym-map))
1000          (sym-temp-let sym-temp-map)
1001          (temp-sym-assign (apply 'append temp-sym-map))
1002          (sym-temp-assign (apply 'append sym-temp-map))
1003          (result (make-symbol "result-tmp")))
1004     `(let (,@temp-sym-let
1005            ,result)
1006        (let ,sym-temp-let
1007          (setq ,result (progn ,@forms))
1008          (setq ,@temp-sym-assign))
1009        (let ((inhibit-quit gnus-atomic-be-safe))
1010          (setq ,@sym-temp-assign))
1011        ,result)))
1012
1013 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
1014 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
1015
1016 (defmacro gnus-atomic-setq (&rest pairs)
1017   "Similar to setq, except that the real symbols are only assigned when
1018 there are no errors.  And when the real symbols are assigned, they are
1019 done so atomically.  If other variables might be changed via side-effect,
1020 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
1021 with potentially long computations."
1022   (let ((tpairs pairs)
1023         syms)
1024     (while tpairs
1025       (push (car tpairs) syms)
1026       (setq tpairs (cddr tpairs)))
1027     `(gnus-atomic-progn-assign ,syms
1028        (setq ,@pairs))))
1029
1030 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
1031
1032
1033 ;;; Functions for saving to babyl/mail files.
1034
1035 (eval-when-compile
1036   (condition-case nil
1037       (progn
1038         (require 'rmail)
1039         (autoload 'rmail-update-summary "rmailsum"))
1040     (error
1041      (define-compiler-macro rmail-select-summary (&rest body)
1042        ;; Rmail of the XEmacs version is supplied by the package, and
1043        ;; requires tm and apel packages.  However, there may be those
1044        ;; who haven't installed those packages.  This macro helps such
1045        ;; people even if they install those packages later.
1046        `(eval '(rmail-select-summary ,@body)))
1047      ;; If there's rmail but there's no tm (or there's apel of the
1048      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
1049      ;; version fails halfway, however it provides the rmail-select-summary
1050      ;; macro which uses the following functions:
1051      (autoload 'rmail-summary-displayed "rmail")
1052      (autoload 'rmail-maybe-display-summary "rmail"))))
1053
1054 (defvar rmail-default-rmail-file)
1055 (defvar mm-text-coding-system)
1056
1057 (declare-function mm-append-to-file "mm-util"
1058                   (start end filename &optional codesys inhibit))
1059
1060 (defun gnus-output-to-rmail (filename &optional ask)
1061   "Append the current article to an Rmail file named FILENAME."
1062   (require 'rmail)
1063   (require 'mm-util)
1064   ;; Most of these codes are borrowed from rmailout.el.
1065   (setq filename (expand-file-name filename))
1066   (setq rmail-default-rmail-file filename)
1067   (let ((artbuf (current-buffer))
1068         (tmpbuf (get-buffer-create " *Gnus-output*")))
1069     (save-excursion
1070       (or (get-file-buffer filename)
1071           (file-exists-p filename)
1072           (if (or (not ask)
1073                   (gnus-yes-or-no-p
1074                    (concat "\"" filename "\" does not exist, create it? ")))
1075               (let ((file-buffer (create-file-buffer filename)))
1076                 (save-excursion
1077                   (set-buffer file-buffer)
1078                   (rmail-insert-rmail-file-header)
1079                   (let ((require-final-newline nil)
1080                         (coding-system-for-write mm-text-coding-system))
1081                     (gnus-write-buffer filename)))
1082                 (kill-buffer file-buffer))
1083             (error "Output file does not exist")))
1084       (set-buffer tmpbuf)
1085       (erase-buffer)
1086       (insert-buffer-substring artbuf)
1087       (gnus-convert-article-to-rmail)
1088       ;; Decide whether to append to a file or to an Emacs buffer.
1089       (let ((outbuf (get-file-buffer filename)))
1090         (if (not outbuf)
1091             (let ((file-name-coding-system nnmail-pathname-coding-system))
1092               (mm-append-to-file (point-min) (point-max) filename))
1093           ;; File has been visited, in buffer OUTBUF.
1094           (set-buffer outbuf)
1095           (let ((buffer-read-only nil)
1096                 (msg (and (boundp 'rmail-current-message)
1097                           (symbol-value 'rmail-current-message))))
1098             ;; If MSG is non-nil, buffer is in RMAIL mode.
1099             (when msg
1100               (widen)
1101               (narrow-to-region (point-max) (point-max)))
1102             (insert-buffer-substring tmpbuf)
1103             (when msg
1104               (goto-char (point-min))
1105               (widen)
1106               (search-backward "\n\^_")
1107               (narrow-to-region (point) (point-max))
1108               (rmail-count-new-messages t)
1109               (when (rmail-summary-exists)
1110                 (rmail-select-summary
1111                  (rmail-update-summary)))
1112               (rmail-count-new-messages t)
1113               (rmail-show-message msg))
1114             (save-buffer)))))
1115     (kill-buffer tmpbuf)))
1116
1117 (defun gnus-output-to-mail (filename &optional ask)
1118   "Append the current article to a mail file named FILENAME."
1119   (setq filename (expand-file-name filename))
1120   (let ((artbuf (current-buffer))
1121         (tmpbuf (get-buffer-create " *Gnus-output*")))
1122     (save-excursion
1123       ;; Create the file, if it doesn't exist.
1124       (when (and (not (get-file-buffer filename))
1125                  (not (file-exists-p filename)))
1126         (if (or (not ask)
1127                 (gnus-y-or-n-p
1128                  (concat "\"" filename "\" does not exist, create it? ")))
1129             (let ((file-buffer (create-file-buffer filename)))
1130               (save-excursion
1131                 (set-buffer file-buffer)
1132                 (let ((require-final-newline nil)
1133                       (coding-system-for-write mm-text-coding-system))
1134                   (gnus-write-buffer filename)))
1135               (kill-buffer file-buffer))
1136           (error "Output file does not exist")))
1137       (set-buffer tmpbuf)
1138       (erase-buffer)
1139       (insert-buffer-substring artbuf)
1140       (goto-char (point-min))
1141       (if (looking-at "From ")
1142           (forward-line 1)
1143         (insert "From nobody " (current-time-string) "\n"))
1144       (let (case-fold-search)
1145         (while (re-search-forward "^From " nil t)
1146           (beginning-of-line)
1147           (insert ">")))
1148       ;; Decide whether to append to a file or to an Emacs buffer.
1149       (let ((outbuf (get-file-buffer filename)))
1150         (if (not outbuf)
1151             (let ((buffer-read-only nil))
1152               (save-excursion
1153                 (goto-char (point-max))
1154                 (forward-char -2)
1155                 (unless (looking-at "\n\n")
1156                   (goto-char (point-max))
1157                   (unless (bolp)
1158                     (insert "\n"))
1159                   (insert "\n"))
1160                 (goto-char (point-max))
1161                 (let ((file-name-coding-system nnmail-pathname-coding-system))
1162                   (mm-append-to-file (point-min) (point-max) filename))))
1163           ;; File has been visited, in buffer OUTBUF.
1164           (set-buffer outbuf)
1165           (let ((buffer-read-only nil))
1166             (goto-char (point-max))
1167             (unless (eobp)
1168               (insert "\n"))
1169             (insert "\n")
1170             (insert-buffer-substring tmpbuf)))))
1171     (kill-buffer tmpbuf)))
1172
1173 (defun gnus-convert-article-to-rmail ()
1174   "Convert article in current buffer to Rmail message format."
1175   (let ((buffer-read-only nil))
1176     ;; Convert article directly into Babyl format.
1177     (goto-char (point-min))
1178     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1179     (while (search-forward "\n\^_" nil t) ;single char
1180       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
1181     (goto-char (point-max))
1182     (insert "\^_")))
1183
1184 (defun gnus-map-function (funs arg)
1185   "Apply the result of the first function in FUNS to the second, and so on.
1186 ARG is passed to the first function."
1187   (while funs
1188     (setq arg (funcall (pop funs) arg)))
1189   arg)
1190
1191 (defun gnus-run-hooks (&rest funcs)
1192   "Does the same as `run-hooks', but saves the current buffer."
1193   (save-current-buffer
1194     (apply 'run-hooks funcs)))
1195
1196 (defun gnus-run-mode-hooks (&rest funcs)
1197   "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1198 This function saves the current buffer."
1199   (if (fboundp 'run-mode-hooks)
1200       (save-current-buffer (apply 'run-mode-hooks funcs))
1201     (save-current-buffer (apply 'run-hooks funcs))))
1202
1203 ;;; Various
1204
1205 (defvar gnus-group-buffer)              ; Compiler directive
1206 (defun gnus-alive-p ()
1207   "Say whether Gnus is running or not."
1208   (and (boundp 'gnus-group-buffer)
1209        (get-buffer gnus-group-buffer)
1210        (save-excursion
1211          (set-buffer gnus-group-buffer)
1212          (eq major-mode 'gnus-group-mode))))
1213
1214 (defun gnus-remove-if (predicate list)
1215   "Return a copy of LIST with all items satisfying PREDICATE removed."
1216   (let (out)
1217     (while list
1218       (unless (funcall predicate (car list))
1219         (push (car list) out))
1220       (setq list (cdr list)))
1221     (nreverse out)))
1222
1223 (if (fboundp 'assq-delete-all)
1224     (defalias 'gnus-delete-alist 'assq-delete-all)
1225   (defun gnus-delete-alist (key alist)
1226     "Delete from ALIST all elements whose car is KEY.
1227 Return the modified alist."
1228     (let (entry)
1229       (while (setq entry (assq key alist))
1230         (setq alist (delq entry alist)))
1231       alist)))
1232
1233 (defmacro gnus-pull (key alist &optional assoc-p)
1234   "Modify ALIST to be without KEY."
1235   (unless (symbolp alist)
1236     (error "Not a symbol: %s" alist))
1237   (let ((fun (if assoc-p 'assoc 'assq)))
1238     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1239
1240 (defun gnus-globalify-regexp (re)
1241   "Return a regexp that matches a whole line, if RE matches a part of it."
1242   (concat (unless (string-match "^\\^" re) "^.*")
1243           re
1244           (unless (string-match "\\$$" re) ".*$")))
1245
1246 (defun gnus-set-window-start (&optional point)
1247   "Set the window start to POINT, or (point) if nil."
1248   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1249     (when win
1250       (set-window-start win (or point (point))))))
1251
1252 (defun gnus-annotation-in-region-p (b e)
1253   (if (= b e)
1254       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1255     (text-property-any b e 'gnus-undeletable t)))
1256
1257 (defun gnus-or (&rest elems)
1258   "Return non-nil if any of the elements are non-nil."
1259   (catch 'found
1260     (while elems
1261       (when (pop elems)
1262         (throw 'found t)))))
1263
1264 (defun gnus-and (&rest elems)
1265   "Return non-nil if all of the elements are non-nil."
1266   (catch 'found
1267     (while elems
1268       (unless (pop elems)
1269         (throw 'found nil)))
1270     t))
1271
1272 ;; gnus.el requires mm-util.
1273 (declare-function mm-disable-multibyte "mm-util")
1274
1275 (defun gnus-write-active-file (file hashtb &optional full-names)
1276   ;; `coding-system-for-write' should be `raw-text' or equivalent.
1277   (let ((coding-system-for-write nnmail-active-file-coding-system))
1278     (with-temp-file file
1279       ;; The buffer should be in the unibyte mode because group names
1280       ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1281       (mm-disable-multibyte)
1282       (mapatoms
1283        (lambda (sym)
1284          (when (and sym
1285                     (boundp sym)
1286                     (symbol-value sym))
1287            (insert (format "%S %d %d y\n"
1288                            (if full-names
1289                                sym
1290                              (intern (gnus-group-real-name (symbol-name sym))))
1291                            (or (cdr (symbol-value sym))
1292                                (car (symbol-value sym)))
1293                            (car (symbol-value sym))))))
1294        hashtb)
1295       (goto-char (point-max))
1296       (while (search-backward "\\." nil t)
1297         (delete-char 1)))))
1298
1299 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1300 (defmacro gnus-with-output-to-file (file &rest body)
1301   (let ((buffer (make-symbol "output-buffer"))
1302         (size (make-symbol "output-buffer-size"))
1303         (leng (make-symbol "output-buffer-length"))
1304         (append (make-symbol "output-buffer-append")))
1305     `(let* ((,size 131072)
1306             (,buffer (make-string ,size 0))
1307             (,leng 0)
1308             (,append nil)
1309             (standard-output
1310              (lambda (c)
1311                (aset ,buffer ,leng c)
1312
1313                (if (= ,size (setq ,leng (1+ ,leng)))
1314                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1315                           (setq ,leng 0
1316                                 ,append t))))))
1317        ,@body
1318        (when (> ,leng 0)
1319          (let ((coding-system-for-write 'no-conversion))
1320          (write-region (substring ,buffer 0 ,leng) nil ,file
1321                        ,append 'no-msg))))))
1322
1323 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1324 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1325
1326 (if (fboundp 'union)
1327     (defalias 'gnus-union 'union)
1328   (defun gnus-union (l1 l2)
1329     "Set union of lists L1 and L2."
1330     (cond ((null l1) l2)
1331           ((null l2) l1)
1332           ((equal l1 l2) l1)
1333           (t
1334            (or (>= (length l1) (length l2))
1335                (setq l1 (prog1 l2 (setq l2 l1))))
1336            (while l2
1337              (or (member (car l2) l1)
1338                  (push (car l2) l1))
1339              (pop l2))
1340            l1))))
1341
1342 (declare-function gnus-add-text-properties "gnus"
1343                   (start end properties &optional object))
1344
1345 (defun gnus-add-text-properties-when
1346   (property value start end properties &optional object)
1347   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1348   (let (point)
1349     (while (and start
1350                 (< start end) ;; XEmacs will loop for every when start=end.
1351                 (setq point (text-property-not-all start end property value)))
1352       (gnus-add-text-properties start point properties object)
1353       (setq start (text-property-any point end property value)))
1354     (if start
1355         (gnus-add-text-properties start end properties object))))
1356
1357 (defun gnus-remove-text-properties-when
1358   (property value start end properties &optional object)
1359   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1360   (let (point)
1361     (while (and start
1362                 (< start end)
1363                 (setq point (text-property-not-all start end property value)))
1364       (remove-text-properties start point properties object)
1365       (setq start (text-property-any point end property value)))
1366     (if start
1367         (remove-text-properties start end properties object))
1368     t))
1369
1370 (defun gnus-string-remove-all-properties (string)
1371   (condition-case ()
1372       (let ((s string))
1373         (set-text-properties 0 (length string) nil string)
1374         s)
1375     (error string)))
1376
1377 ;; This might use `compare-strings' to reduce consing in the
1378 ;; case-insensitive case, but it has to cope with null args.
1379 ;; (`string-equal' uses symbol print names.)
1380 (defun gnus-string-equal (x y)
1381   "Like `string-equal', except it compares case-insensitively."
1382   (and (= (length x) (length y))
1383        (or (string-equal x y)
1384            (string-equal (downcase x) (downcase y)))))
1385
1386 (defcustom gnus-use-byte-compile t
1387   "If non-nil, byte-compile crucial run-time code.
1388 Setting it to nil has no effect after the first time `gnus-byte-compile'
1389 is run."
1390   :type 'boolean
1391   :version "22.1"
1392   :group 'gnus-various)
1393
1394 (defun gnus-byte-compile (form)
1395   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1396   (if gnus-use-byte-compile
1397       (progn
1398         (condition-case nil
1399             ;; Work around a bug in XEmacs 21.4
1400             (require 'byte-optimize)
1401           (error))
1402         (require 'bytecomp)
1403         (defalias 'gnus-byte-compile
1404           (lambda (form)
1405             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1406               (byte-compile form))))
1407         (gnus-byte-compile form))
1408     form))
1409
1410 (defun gnus-remassoc (key alist)
1411   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1412 The modified LIST is returned.  If the first member
1413 of LIST has a car that is `equal' to KEY, there is no way to remove it
1414 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1415 sure of changing the value of `foo'."
1416   (when alist
1417     (if (equal key (caar alist))
1418         (cdr alist)
1419       (setcdr alist (gnus-remassoc key (cdr alist)))
1420       alist)))
1421
1422 (defun gnus-update-alist-soft (key value alist)
1423   (if value
1424       (cons (cons key value) (gnus-remassoc key alist))
1425     (gnus-remassoc key alist)))
1426
1427 (defun gnus-create-info-command (node)
1428   "Create a command that will go to info NODE."
1429   `(lambda ()
1430      (interactive)
1431      ,(concat "Enter the info system at node " node)
1432      (Info-goto-node ,node)
1433      (setq gnus-info-buffer (current-buffer))
1434      (gnus-configure-windows 'info)))
1435
1436 (defun gnus-not-ignore (&rest args)
1437   t)
1438
1439 (defvar gnus-directory-sep-char-regexp "/"
1440   "The regexp of directory separator character.
1441 If you find some problem with the directory separator character, try
1442 \"[/\\\\\]\" for some systems.")
1443
1444 (defun gnus-url-unhex (x)
1445   (if (> x ?9)
1446       (if (>= x ?a)
1447           (+ 10 (- x ?a))
1448         (+ 10 (- x ?A)))
1449     (- x ?0)))
1450
1451 ;; Fixme: Do it like QP.
1452 (defun gnus-url-unhex-string (str &optional allow-newlines)
1453   "Remove %XX, embedded spaces, etc in a url.
1454 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1455 decoding of carriage returns and line feeds in the string, which is normally
1456 forbidden in URL encoding."
1457   (let ((tmp "")
1458         (case-fold-search t))
1459     (while (string-match "%[0-9a-f][0-9a-f]" str)
1460       (let* ((start (match-beginning 0))
1461              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1462              (code (+ (* 16 ch1)
1463                       (gnus-url-unhex (elt str (+ start 2))))))
1464         (setq tmp (concat
1465                    tmp (substring str 0 start)
1466                    (cond
1467                     (allow-newlines
1468                      (char-to-string code))
1469                     ((or (= code ?\n) (= code ?\r))
1470                      " ")
1471                     (t (char-to-string code))))
1472               str (substring str (match-end 0)))))
1473     (setq tmp (concat tmp str))
1474     tmp))
1475
1476 (defun gnus-make-predicate (spec)
1477   "Transform SPEC into a function that can be called.
1478 SPEC is a predicate specifier that contains stuff like `or', `and',
1479 `not', lists and functions.  The functions all take one parameter."
1480   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1481
1482 (defun gnus-make-predicate-1 (spec)
1483   (cond
1484    ((symbolp spec)
1485     `(,spec elem))
1486    ((listp spec)
1487     (if (memq (car spec) '(or and not))
1488         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1489       (error "Invalid predicate specifier: %s" spec)))))
1490
1491 (defun gnus-completing-read (prompt table &optional predicate require-match
1492                                     history)
1493   (when (and history
1494              (not (boundp history)))
1495     (set history nil))
1496   (completing-read
1497    (if (symbol-value history)
1498        (concat prompt " (" (car (symbol-value history)) "): ")
1499      (concat prompt ": "))
1500    table
1501    predicate
1502    require-match
1503    nil
1504    history
1505    (car (symbol-value history))))
1506
1507 (defun gnus-graphic-display-p ()
1508   (or (and (fboundp 'display-graphic-p)
1509            (display-graphic-p))
1510       ;;;!!!This is bogus.  Fixme!
1511       (and (featurep 'xemacs)
1512            t)))
1513
1514 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1515 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1516
1517 (defmacro gnus-parse-without-error (&rest body)
1518   "Allow continuing onto the next line even if an error occurs."
1519   `(while (not (eobp))
1520      (condition-case ()
1521          (progn
1522            ,@body
1523            (goto-char (point-max)))
1524        (error
1525         (gnus-error 4 "Invalid data on line %d"
1526                     (count-lines (point-min) (point)))
1527         (forward-line 1)))))
1528
1529 (defun gnus-cache-file-contents (file variable function)
1530   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1531   (let ((time (nth 5 (file-attributes file)))
1532         contents value)
1533     (if (or (null (setq value (symbol-value variable)))
1534             (not (equal (car value) file))
1535             (not (equal (nth 1 value) time)))
1536         (progn
1537           (setq contents (funcall function file))
1538           (set variable (list file time contents))
1539           contents)
1540       (nth 2 value))))
1541
1542 (defun gnus-multiple-choice (prompt choice &optional idx)
1543   "Ask user a multiple choice question.
1544 CHOICE is a list of the choice char and help message at IDX."
1545   (let (tchar buf)
1546     (save-window-excursion
1547       (save-excursion
1548         (while (not tchar)
1549           (message "%s (%s): "
1550                    prompt
1551                    (concat
1552                     (mapconcat (lambda (s) (char-to-string (car s)))
1553                                choice ", ") ", ?"))
1554           (setq tchar (read-char))
1555           (when (not (assq tchar choice))
1556             (setq tchar nil)
1557             (setq buf (get-buffer-create "*Gnus Help*"))
1558             (pop-to-buffer buf)
1559             (fundamental-mode)          ; for Emacs 20.4+
1560             (buffer-disable-undo)
1561             (erase-buffer)
1562             (insert prompt ":\n\n")
1563             (let ((max -1)
1564                   (list choice)
1565                   (alist choice)
1566                   (idx (or idx 1))
1567                   (i 0)
1568                   n width pad format)
1569               ;; find the longest string to display
1570               (while list
1571                 (setq n (length (nth idx (car list))))
1572                 (unless (> max n)
1573                   (setq max n))
1574                 (setq list (cdr list)))
1575               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1576               (setq n (/ (1- (window-width)) max)) ; items per line
1577               (setq width (/ (1- (window-width)) n)) ; width of each item
1578               ;; insert `n' items, each in a field of width `width'
1579               (while alist
1580                 (if (< i n)
1581                     ()
1582                   (setq i 0)
1583                   (delete-char -1)              ; the `\n' takes a char
1584                   (insert "\n"))
1585                 (setq pad (- width 3))
1586                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1587                 (insert (format format (caar alist) (nth idx (car alist))))
1588                 (setq alist (cdr alist))
1589                 (setq i (1+ i))))))))
1590     (if (buffer-live-p buf)
1591         (kill-buffer buf))
1592     tchar))
1593
1594 (declare-function x-focus-frame "xfns.c" (frame))
1595 (declare-function w32-focus-frame "../term/w32-win" (frame))
1596
1597 (defun gnus-select-frame-set-input-focus (frame)
1598   "Select FRAME, raise it, and set input focus, if possible."
1599   (cond ((featurep 'xemacs)
1600          (if (fboundp 'select-frame-set-input-focus)
1601              (select-frame-set-input-focus frame)
1602            (raise-frame frame)
1603            (select-frame frame)
1604            (focus-frame frame)))
1605         ;; `select-frame-set-input-focus' defined in Emacs 21 will not
1606         ;; set the input focus.
1607         ((>= emacs-major-version 22)
1608          (select-frame-set-input-focus frame))
1609         (t
1610          (raise-frame frame)
1611          (select-frame frame)
1612          (cond ((memq window-system '(x mac))
1613                 (x-focus-frame frame))
1614                ((eq window-system 'w32)
1615                 (w32-focus-frame frame)))
1616          (when focus-follows-mouse
1617            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1618
1619 (defun gnus-frame-or-window-display-name (object)
1620   "Given a frame or window, return the associated display name.
1621 Return nil otherwise."
1622   (if (featurep 'xemacs)
1623       (device-connection (dfw-device object))
1624     (if (or (framep object)
1625             (and (windowp object)
1626                  (setq object (window-frame object))))
1627         (let ((display (frame-parameter object 'display)))
1628           (if (and (stringp display)
1629                    ;; Exclude invalid display names.
1630                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1631                                  display))
1632               display)))))
1633
1634 (defvar tool-bar-mode)
1635
1636 (defun gnus-tool-bar-update (&rest ignore)
1637   "Update the tool bar."
1638   (when (and (boundp 'tool-bar-mode)
1639              tool-bar-mode)
1640     (let* ((args nil)
1641            (func (cond ((featurep 'xemacs)
1642                         'ignore)
1643                        ((fboundp 'tool-bar-update)
1644                         'tool-bar-update)
1645                        ((fboundp 'force-window-update)
1646                         'force-window-update)
1647                        ((fboundp 'redraw-frame)
1648                         (setq args (list (selected-frame)))
1649                         'redraw-frame)
1650                        (t 'ignore))))
1651       (apply func args))))
1652
1653 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1654 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1655   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1656 If there are several sequences, FUNCTION is called with that many arguments,
1657 and mapping stops as soon as the shortest sequence runs out.  With just one
1658 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1659 `mapcar' function extended to arbitrary sequence types."
1660
1661   (if seqs2_n
1662       (let* ((seqs (cons seq1 seqs2_n))
1663              (cnt 0)
1664              (heads (mapcar (lambda (seq)
1665                               (make-symbol (concat "head"
1666                                                    (int-to-string
1667                                                     (setq cnt (1+ cnt))))))
1668                             seqs))
1669              (result (make-symbol "result"))
1670              (result-tail (make-symbol "result-tail")))
1671         `(let* ,(let* ((bindings (cons nil nil))
1672                        (heads heads))
1673                   (nconc bindings (list (list result '(cons nil nil))))
1674                   (nconc bindings (list (list result-tail result)))
1675                   (while heads
1676                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1677                   (cdr bindings))
1678            (while (and ,@heads)
1679              (setcdr ,result-tail (cons (funcall ,function
1680                                                  ,@(mapcar (lambda (h) (list 'car h))
1681                                                            heads))
1682                                         nil))
1683              (setq ,result-tail (cdr ,result-tail)
1684                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1685            (cdr ,result)))
1686     `(mapcar ,function ,seq1)))
1687
1688 (if (fboundp 'merge)
1689     (defalias 'gnus-merge 'merge)
1690   ;; Adapted from cl-seq.el
1691   (defun gnus-merge (type list1 list2 pred)
1692     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1693 Argument TYPE is for compatibility and ignored.
1694 Ordering of the elements is preserved according to PRED, a `less-than'
1695 predicate on the elements."
1696     (let ((res nil))
1697       (while (and list1 list2)
1698         (if (funcall pred (car list2) (car list1))
1699             (push (pop list2) res)
1700           (push (pop list1) res)))
1701       (nconc (nreverse res) list1 list2))))
1702
1703 (defvar xemacs-codename)
1704 (defvar sxemacs-codename)
1705 (defvar emacs-program-version)
1706
1707 (defun gnus-emacs-version ()
1708   "Stringified Emacs version."
1709   (let* ((lst (if (listp gnus-user-agent)
1710                   gnus-user-agent
1711                 '(gnus emacs type)))
1712          (system-v (cond ((memq 'config lst)
1713                           system-configuration)
1714                          ((memq 'type lst)
1715                           (symbol-name system-type))
1716                          (t nil)))
1717          codename emacsname)
1718     (cond ((featurep 'sxemacs)
1719            (setq emacsname "SXEmacs"
1720                  codename sxemacs-codename))
1721           ((featurep 'xemacs)
1722            (setq emacsname "XEmacs"
1723                  codename xemacs-codename))
1724           (t
1725            (setq emacsname "Emacs")))
1726     (cond
1727      ((not (memq 'emacs lst))
1728       nil)
1729      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1730       ;; Emacs:
1731       (concat "Emacs/" (match-string 1 emacs-version)
1732               (if system-v
1733                   (concat " (" system-v ")")
1734                 "")))
1735      ((or (featurep 'sxemacs) (featurep 'xemacs))
1736       ;; XEmacs or SXEmacs:
1737       (concat emacsname "/" emacs-program-version
1738               (let (plst)
1739                 (when (memq 'codename lst)
1740                   (push codename plst))
1741                 (when system-v
1742                   (push system-v plst))
1743                 (unless (featurep 'mule)
1744                   (push "no MULE" plst))
1745                 (when (> (length plst) 0)
1746                   (concat
1747                    " (" (mapconcat 'identity (reverse plst) ", ") ")")))))
1748      (t emacs-version))))
1749
1750 (defun gnus-rename-file (old-path new-path &optional trim)
1751   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1752 empty directories from OLD-PATH."
1753   (when (file-exists-p old-path)
1754     (let* ((old-dir (file-name-directory old-path))
1755            (old-name (file-name-nondirectory old-path))
1756            (new-dir (file-name-directory new-path))
1757            (new-name (file-name-nondirectory new-path))
1758            temp)
1759       (gnus-make-directory new-dir)
1760       (rename-file old-path new-path t)
1761       (when trim
1762         (while (progn (setq temp (directory-files old-dir))
1763                       (while (member (car temp) '("." ".."))
1764                         (setq temp (cdr temp)))
1765                       (= (length temp) 0))
1766           (delete-directory old-dir)
1767           (setq old-dir (file-name-as-directory
1768                          (file-truename
1769                           (concat old-dir "..")))))))))
1770
1771 (defun gnus-set-file-modes (filename mode)
1772   "Wrapper for set-file-modes."
1773   (ignore-errors
1774     (set-file-modes filename mode)))
1775
1776 (if (fboundp 'set-process-query-on-exit-flag)
1777     (defalias 'gnus-set-process-query-on-exit-flag
1778       'set-process-query-on-exit-flag)
1779   (defalias 'gnus-set-process-query-on-exit-flag
1780     'process-kill-without-query))
1781
1782 (if (fboundp 'with-local-quit)
1783     (defalias 'gnus-with-local-quit 'with-local-quit)
1784   (defmacro gnus-with-local-quit (&rest body)
1785     "Execute BODY, allowing quits to terminate BODY but not escape further.
1786 When a quit terminates BODY, `gnus-with-local-quit' returns nil but
1787 requests another quit.  That quit will be processed as soon as quitting
1788 is allowed once again.  (Immediately, if `inhibit-quit' is nil.)"
1789     ;;(declare (debug t) (indent 0))
1790     `(condition-case nil
1791          (let ((inhibit-quit nil))
1792            ,@body)
1793        (quit (setq quit-flag t)
1794              ;; This call is to give a chance to handle quit-flag
1795              ;; in case inhibit-quit is nil.
1796              ;; Without this, it will not be handled until the next function
1797              ;; call, and that might allow it to exit thru a condition-case
1798              ;; that intends to handle the quit signal next time.
1799              (eval '(ignore nil))))))
1800
1801 (defalias 'gnus-read-shell-command
1802   (if (fboundp 'read-shell-command) 'read-shell-command 'read-string))
1803
1804 (provide 'gnus-util)
1805
1806 ;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
1807 ;;; gnus-util.el ends here