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