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