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