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