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