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