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