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