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