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