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