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