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