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