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