Wait for the end of the LIST ACTIVE command, if we're using that.
[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-duplicates (list)
875   "Remove duplicate entries from LIST."
876   (let ((result nil))
877     (while list
878       (unless (member (car list) result)
879         (push (car list) result))
880       (pop list))
881     (nreverse result)))
882
883 (defun gnus-delete-directory (directory)
884   "Delete files in DIRECTORY.  Subdirectories remain.
885 If there's no subdirectory, delete DIRECTORY as well."
886   (when (file-directory-p directory)
887     (let ((files (directory-files
888                   directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
889           file dir)
890       (while files
891         (setq file (pop files))
892         (if (eq t (car (file-attributes file)))
893             ;; `file' is a subdirectory.
894             (setq dir t)
895           ;; `file' is a file or a symlink.
896           (delete-file file)))
897       (unless dir
898         (delete-directory directory)))))
899
900 ;; The following two functions are used in gnus-registry.
901 ;; They were contributed by Andreas Fuchs <asf@void.at>.
902 (defun gnus-alist-to-hashtable (alist)
903   "Build a hashtable from the values in ALIST."
904   (let ((ht (make-hash-table
905              :size 4096
906              :test 'equal)))
907     (mapc
908      (lambda (kv-pair)
909        (puthash (car kv-pair) (cdr kv-pair) ht))
910      alist)
911      ht))
912
913 (defun gnus-hashtable-to-alist (hash)
914   "Build an alist from the values in HASH."
915   (let ((list nil))
916     (maphash
917      (lambda (key value)
918        (setq list (cons (cons key value) list)))
919      hash)
920     list))
921
922 (defun gnus-strip-whitespace (string)
923   "Return STRING stripped of all whitespace."
924   (while (string-match "[\r\n\t ]+" string)
925     (setq string (replace-match "" t t string)))
926   string)
927
928 (declare-function gnus-put-text-property "gnus"
929                   (start end property value &optional object))
930
931 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
932   "The same as `put-text-property', but don't put this prop on any newlines in the region."
933   (save-match-data
934     (save-excursion
935       (save-restriction
936         (goto-char beg)
937         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
938           (gnus-put-text-property beg (match-beginning 0) prop val)
939           (setq beg (point)))
940         (gnus-put-text-property beg (point) prop val)))))
941
942 (declare-function gnus-overlay-put  "gnus" (overlay prop value))
943 (declare-function gnus-make-overlay "gnus"
944                   (beg end &optional buffer front-advance rear-advance))
945
946 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
947   "The same as `put-text-property', but don't put this prop on any newlines in the region."
948   (save-match-data
949     (save-excursion
950       (save-restriction
951         (goto-char beg)
952         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
953           (gnus-overlay-put
954            (gnus-make-overlay beg (match-beginning 0))
955            prop val)
956           (setq beg (point)))
957         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
958
959 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
960                                                                    prop val)
961   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
962   (let ((b beg))
963     (while (/= b end)
964       (when (get-text-property b 'gnus-face)
965         (setq b (next-single-property-change b 'gnus-face nil end)))
966       (when (/= b end)
967         (inline
968           (gnus-put-text-property
969            b (setq b (next-single-property-change b 'gnus-face nil end))
970            prop val))))))
971
972 (defmacro gnus-faces-at (position)
973   "Return a list of faces at POSITION."
974   (if (featurep 'xemacs)
975       `(let ((pos ,position))
976          (mapcar-extents 'extent-face
977                          nil (current-buffer) pos pos nil 'face))
978     `(let ((pos ,position))
979        (delq nil (cons (get-text-property pos 'face)
980                        (mapcar
981                         (lambda (overlay)
982                           (overlay-get overlay 'face))
983                         (overlays-at pos)))))))
984
985 (if (fboundp 'invisible-p)
986     (defalias 'gnus-invisible-p 'invisible-p)
987   ;; for Emacs < 22.2, and XEmacs.
988   (defun gnus-invisible-p (pos)
989     "Return non-nil if the character after POS is currently invisible."
990     (let ((prop (get-char-property pos 'invisible)))
991       (if (eq buffer-invisibility-spec t)
992           prop
993         (or (memq prop buffer-invisibility-spec)
994             (assq prop buffer-invisibility-spec))))))
995
996 ;; Note: the optional 2nd argument has a different meaning between
997 ;; Emacs and XEmacs.
998 ;; (next-char-property-change POSITION &optional LIMIT)
999 ;; (next-extent-change        POS      &optional OBJECT)
1000 (defalias 'gnus-next-char-property-change
1001   (if (fboundp 'next-extent-change)
1002       'next-extent-change 'next-char-property-change))
1003
1004 (defalias 'gnus-previous-char-property-change
1005   (if (fboundp 'previous-extent-change)
1006       'previous-extent-change 'previous-char-property-change))
1007
1008 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
1009 ;; The primary idea here is to try to protect internal datastructures
1010 ;; from becoming corrupted when the user hits C-g, or if a hook or
1011 ;; similar blows up.  Often in Gnus multiple tables/lists need to be
1012 ;; updated at the same time, or information can be lost.
1013
1014 (defvar gnus-atomic-be-safe t
1015   "If t, certain operations will be protected from interruption by C-g.")
1016
1017 (defmacro gnus-atomic-progn (&rest forms)
1018   "Evaluate FORMS atomically, which means to protect the evaluation
1019 from being interrupted by the user.  An error from the forms themselves
1020 will return without finishing the operation.  Since interrupts from
1021 the user are disabled, it is recommended that only the most minimal
1022 operations are performed by FORMS.  If you wish to assign many
1023 complicated values atomically, compute the results into temporary
1024 variables and then do only the assignment atomically."
1025   `(let ((inhibit-quit gnus-atomic-be-safe))
1026      ,@forms))
1027
1028 (put 'gnus-atomic-progn 'lisp-indent-function 0)
1029
1030 (defmacro gnus-atomic-progn-assign (protect &rest forms)
1031   "Evaluate FORMS, but ensure that the variables listed in PROTECT
1032 are not changed if anything in FORMS signals an error or otherwise
1033 non-locally exits.  The variables listed in PROTECT are updated atomically.
1034 It is safe to use gnus-atomic-progn-assign with long computations.
1035
1036 Note that if any of the symbols in PROTECT were unbound, they will be
1037 set to nil on a successful assignment.  In case of an error or other
1038 non-local exit, it will still be unbound."
1039   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
1040                                                   (concat (symbol-name x)
1041                                                           "-tmp"))
1042                                                  x))
1043                                protect))
1044          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
1045                                temp-sym-map))
1046          (temp-sym-let (mapcar (lambda (x) (list (car x)
1047                                                  `(and (boundp ',(cadr x))
1048                                                        ,(cadr x))))
1049                                temp-sym-map))
1050          (sym-temp-let sym-temp-map)
1051          (temp-sym-assign (apply 'append temp-sym-map))
1052          (sym-temp-assign (apply 'append sym-temp-map))
1053          (result (make-symbol "result-tmp")))
1054     `(let (,@temp-sym-let
1055            ,result)
1056        (let ,sym-temp-let
1057          (setq ,result (progn ,@forms))
1058          (setq ,@temp-sym-assign))
1059        (let ((inhibit-quit gnus-atomic-be-safe))
1060          (setq ,@sym-temp-assign))
1061        ,result)))
1062
1063 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
1064 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
1065
1066 (defmacro gnus-atomic-setq (&rest pairs)
1067   "Similar to setq, except that the real symbols are only assigned when
1068 there are no errors.  And when the real symbols are assigned, they are
1069 done so atomically.  If other variables might be changed via side-effect,
1070 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
1071 with potentially long computations."
1072   (let ((tpairs pairs)
1073         syms)
1074     (while tpairs
1075       (push (car tpairs) syms)
1076       (setq tpairs (cddr tpairs)))
1077     `(gnus-atomic-progn-assign ,syms
1078        (setq ,@pairs))))
1079
1080 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
1081
1082
1083 ;;; Functions for saving to babyl/mail files.
1084
1085 (eval-when-compile
1086   (if (featurep 'xemacs)
1087       ;; Don't load tm and apel XEmacs packages that provide some
1088       ;; Emacs emulating functions and variables.
1089       (let ((features features))
1090         (provide 'tm-view)
1091         (unless (fboundp 'set-alist) (defalias 'set-alist 'ignore))
1092         (require 'rmail)) ;; It requires tm-view that loads apel.
1093     (require 'rmail))
1094   (autoload 'rmail-update-summary "rmailsum"))
1095
1096 (defvar mm-text-coding-system)
1097
1098 (declare-function mm-append-to-file "mm-util"
1099                   (start end filename &optional codesys inhibit))
1100
1101 (defun gnus-output-to-rmail (filename &optional ask)
1102   "Append the current article to an Rmail file named FILENAME.
1103 In Emacs 22 this writes Babyl format; in Emacs 23 it writes mbox unless
1104 FILENAME exists and is Babyl format."
1105   (require 'rmail)
1106   (require 'mm-util)
1107   (require 'nnmail)
1108   ;; Some of this codes is borrowed from rmailout.el.
1109   (setq filename (expand-file-name filename))
1110   ;; FIXME should we really be messing with this defcustom?
1111   ;; It is not needed for the operation of this function.
1112   (if (boundp 'rmail-default-rmail-file)
1113       (setq rmail-default-rmail-file filename) ; 22
1114     (setq rmail-default-file filename))        ; 23
1115   (let ((artbuf (current-buffer))
1116         (tmpbuf (get-buffer-create " *Gnus-output*"))
1117         ;; Babyl rmail.el defines this, mbox does not.
1118         (babyl (fboundp 'rmail-insert-rmail-file-header)))
1119     (save-excursion
1120       ;; Note that we ignore the possibility of visiting a Babyl
1121       ;; format buffer in Emacs 23, since Rmail no longer supports that.
1122      (or (get-file-buffer filename)
1123          (progn
1124            ;; In case someone wants to write to a Babyl file from Emacs 23.
1125            (when (file-exists-p filename)
1126              (setq babyl (mail-file-babyl-p filename))
1127              t))
1128           (if (or (not ask)
1129                   (gnus-yes-or-no-p
1130                    (concat "\"" filename "\" does not exist, create it? ")))
1131               (let ((file-buffer (create-file-buffer filename)))
1132                 (with-current-buffer file-buffer
1133                   (if (fboundp 'rmail-insert-rmail-file-header)
1134                       (rmail-insert-rmail-file-header))
1135                   (let ((require-final-newline nil)
1136                         (coding-system-for-write mm-text-coding-system))
1137                     (gnus-write-buffer filename)))
1138                 (kill-buffer file-buffer))
1139             (error "Output file does not exist")))
1140       (set-buffer tmpbuf)
1141       (erase-buffer)
1142       (insert-buffer-substring artbuf)
1143       (if babyl
1144           (gnus-convert-article-to-rmail)
1145         ;; Non-Babyl case copied from gnus-output-to-mail.
1146         (goto-char (point-min))
1147         (if (looking-at "From ")
1148             (forward-line 1)
1149           (insert "From nobody " (current-time-string) "\n"))
1150         (let (case-fold-search)
1151           (while (re-search-forward "^From " nil t)
1152             (beginning-of-line)
1153             (insert ">"))))
1154       ;; Decide whether to append to a file or to an Emacs buffer.
1155       (let ((outbuf (get-file-buffer filename)))
1156         (if (not outbuf)
1157             (progn
1158               (unless babyl             ; from gnus-output-to-mail
1159                 (let ((buffer-read-only nil))
1160                   (goto-char (point-max))
1161                   (forward-char -2)
1162                   (unless (looking-at "\n\n")
1163                     (goto-char (point-max))
1164                     (unless (bolp)
1165                       (insert "\n"))
1166                     (insert "\n"))))
1167               (let ((file-name-coding-system nnmail-pathname-coding-system))
1168                 (mm-append-to-file (point-min) (point-max) filename)))
1169           ;; File has been visited, in buffer OUTBUF.
1170           (set-buffer outbuf)
1171           (let ((buffer-read-only nil)
1172                 (msg (and (boundp 'rmail-current-message)
1173                           (symbol-value 'rmail-current-message))))
1174             ;; If MSG is non-nil, buffer is in RMAIL mode.
1175             ;; Compare this with rmail-output-to-rmail-buffer in Emacs 23.
1176             (when msg
1177               (unless babyl
1178                 (rmail-swap-buffers-maybe)
1179                 (rmail-maybe-set-message-counters))
1180               (widen)
1181               (narrow-to-region (point-max) (point-max)))
1182             (insert-buffer-substring tmpbuf)
1183             (when msg
1184               (when babyl
1185                 (goto-char (point-min))
1186                 (widen)
1187                 (search-backward "\n\^_")
1188                 (narrow-to-region (point) (point-max)))
1189               (rmail-count-new-messages t)
1190               (when (rmail-summary-exists)
1191                 (rmail-select-summary
1192                  (rmail-update-summary)))
1193               (rmail-show-message msg))
1194             (save-buffer)))))
1195     (kill-buffer tmpbuf)))
1196
1197 (defun gnus-output-to-mail (filename &optional ask)
1198   "Append the current article to a mail file named FILENAME."
1199   (require 'nnmail)
1200   (setq filename (expand-file-name filename))
1201   (let ((artbuf (current-buffer))
1202         (tmpbuf (get-buffer-create " *Gnus-output*")))
1203     (save-excursion
1204       ;; Create the file, if it doesn't exist.
1205       (when (and (not (get-file-buffer filename))
1206                  (not (file-exists-p filename)))
1207         (if (or (not ask)
1208                 (gnus-y-or-n-p
1209                  (concat "\"" filename "\" does not exist, create it? ")))
1210             (let ((file-buffer (create-file-buffer filename)))
1211               (with-current-buffer file-buffer
1212                 (let ((require-final-newline nil)
1213                       (coding-system-for-write mm-text-coding-system))
1214                   (gnus-write-buffer filename)))
1215               (kill-buffer file-buffer))
1216           (error "Output file does not exist")))
1217       (set-buffer tmpbuf)
1218       (erase-buffer)
1219       (insert-buffer-substring artbuf)
1220       (goto-char (point-min))
1221       (if (looking-at "From ")
1222           (forward-line 1)
1223         (insert "From nobody " (current-time-string) "\n"))
1224       (let (case-fold-search)
1225         (while (re-search-forward "^From " nil t)
1226           (beginning-of-line)
1227           (insert ">")))
1228       ;; Decide whether to append to a file or to an Emacs buffer.
1229       (let ((outbuf (get-file-buffer filename)))
1230         (if (not outbuf)
1231             (let ((buffer-read-only nil))
1232               (save-excursion
1233                 (goto-char (point-max))
1234                 (forward-char -2)
1235                 (unless (looking-at "\n\n")
1236                   (goto-char (point-max))
1237                   (unless (bolp)
1238                     (insert "\n"))
1239                   (insert "\n"))
1240                 (goto-char (point-max))
1241                 (let ((file-name-coding-system nnmail-pathname-coding-system))
1242                   (mm-append-to-file (point-min) (point-max) filename))))
1243           ;; File has been visited, in buffer OUTBUF.
1244           (set-buffer outbuf)
1245           (let ((buffer-read-only nil))
1246             (goto-char (point-max))
1247             (unless (eobp)
1248               (insert "\n"))
1249             (insert "\n")
1250             (insert-buffer-substring tmpbuf)))))
1251     (kill-buffer tmpbuf)))
1252
1253 (defun gnus-convert-article-to-rmail ()
1254   "Convert article in current buffer to Rmail message format."
1255   (let ((buffer-read-only nil))
1256     ;; Convert article directly into Babyl format.
1257     (goto-char (point-min))
1258     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1259     (while (search-forward "\n\^_" nil t) ;single char
1260       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
1261     (goto-char (point-max))
1262     (insert "\^_")))
1263
1264 (defun gnus-map-function (funs arg)
1265   "Apply the result of the first function in FUNS to the second, and so on.
1266 ARG is passed to the first function."
1267   (while funs
1268     (setq arg (funcall (pop funs) arg)))
1269   arg)
1270
1271 (defun gnus-run-hooks (&rest funcs)
1272   "Does the same as `run-hooks', but saves the current buffer."
1273   (save-current-buffer
1274     (apply 'run-hooks funcs)))
1275
1276 (defun gnus-run-hook-with-args (hook &rest args)
1277   "Does the same as `run-hook-with-args', but saves the current buffer."
1278   (save-current-buffer
1279     (apply 'run-hook-with-args hook args)))
1280
1281 (defun gnus-run-mode-hooks (&rest funcs)
1282   "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1283 This function saves the current buffer."
1284   (if (fboundp 'run-mode-hooks)
1285       (save-current-buffer (apply 'run-mode-hooks funcs))
1286     (save-current-buffer (apply 'run-hooks funcs))))
1287
1288 ;;; Various
1289
1290 (defvar gnus-group-buffer)              ; Compiler directive
1291 (defun gnus-alive-p ()
1292   "Say whether Gnus is running or not."
1293   (and (boundp 'gnus-group-buffer)
1294        (get-buffer gnus-group-buffer)
1295        (with-current-buffer gnus-group-buffer
1296          (eq major-mode 'gnus-group-mode))))
1297
1298 (defun gnus-remove-if (predicate sequence &optional hash-table-p)
1299   "Return a copy of SEQUENCE with all items satisfying PREDICATE removed.
1300 SEQUENCE should be a list, a vector, or a string.  Returns always a list.
1301 If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
1302   (let (out)
1303     (if hash-table-p
1304         (mapatoms (lambda (symbol)
1305                     (unless (funcall predicate symbol)
1306                       (push symbol out)))
1307                   sequence)
1308       (unless (listp sequence)
1309         (setq sequence (append sequence nil)))
1310       (while sequence
1311         (unless (funcall predicate (car sequence))
1312           (push (car sequence) out))
1313         (setq sequence (cdr sequence))))
1314     (nreverse out)))
1315
1316 (defun gnus-remove-if-not (predicate sequence &optional hash-table-p)
1317   "Return a copy of SEQUENCE with all items not satisfying PREDICATE removed.
1318 SEQUENCE should be a list, a vector, or a string.  Returns always a list.
1319 If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
1320   (let (out)
1321     (if hash-table-p
1322         (mapatoms (lambda (symbol)
1323                     (when (funcall predicate symbol)
1324                       (push symbol out)))
1325                   sequence)
1326       (unless (listp sequence)
1327         (setq sequence (append sequence nil)))
1328       (while sequence
1329         (when (funcall predicate (car sequence))
1330           (push (car sequence) out))
1331         (setq sequence (cdr sequence))))
1332     (nreverse out)))
1333
1334 (if (fboundp 'assq-delete-all)
1335     (defalias 'gnus-delete-alist 'assq-delete-all)
1336   (defun gnus-delete-alist (key alist)
1337     "Delete from ALIST all elements whose car is KEY.
1338 Return the modified alist."
1339     (let (entry)
1340       (while (setq entry (assq key alist))
1341         (setq alist (delq entry alist)))
1342       alist)))
1343
1344 (defun gnus-grep-in-list (word list)
1345   "Find if a WORD matches any regular expression in the given LIST."
1346   (when (and word list)
1347     (catch 'found
1348       (dolist (r list)
1349         (when (string-match r word)
1350           (throw 'found r))))))
1351
1352 (defmacro gnus-alist-pull (key alist &optional assoc-p)
1353   "Modify ALIST to be without KEY."
1354   (unless (symbolp alist)
1355     (error "Not a symbol: %s" alist))
1356   (let ((fun (if assoc-p 'assoc 'assq)))
1357     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1358
1359 (defun gnus-globalify-regexp (re)
1360   "Return a regexp that matches a whole line, if RE matches a part of it."
1361   (concat (unless (string-match "^\\^" re) "^.*")
1362           re
1363           (unless (string-match "\\$$" re) ".*$")))
1364
1365 (defun gnus-set-window-start (&optional point)
1366   "Set the window start to POINT, or (point) if nil."
1367   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1368     (when win
1369       (set-window-start win (or point (point))))))
1370
1371 (defun gnus-annotation-in-region-p (b e)
1372   (if (= b e)
1373       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1374     (text-property-any b e 'gnus-undeletable t)))
1375
1376 (defun gnus-or (&rest elems)
1377   "Return non-nil if any of the elements are non-nil."
1378   (catch 'found
1379     (while elems
1380       (when (pop elems)
1381         (throw 'found t)))))
1382
1383 (defun gnus-and (&rest elems)
1384   "Return non-nil if all of the elements are non-nil."
1385   (catch 'found
1386     (while elems
1387       (unless (pop elems)
1388         (throw 'found nil)))
1389     t))
1390
1391 ;; gnus.el requires mm-util.
1392 (declare-function mm-disable-multibyte "mm-util")
1393
1394 (defun gnus-write-active-file (file hashtb &optional full-names)
1395   ;; `coding-system-for-write' should be `raw-text' or equivalent.
1396   (let ((coding-system-for-write nnmail-active-file-coding-system))
1397     (with-temp-file file
1398       ;; The buffer should be in the unibyte mode because group names
1399       ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1400       (mm-disable-multibyte)
1401       (mapatoms
1402        (lambda (sym)
1403          (when (and sym
1404                     (boundp sym)
1405                     (symbol-value sym))
1406            (insert (format "%S %d %d y\n"
1407                            (if full-names
1408                                sym
1409                              (intern (gnus-group-real-name (symbol-name sym))))
1410                            (or (cdr (symbol-value sym))
1411                                (car (symbol-value sym)))
1412                            (car (symbol-value sym))))))
1413        hashtb)
1414       (goto-char (point-max))
1415       (while (search-backward "\\." nil t)
1416         (delete-char 1)))))
1417
1418 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1419 (defmacro gnus-with-output-to-file (file &rest body)
1420   (let ((buffer (make-symbol "output-buffer"))
1421         (size (make-symbol "output-buffer-size"))
1422         (leng (make-symbol "output-buffer-length"))
1423         (append (make-symbol "output-buffer-append")))
1424     `(let* ((,size 131072)
1425             (,buffer (make-string ,size 0))
1426             (,leng 0)
1427             (,append nil)
1428             (standard-output
1429              (lambda (c)
1430                (aset ,buffer ,leng c)
1431
1432                (if (= ,size (setq ,leng (1+ ,leng)))
1433                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1434                           (setq ,leng 0
1435                                 ,append t))))))
1436        ,@body
1437        (when (> ,leng 0)
1438          (let ((coding-system-for-write 'no-conversion))
1439          (write-region (substring ,buffer 0 ,leng) nil ,file
1440                        ,append 'no-msg))))))
1441
1442 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1443 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1444
1445 (if (fboundp 'union)
1446     (defalias 'gnus-union 'union)
1447   (defun gnus-union (l1 l2)
1448     "Set union of lists L1 and L2."
1449     (cond ((null l1) l2)
1450           ((null l2) l1)
1451           ((equal l1 l2) l1)
1452           (t
1453            (or (>= (length l1) (length l2))
1454                (setq l1 (prog1 l2 (setq l2 l1))))
1455            (while l2
1456              (or (member (car l2) l1)
1457                  (push (car l2) l1))
1458              (pop l2))
1459            l1))))
1460
1461 (declare-function gnus-add-text-properties "gnus"
1462                   (start end properties &optional object))
1463
1464 (defun gnus-add-text-properties-when
1465   (property value start end properties &optional object)
1466   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1467   (let (point)
1468     (while (and start
1469                 (< start end) ;; XEmacs will loop for every when start=end.
1470                 (setq point (text-property-not-all start end property value)))
1471       (gnus-add-text-properties start point properties object)
1472       (setq start (text-property-any point end property value)))
1473     (if start
1474         (gnus-add-text-properties start end properties object))))
1475
1476 (defun gnus-remove-text-properties-when
1477   (property value start end properties &optional object)
1478   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1479   (let (point)
1480     (while (and start
1481                 (< start end)
1482                 (setq point (text-property-not-all start end property value)))
1483       (remove-text-properties start point properties object)
1484       (setq start (text-property-any point end property value)))
1485     (if start
1486         (remove-text-properties start end properties object))
1487     t))
1488
1489 (defun gnus-string-remove-all-properties (string)
1490   (condition-case ()
1491       (let ((s string))
1492         (set-text-properties 0 (length string) nil string)
1493         s)
1494     (error string)))
1495
1496 ;; This might use `compare-strings' to reduce consing in the
1497 ;; case-insensitive case, but it has to cope with null args.
1498 ;; (`string-equal' uses symbol print names.)
1499 (defun gnus-string-equal (x y)
1500   "Like `string-equal', except it compares case-insensitively."
1501   (and (= (length x) (length y))
1502        (or (string-equal x y)
1503            (string-equal (downcase x) (downcase y)))))
1504
1505 (defcustom gnus-use-byte-compile t
1506   "If non-nil, byte-compile crucial run-time code.
1507 Setting it to nil has no effect after the first time `gnus-byte-compile'
1508 is run."
1509   :type 'boolean
1510   :version "22.1"
1511   :group 'gnus-various)
1512
1513 (defun gnus-byte-compile (form)
1514   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1515   (if gnus-use-byte-compile
1516       (progn
1517         (condition-case nil
1518             ;; Work around a bug in XEmacs 21.4
1519             (require 'byte-optimize)
1520           (error))
1521         (require 'bytecomp)
1522         (defalias 'gnus-byte-compile
1523           (lambda (form)
1524             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1525               (byte-compile form))))
1526         (gnus-byte-compile form))
1527     form))
1528
1529 (defun gnus-remassoc (key alist)
1530   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1531 The modified LIST is returned.  If the first member
1532 of LIST has a car that is `equal' to KEY, there is no way to remove it
1533 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1534 sure of changing the value of `foo'."
1535   (when alist
1536     (if (equal key (caar alist))
1537         (cdr alist)
1538       (setcdr alist (gnus-remassoc key (cdr alist)))
1539       alist)))
1540
1541 (defun gnus-update-alist-soft (key value alist)
1542   (if value
1543       (cons (cons key value) (gnus-remassoc key alist))
1544     (gnus-remassoc key alist)))
1545
1546 (defun gnus-create-info-command (node)
1547   "Create a command that will go to info NODE."
1548   `(lambda ()
1549      (interactive)
1550      ,(concat "Enter the info system at node " node)
1551      (Info-goto-node ,node)
1552      (setq gnus-info-buffer (current-buffer))
1553      (gnus-configure-windows 'info)))
1554
1555 (defun gnus-not-ignore (&rest args)
1556   t)
1557
1558 (defvar gnus-directory-sep-char-regexp "/"
1559   "The regexp of directory separator character.
1560 If you find some problem with the directory separator character, try
1561 \"[/\\\\\]\" for some systems.")
1562
1563 (defun gnus-url-unhex (x)
1564   (if (> x ?9)
1565       (if (>= x ?a)
1566           (+ 10 (- x ?a))
1567         (+ 10 (- x ?A)))
1568     (- x ?0)))
1569
1570 ;; Fixme: Do it like QP.
1571 (defun gnus-url-unhex-string (str &optional allow-newlines)
1572   "Remove %XX, embedded spaces, etc in a url.
1573 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1574 decoding of carriage returns and line feeds in the string, which is normally
1575 forbidden in URL encoding."
1576   (let ((tmp "")
1577         (case-fold-search t))
1578     (while (string-match "%[0-9a-f][0-9a-f]" str)
1579       (let* ((start (match-beginning 0))
1580              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1581              (code (+ (* 16 ch1)
1582                       (gnus-url-unhex (elt str (+ start 2))))))
1583         (setq tmp (concat
1584                    tmp (substring str 0 start)
1585                    (cond
1586                     (allow-newlines
1587                      (char-to-string code))
1588                     ((or (= code ?\n) (= code ?\r))
1589                      " ")
1590                     (t (char-to-string code))))
1591               str (substring str (match-end 0)))))
1592     (setq tmp (concat tmp str))
1593     tmp))
1594
1595 (defun gnus-make-predicate (spec)
1596   "Transform SPEC into a function that can be called.
1597 SPEC is a predicate specifier that contains stuff like `or', `and',
1598 `not', lists and functions.  The functions all take one parameter."
1599   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1600
1601 (defun gnus-make-predicate-1 (spec)
1602   (cond
1603    ((symbolp spec)
1604     `(,spec elem))
1605    ((listp spec)
1606     (if (memq (car spec) '(or and not))
1607         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1608       (error "Invalid predicate specifier: %s" spec)))))
1609
1610 (defun gnus-completing-read (prompt collection &optional require-match
1611                                     initial-input history def)
1612   "Call `gnus-completing-read-function'."
1613   (funcall gnus-completing-read-function
1614            (concat prompt (when def
1615                             (concat " (default " def ")"))
1616                    ": ")
1617            collection require-match initial-input history def))
1618
1619 (defun gnus-emacs-completing-read (prompt collection &optional require-match
1620                                           initial-input history def)
1621   "Call standard `completing-read-function'."
1622   (let ((completion-styles gnus-completion-styles))
1623     (completing-read prompt
1624                      ;; Old XEmacs (at least 21.4) expect an alist for
1625                      ;; collection.
1626                      (mapcar 'list collection)
1627                      nil require-match initial-input history def)))
1628
1629 (autoload 'ido-completing-read "ido")
1630 (defun gnus-ido-completing-read (prompt collection &optional require-match
1631                                         initial-input history def)
1632   "Call `ido-completing-read-function'."
1633   (ido-completing-read prompt collection nil require-match
1634                        initial-input history def))
1635
1636
1637 (declare-function iswitchb-read-buffer "iswitchb"
1638                   (prompt &optional default require-match start matches-set))
1639 (defvar iswitchb-temp-buflist)
1640
1641 (defun gnus-iswitchb-completing-read (prompt collection &optional require-match
1642                                             initial-input history def)
1643   "`iswitchb' based completing-read function."
1644   ;; Make sure iswitchb is loaded before we let-bind its variables.
1645   ;; If it is loaded inside the let, variables can become unbound afterwards.
1646   (require 'iswitchb)
1647   (let ((iswitchb-make-buflist-hook
1648          (lambda ()
1649            (setq iswitchb-temp-buflist
1650                  (let ((choices (append
1651                                  (when initial-input (list initial-input))
1652                                  (symbol-value history) collection))
1653                        filtered-choices)
1654                    (dolist (x choices)
1655                      (setq filtered-choices (adjoin x filtered-choices)))
1656                    (nreverse filtered-choices))))))
1657     (unwind-protect
1658         (progn
1659           (or iswitchb-mode
1660               (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup))
1661           (iswitchb-read-buffer prompt def require-match))
1662       (or iswitchb-mode
1663           (remove-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)))))
1664
1665 (defun gnus-graphic-display-p ()
1666   (if (featurep 'xemacs)
1667       (device-on-window-system-p)
1668     (display-graphic-p)))
1669
1670 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1671 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1672
1673 (defmacro gnus-parse-without-error (&rest body)
1674   "Allow continuing onto the next line even if an error occurs."
1675   `(while (not (eobp))
1676      (condition-case ()
1677          (progn
1678            ,@body
1679            (goto-char (point-max)))
1680        (error
1681         (gnus-error 4 "Invalid data on line %d"
1682                     (count-lines (point-min) (point)))
1683         (forward-line 1)))))
1684
1685 (defun gnus-cache-file-contents (file variable function)
1686   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1687   (let ((time (nth 5 (file-attributes file)))
1688         contents value)
1689     (if (or (null (setq value (symbol-value variable)))
1690             (not (equal (car value) file))
1691             (not (equal (nth 1 value) time)))
1692         (progn
1693           (setq contents (funcall function file))
1694           (set variable (list file time contents))
1695           contents)
1696       (nth 2 value))))
1697
1698 (defun gnus-multiple-choice (prompt choice &optional idx)
1699   "Ask user a multiple choice question.
1700 CHOICE is a list of the choice char and help message at IDX."
1701   (let (tchar buf)
1702     (save-window-excursion
1703       (save-excursion
1704         (while (not tchar)
1705           (message "%s (%s): "
1706                    prompt
1707                    (concat
1708                     (mapconcat (lambda (s) (char-to-string (car s)))
1709                                choice ", ") ", ?"))
1710           (setq tchar (read-char))
1711           (when (not (assq tchar choice))
1712             (setq tchar nil)
1713             (setq buf (get-buffer-create "*Gnus Help*"))
1714             (pop-to-buffer buf)
1715             (fundamental-mode)          ; for Emacs 20.4+
1716             (buffer-disable-undo)
1717             (erase-buffer)
1718             (insert prompt ":\n\n")
1719             (let ((max -1)
1720                   (list choice)
1721                   (alist choice)
1722                   (idx (or idx 1))
1723                   (i 0)
1724                   n width pad format)
1725               ;; find the longest string to display
1726               (while list
1727                 (setq n (length (nth idx (car list))))
1728                 (unless (> max n)
1729                   (setq max n))
1730                 (setq list (cdr list)))
1731               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1732               (setq n (/ (1- (window-width)) max)) ; items per line
1733               (setq width (/ (1- (window-width)) n)) ; width of each item
1734               ;; insert `n' items, each in a field of width `width'
1735               (while alist
1736                 (if (< i n)
1737                     ()
1738                   (setq i 0)
1739                   (delete-char -1)              ; the `\n' takes a char
1740                   (insert "\n"))
1741                 (setq pad (- width 3))
1742                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1743                 (insert (format format (caar alist) (nth idx (car alist))))
1744                 (setq alist (cdr alist))
1745                 (setq i (1+ i))))))))
1746     (if (buffer-live-p buf)
1747         (kill-buffer buf))
1748     tchar))
1749
1750 (if (featurep 'emacs)
1751     (defalias 'gnus-select-frame-set-input-focus 'select-frame-set-input-focus)
1752   (if (fboundp 'select-frame-set-input-focus)
1753       (defalias 'gnus-select-frame-set-input-focus 'select-frame-set-input-focus)
1754     ;; XEmacs 21.4, SXEmacs
1755     (defun gnus-select-frame-set-input-focus (frame)
1756       "Select FRAME, raise it, and set input focus, if possible."
1757       (raise-frame frame)
1758       (select-frame frame)
1759       (focus-frame frame))))
1760
1761 (defun gnus-frame-or-window-display-name (object)
1762   "Given a frame or window, return the associated display name.
1763 Return nil otherwise."
1764   (if (featurep 'xemacs)
1765       (device-connection (dfw-device object))
1766     (if (or (framep object)
1767             (and (windowp object)
1768                  (setq object (window-frame object))))
1769         (let ((display (frame-parameter object 'display)))
1770           (if (and (stringp display)
1771                    ;; Exclude invalid display names.
1772                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1773                                  display))
1774               display)))))
1775
1776 (defvar tool-bar-mode)
1777
1778 (defun gnus-tool-bar-update (&rest ignore)
1779   "Update the tool bar."
1780   (when (and (boundp 'tool-bar-mode)
1781              tool-bar-mode)
1782     (let* ((args nil)
1783            (func (cond ((featurep 'xemacs)
1784                         'ignore)
1785                        ((fboundp 'tool-bar-update)
1786                         'tool-bar-update)
1787                        ((fboundp 'force-window-update)
1788                         'force-window-update)
1789                        ((fboundp 'redraw-frame)
1790                         (setq args (list (selected-frame)))
1791                         'redraw-frame)
1792                        (t 'ignore))))
1793       (apply func args))))
1794
1795 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1796 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1797   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1798 If there are several sequences, FUNCTION is called with that many arguments,
1799 and mapping stops as soon as the shortest sequence runs out.  With just one
1800 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1801 `mapcar' function extended to arbitrary sequence types."
1802
1803   (if seqs2_n
1804       (let* ((seqs (cons seq1 seqs2_n))
1805              (cnt 0)
1806              (heads (mapcar (lambda (seq)
1807                               (make-symbol (concat "head"
1808                                                    (int-to-string
1809                                                     (setq cnt (1+ cnt))))))
1810                             seqs))
1811              (result (make-symbol "result"))
1812              (result-tail (make-symbol "result-tail")))
1813         `(let* ,(let* ((bindings (cons nil nil))
1814                        (heads heads))
1815                   (nconc bindings (list (list result '(cons nil nil))))
1816                   (nconc bindings (list (list result-tail result)))
1817                   (while heads
1818                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1819                   (cdr bindings))
1820            (while (and ,@heads)
1821              (setcdr ,result-tail (cons (funcall ,function
1822                                                  ,@(mapcar (lambda (h) (list 'car h))
1823                                                            heads))
1824                                         nil))
1825              (setq ,result-tail (cdr ,result-tail)
1826                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1827            (cdr ,result)))
1828     `(mapcar ,function ,seq1)))
1829
1830 (if (fboundp 'merge)
1831     (defalias 'gnus-merge 'merge)
1832   ;; Adapted from cl-seq.el
1833   (defun gnus-merge (type list1 list2 pred)
1834     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1835 Argument TYPE is for compatibility and ignored.
1836 Ordering of the elements is preserved according to PRED, a `less-than'
1837 predicate on the elements."
1838     (let ((res nil))
1839       (while (and list1 list2)
1840         (if (funcall pred (car list2) (car list1))
1841             (push (pop list2) res)
1842           (push (pop list1) res)))
1843       (nconc (nreverse res) list1 list2))))
1844
1845 (defvar xemacs-codename)
1846 (defvar sxemacs-codename)
1847 (defvar emacs-program-version)
1848
1849 (defun gnus-emacs-version ()
1850   "Stringified Emacs version."
1851   (let* ((lst (if (listp gnus-user-agent)
1852                   gnus-user-agent
1853                 '(gnus emacs type)))
1854          (system-v (cond ((memq 'config lst)
1855                           system-configuration)
1856                          ((memq 'type lst)
1857                           (symbol-name system-type))
1858                          (t nil)))
1859          codename emacsname)
1860     (cond ((featurep 'sxemacs)
1861            (setq emacsname "SXEmacs"
1862                  codename sxemacs-codename))
1863           ((featurep 'xemacs)
1864            (setq emacsname "XEmacs"
1865                  codename xemacs-codename))
1866           (t
1867            (setq emacsname "Emacs")))
1868     (cond
1869      ((not (memq 'emacs lst))
1870       nil)
1871      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1872       ;; Emacs:
1873       (concat "Emacs/" (match-string 1 emacs-version)
1874               (if system-v
1875                   (concat " (" system-v ")")
1876                 "")))
1877      ((or (featurep 'sxemacs) (featurep 'xemacs))
1878       ;; XEmacs or SXEmacs:
1879       (concat emacsname "/" emacs-program-version
1880               (let (plst)
1881                 (when (memq 'codename lst)
1882                   (push codename plst))
1883                 (when system-v
1884                   (push system-v plst))
1885                 (unless (featurep 'mule)
1886                   (push "no MULE" plst))
1887                 (when (> (length plst) 0)
1888                   (concat
1889                    " (" (mapconcat 'identity (reverse plst) ", ") ")")))))
1890      (t emacs-version))))
1891
1892 (defun gnus-rename-file (old-path new-path &optional trim)
1893   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1894 empty directories from OLD-PATH."
1895   (when (file-exists-p old-path)
1896     (let* ((old-dir (file-name-directory old-path))
1897            (old-name (file-name-nondirectory old-path))
1898            (new-dir (file-name-directory new-path))
1899            (new-name (file-name-nondirectory new-path))
1900            temp)
1901       (gnus-make-directory new-dir)
1902       (rename-file old-path new-path t)
1903       (when trim
1904         (while (progn (setq temp (directory-files old-dir))
1905                       (while (member (car temp) '("." ".."))
1906                         (setq temp (cdr temp)))
1907                       (= (length temp) 0))
1908           (delete-directory old-dir)
1909           (setq old-dir (file-name-as-directory
1910                          (file-truename
1911                           (concat old-dir "..")))))))))
1912
1913 (defun gnus-set-file-modes (filename mode)
1914   "Wrapper for set-file-modes."
1915   (ignore-errors
1916     (set-file-modes filename mode)))
1917
1918 (if (fboundp 'set-process-query-on-exit-flag)
1919     (defalias 'gnus-set-process-query-on-exit-flag
1920       'set-process-query-on-exit-flag)
1921   (defalias 'gnus-set-process-query-on-exit-flag
1922     'process-kill-without-query))
1923
1924 (defalias 'gnus-read-shell-command
1925   (if (fboundp 'read-shell-command) 'read-shell-command 'read-string))
1926
1927 (defmacro gnus-put-display-table (range value display-table)
1928   "Set the value for char RANGE to VALUE in DISPLAY-TABLE.  "
1929   (if (featurep 'xemacs)
1930       (progn
1931         `(if (fboundp 'put-display-table)
1932           (put-display-table ,range ,value ,display-table)
1933           (if (sequencep ,display-table)
1934               (aset ,display-table ,range ,value)
1935             (put-char-table ,range ,value ,display-table))))
1936     `(aset ,display-table ,range ,value)))
1937
1938 (defmacro gnus-get-display-table (character display-table)
1939   "Find value for CHARACTER in DISPLAY-TABLE.  "
1940   (if (featurep 'xemacs)
1941       `(if (fboundp 'get-display-table)
1942           (get-display-table ,character ,display-table)
1943           (if (sequencep ,display-table)
1944               (aref ,display-table ,character)
1945             (get-char-table ,character ,display-table)))
1946     `(aref ,display-table ,character)))
1947
1948 (defun gnus-rescale-image (image size)
1949   "Rescale IMAGE to SIZE if possible.
1950 SIZE is in format (WIDTH . HEIGHT). Return a new image.
1951 Sizes are in pixels."
1952   (if (or (not (fboundp 'imagemagick-types))
1953           (not (get-buffer-window (current-buffer))))
1954       image
1955     (let ((new-width (car size))
1956           (new-height (cdr size)))
1957       (when (> (cdr (image-size image t)) new-height)
1958         (setq image (or (create-image (plist-get (cdr image) :data) 'imagemagick t
1959                                       :height new-height)
1960                         image)))
1961       (when (> (car (image-size image t)) new-width)
1962         (setq image (or
1963                    (create-image (plist-get (cdr image) :data) 'imagemagick t
1964                                  :width new-width)
1965                    image)))
1966       image)))
1967
1968 (defun gnus-list-memq-of-list (elements list)
1969   "Return non-nil if any of the members of ELEMENTS are in LIST."
1970   (let ((found nil))
1971     (dolist (elem elements)
1972       (setq found (or found
1973                       (memq elem list))))
1974     found))
1975
1976 (eval-and-compile
1977   (cond
1978    ((fboundp 'match-substitute-replacement)
1979     (defalias 'gnus-match-substitute-replacement 'match-substitute-replacement))
1980    (t
1981     (defun gnus-match-substitute-replacement (replacement &optional fixedcase literal string subexp)
1982       "Return REPLACEMENT as it will be inserted by `replace-match'.
1983 In other words, all back-references in the form `\\&' and `\\N'
1984 are substituted with actual strings matched by the last search.
1985 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
1986 meaning as for `replace-match'.
1987
1988 This is the definition of match-substitute-replacement in subr.el from GNU Emacs."
1989       (let ((match (match-string 0 string)))
1990         (save-match-data
1991           (set-match-data (mapcar (lambda (x)
1992                                     (if (numberp x)
1993                                         (- x (match-beginning 0))
1994                                       x))
1995                                   (match-data t)))
1996           (replace-match replacement fixedcase literal match subexp)))))))
1997
1998 (if (fboundp 'string-match-p)
1999     (defalias 'gnus-string-match-p 'string-match-p)
2000   (defsubst gnus-string-match-p (regexp string &optional start)
2001     "\
2002 Same as `string-match' except this function does not change the match data."
2003     (save-match-data
2004       (string-match regexp string start))))
2005
2006 (eval-and-compile
2007   (if (fboundp 'macroexpand-all)
2008       (defalias 'gnus-macroexpand-all 'macroexpand-all)
2009     (defun gnus-macroexpand-all (form &optional environment)
2010       "Return result of expanding macros at all levels in FORM.
2011 If no macros are expanded, FORM is returned unchanged.
2012 The second optional arg ENVIRONMENT specifies an environment of macro
2013 definitions to shadow the loaded ones for use in file byte-compilation."
2014       (if (consp form)
2015           (let ((idx 1)
2016                 (len (length (setq form (copy-sequence form))))
2017                 expanded)
2018             (while (< idx len)
2019               (setcar (nthcdr idx form) (gnus-macroexpand-all (nth idx form)
2020                                                               environment))
2021               (setq idx (1+ idx)))
2022             (if (eq (setq expanded (macroexpand form environment)) form)
2023                 form
2024               (gnus-macroexpand-all expanded environment)))
2025         form))))
2026
2027 (provide 'gnus-util)
2028
2029 ;;; gnus-util.el ends here