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