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