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