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