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