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