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