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