Change the message to "available fonts".
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Nothing in this file depends on any other parts of Gnus -- all
28 ;; functions and macros in this file are utility functions that are
29 ;; used by Gnus and may be used by any other package without loading
30 ;; Gnus first.
31
32 ;;; Code:
33
34 (require 'custom)
35 (eval-when-compile
36   (require 'cl)
37   ;; Fixme: this should be a gnus variable, not nnmail-.
38   (defvar nnmail-pathname-coding-system))
39 (require 'nnheader)
40 (require 'time-date)
41
42 (eval-and-compile
43   (autoload 'message-fetch-field "message")
44   (autoload 'rmail-insert-rmail-file-header "rmail")
45   (autoload 'rmail-count-new-messages "rmail")
46   (autoload 'rmail-show-message "rmail"))
47
48 (defun gnus-boundp (variable)
49   "Return non-nil if VARIABLE is bound and non-nil."
50   (and (boundp variable)
51        (symbol-value variable)))
52
53 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
54   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
55   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
56         (w (make-symbol "w"))
57         (buf (make-symbol "buf")))
58     `(let* ((,tempvar (selected-window))
59             (,buf ,buffer)
60             (,w (get-buffer-window ,buf 'visible)))
61        (unwind-protect
62            (progn
63              (if ,w
64                  (progn
65                    (select-window ,w)
66                    (set-buffer (window-buffer ,w)))
67                (pop-to-buffer ,buf))
68              ,@forms)
69          (select-window ,tempvar)))))
70
71 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
72 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
73
74 (defmacro gnus-intern-safe (string hashtable)
75   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
76   `(let ((symbol (intern ,string ,hashtable)))
77      (or (boundp symbol)
78          (set symbol nil))
79      symbol))
80
81 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
82 ;; to limit the length of a string.  This function is necessary since
83 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
84 (defsubst gnus-limit-string (str width)
85   (if (> (length str) width)
86       (substring str 0 width)
87     str))
88
89 (defsubst gnus-functionp (form)
90   "Return non-nil if FORM is funcallable."
91   (or (and (symbolp form) (fboundp form))
92       (and (listp form) (eq (car form) 'lambda))
93       (byte-code-function-p form)))
94
95 (defsubst gnus-goto-char (point)
96   (and point (goto-char point)))
97
98 (defmacro gnus-buffer-exists-p (buffer)
99   `(let ((buffer ,buffer))
100      (when buffer
101        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
102                 buffer))))
103
104 (defmacro gnus-kill-buffer (buffer)
105   `(let ((buf ,buffer))
106      (when (gnus-buffer-exists-p buf)
107        (kill-buffer buf))))
108
109 (defalias 'gnus-point-at-bol
110   (if (fboundp 'point-at-bol)
111       'point-at-bol
112     'line-beginning-position))
113
114 (defalias 'gnus-point-at-eol
115   (if (fboundp 'point-at-eol)
116       'point-at-eol
117     'line-end-position))
118
119 (defun gnus-delete-first (elt list)
120   "Delete by side effect the first occurrence of ELT as a member of LIST."
121   (if (equal (car list) elt)
122       (cdr list)
123     (let ((total list))
124       (while (and (cdr list)
125                   (not (equal (cadr list) elt)))
126         (setq list (cdr list)))
127       (when (cdr list)
128         (setcdr list (cddr list)))
129       total)))
130
131 ;; Delete the current line (and the next N lines).
132 (defmacro gnus-delete-line (&optional n)
133   `(delete-region (progn (beginning-of-line) (point))
134                   (progn (forward-line ,(or n 1)) (point))))
135
136 (defun gnus-byte-code (func)
137   "Return a form that can be `eval'ed based on FUNC."
138   (let ((fval (indirect-function func)))
139     (if (byte-code-function-p fval)
140         (let ((flist (append fval nil)))
141           (setcar flist 'byte-code)
142           flist)
143       (cons 'progn (cddr fval)))))
144
145 (defun gnus-extract-address-components (from)
146   (let (name address)
147     ;; First find the address - the thing with the @ in it.  This may
148     ;; not be accurate in mail addresses, but does the trick most of
149     ;; the time in news messages.
150     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
151       (setq address (substring from (match-beginning 0) (match-end 0))))
152     ;; Then we check whether the "name <address>" format is used.
153     (and address
154          ;; Linear white space is not required.
155          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
156          (and (setq name (substring from 0 (match-beginning 0)))
157               ;; Strip any quotes from the name.
158               (string-match "\".*\"" name)
159               (setq name (substring name 1 (1- (match-end 0))))))
160     ;; If not, then "address (name)" is used.
161     (or name
162         (and (string-match "(.+)" from)
163              (setq name (substring from (1+ (match-beginning 0))
164                                    (1- (match-end 0)))))
165         (and (string-match "()" from)
166              (setq name address))
167         ;; XOVER might not support folded From headers.
168         (and (string-match "(.*" from)
169              (setq name (substring from (1+ (match-beginning 0))
170                                    (match-end 0)))))
171     (list (if (string= name "") nil name) (or address from))))
172
173
174 (defun gnus-fetch-field (field)
175   "Return the value of the header FIELD of current article."
176   (save-excursion
177     (save-restriction
178       (let ((case-fold-search t)
179             (inhibit-point-motion-hooks t))
180         (nnheader-narrow-to-headers)
181         (message-fetch-field field)))))
182
183 (defun gnus-goto-colon ()
184   (beginning-of-line)
185   (let ((eol (gnus-point-at-eol)))
186     (goto-char (or (text-property-any (point) eol 'gnus-position t)
187                    (search-forward ":" eol t)
188                    (point)))))
189
190 (defun gnus-remove-text-with-property (prop)
191   "Delete all text in the current buffer with text property PROP."
192   (save-excursion
193     (goto-char (point-min))
194     (while (not (eobp))
195       (while (get-text-property (point) prop)
196         (delete-char 1))
197       (goto-char (next-single-property-change (point) prop nil (point-max))))))
198
199 (require 'nnheader)
200 (defun gnus-newsgroup-directory-form (newsgroup)
201   "Make hierarchical directory name from NEWSGROUP name."
202   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
203          (idx (string-match ":" newsgroup)))
204     (concat
205      (if idx (substring newsgroup 0 idx))
206      (if idx "/")
207      (nnheader-replace-chars-in-string
208       (if idx (substring newsgroup (1+ idx)) newsgroup)
209       ?. ?/))))
210
211 (defun gnus-newsgroup-savable-name (group)
212   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
213   ;; with dots.
214   (nnheader-replace-chars-in-string group ?/ ?.))
215
216 (defun gnus-string> (s1 s2)
217   (not (or (string< s1 s2)
218            (string= s1 s2))))
219
220 ;;; Time functions.
221
222 (defun gnus-file-newer-than (file date)
223   (let ((fdate (nth 5 (file-attributes file))))
224     (or (> (car fdate) (car date))
225         (and (= (car fdate) (car date))
226              (> (nth 1 fdate) (nth 1 date))))))
227
228 ;;; Keymap macros.
229
230 (defmacro gnus-local-set-keys (&rest plist)
231   "Set the keys in PLIST in the current keymap."
232   `(gnus-define-keys-1 (current-local-map) ',plist))
233
234 (defmacro gnus-define-keys (keymap &rest plist)
235   "Define all keys in PLIST in KEYMAP."
236   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
237
238 (defmacro gnus-define-keys-safe (keymap &rest plist)
239   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
240   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
241
242 (put 'gnus-define-keys 'lisp-indent-function 1)
243 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
244 (put 'gnus-local-set-keys 'lisp-indent-function 1)
245
246 (defmacro gnus-define-keymap (keymap &rest plist)
247   "Define all keys in PLIST in KEYMAP."
248   `(gnus-define-keys-1 ,keymap (quote ,plist)))
249
250 (put 'gnus-define-keymap 'lisp-indent-function 1)
251
252 (defun gnus-define-keys-1 (keymap plist &optional safe)
253   (when (null keymap)
254     (error "Can't set keys in a null keymap"))
255   (cond ((symbolp keymap)
256          (setq keymap (symbol-value keymap)))
257         ((keymapp keymap))
258         ((listp keymap)
259          (set (car keymap) nil)
260          (define-prefix-command (car keymap))
261          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
262          (setq keymap (symbol-value (car keymap)))))
263   (let (key)
264     (while plist
265       (when (symbolp (setq key (pop plist)))
266         (setq key (symbol-value key)))
267       (if (or (not safe)
268               (eq (lookup-key keymap key) 'undefined))
269           (define-key keymap key (pop plist))
270         (pop plist)))))
271
272 (defun gnus-completing-read (default prompt &rest args)
273   ;; Like `completing-read', except that DEFAULT is the default argument.
274   (let* ((prompt (if default
275                      (concat prompt " (default " default ") ")
276                    (concat prompt " ")))
277          (answer (apply 'completing-read prompt args)))
278     (if (or (null answer) (zerop (length answer)))
279         default
280       answer)))
281
282 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
283 ;; the echo area.
284 (defun gnus-y-or-n-p (prompt)
285   (prog1
286       (y-or-n-p prompt)
287     (message "")))
288
289 (defun gnus-yes-or-no-p (prompt)
290   (prog1
291       (yes-or-no-p prompt)
292     (message "")))
293
294 (defun gnus-dd-mmm (messy-date)
295   "Return a string like DD-MMM from a big messy string."
296   (condition-case ()
297       (format-time-string "%d-%b" (safe-date-to-time messy-date))
298     (error "  -   ")))
299
300 (defmacro gnus-date-get-time (date)
301   "Convert DATE string to Emacs time.
302 Cache the result as a text property stored in DATE."
303   ;; Either return the cached value...
304   `(let ((d ,date))
305      (if (equal "" d)
306          '(0 0)
307        (or (get-text-property 0 'gnus-time d)
308            ;; or compute the value...
309            (let ((time (safe-date-to-time d)))
310              ;; and store it back in the string.
311              (put-text-property 0 1 'gnus-time time d)
312              time)))))
313
314 (defsubst gnus-time-iso8601 (time)
315   "Return a string of TIME in YYYYMMDDTHHMMSS format."
316   (format-time-string "%Y%m%dT%H%M%S" time))
317
318 (defun gnus-date-iso8601 (date)
319   "Convert the DATE to YYYYMMDDTHHMMSS."
320   (condition-case ()
321       (gnus-time-iso8601 (gnus-date-get-time date))
322     (error "")))
323
324 (defun gnus-mode-string-quote (string)
325   "Quote all \"%\"'s in STRING."
326   (save-excursion
327     (gnus-set-work-buffer)
328     (insert string)
329     (goto-char (point-min))
330     (while (search-forward "%" nil t)
331       (insert "%"))
332     (buffer-string)))
333
334 ;; Make a hash table (default and minimum size is 256).
335 ;; Optional argument HASHSIZE specifies the table size.
336 (defun gnus-make-hashtable (&optional hashsize)
337   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
338
339 ;; Make a number that is suitable for hashing; bigger than MIN and
340 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
341 ;; hardware modulo operation, so they implement it in software.  On
342 ;; many sparcs over 50% of the time to intern is spent in the modulo.
343 ;; Yes, it's slower than actually computing the hash from the string!
344 ;; So we use powers of 2 so people can optimize the modulo to a mask.
345 (defun gnus-create-hash-size (min)
346   (let ((i 1))
347     (while (< i min)
348       (setq i (* 2 i)))
349     i))
350
351 (defcustom gnus-verbose 7
352   "*Integer that says how verbose Gnus should be.
353 The higher the number, the more messages Gnus will flash to say what
354 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
355 display most important messages; and at ten, Gnus will keep on
356 jabbering all the time."
357   :group 'gnus-start
358   :type 'integer)
359
360 ;; Show message if message has a lower level than `gnus-verbose'.
361 ;; Guideline for numbers:
362 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
363 ;; for things that take a long time, 7 - not very important messages
364 ;; on stuff, 9 - messages inside loops.
365 (defun gnus-message (level &rest args)
366   (if (<= level gnus-verbose)
367       (apply 'message args)
368     ;; We have to do this format thingy here even if the result isn't
369     ;; shown - the return value has to be the same as the return value
370     ;; from `message'.
371     (apply 'format args)))
372
373 (defun gnus-error (level &rest args)
374   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
375   (when (<= (floor level) gnus-verbose)
376     (apply 'message args)
377     (ding)
378     (let (duration)
379       (when (and (floatp level)
380                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
381         (sit-for duration))))
382   nil)
383
384 (defun gnus-split-references (references)
385   "Return a list of Message-IDs in REFERENCES."
386   (let ((beg 0)
387         ids)
388     (while (string-match "<[^> \t]+>" references beg)
389       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
390             ids))
391     (nreverse ids)))
392
393 (defsubst gnus-parent-id (references &optional n)
394   "Return the last Message-ID in REFERENCES.
395 If N, return the Nth ancestor instead."
396   (when references
397     (let ((ids (inline (gnus-split-references references))))
398       (while (nthcdr (or n 1) ids)
399         (setq ids (cdr ids)))
400       (car ids))))
401
402 (defsubst gnus-buffer-live-p (buffer)
403   "Say whether BUFFER is alive or not."
404   (and buffer
405        (get-buffer buffer)
406        (buffer-name (get-buffer buffer))))
407
408 (defun gnus-horizontal-recenter ()
409   "Recenter the current buffer horizontally."
410   (if (< (current-column) (/ (window-width) 2))
411       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
412     (let* ((orig (point))
413            (end (window-end (get-buffer-window (current-buffer) t)))
414            (max 0))
415       (when end
416         ;; Find the longest line currently displayed in the window.
417         (goto-char (window-start))
418         (while (and (not (eobp))
419                     (< (point) end))
420           (end-of-line)
421           (setq max (max max (current-column)))
422           (forward-line 1))
423         (goto-char orig)
424         ;; Scroll horizontally to center (sort of) the point.
425         (if (> max (window-width))
426             (set-window-hscroll
427              (get-buffer-window (current-buffer) t)
428              (min (- (current-column) (/ (window-width) 3))
429                   (+ 2 (- max (window-width)))))
430           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
431         max))))
432
433 (defun gnus-read-event-char ()
434   "Get the next event."
435   (let ((event (read-event)))
436     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
437     (cons (and (numberp event) event) event)))
438
439 (defun gnus-sortable-date (date)
440   "Make string suitable for sorting from DATE."
441   (gnus-time-iso8601 (date-to-time date)))
442
443 (defun gnus-copy-file (file &optional to)
444   "Copy FILE to TO."
445   (interactive
446    (list (read-file-name "Copy file: " default-directory)
447          (read-file-name "Copy file to: " default-directory)))
448   (unless to
449     (setq to (read-file-name "Copy file to: " default-directory)))
450   (when (file-directory-p to)
451     (setq to (concat (file-name-as-directory to)
452                      (file-name-nondirectory file))))
453   (copy-file file to))
454
455 (defvar gnus-work-buffer " *gnus work*")
456
457 (defun gnus-set-work-buffer ()
458   "Put point in the empty Gnus work buffer."
459   (if (get-buffer gnus-work-buffer)
460       (progn
461         (set-buffer gnus-work-buffer)
462         (erase-buffer))
463     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
464     (kill-all-local-variables)
465     (mm-enable-multibyte)))
466
467 (defmacro gnus-group-real-name (group)
468   "Find the real name of a foreign newsgroup."
469   `(let ((gname ,group))
470      (if (string-match "^[^:]+:" gname)
471          (substring gname (match-end 0))
472        gname)))
473
474 (defun gnus-make-sort-function (funs)
475   "Return a composite sort condition based on the functions in FUNC."
476   (cond
477    ;; Just a simple function.
478    ((gnus-functionp funs) funs)
479    ;; No functions at all.
480    ((null funs) funs)
481    ;; A list of functions.
482    ((or (cdr funs)
483         (listp (car funs)))
484     (gnus-byte-compile
485      `(lambda (t1 t2)
486         ,(gnus-make-sort-function-1 (reverse funs)))))
487    ;; A list containing just one function.
488    (t
489     (car funs))))
490
491 (defun gnus-make-sort-function-1 (funs)
492   "Return a composite sort condition based on the functions in FUNC."
493   (let ((function (car funs))
494         (first 't1)
495         (last 't2))
496     (when (consp function)
497       (cond
498        ;; Reversed spec.
499        ((eq (car function) 'not)
500         (setq function (cadr function)
501               first 't2
502               last 't1))
503        ((gnus-functionp function)
504         ;; Do nothing.
505         )
506        (t
507         (error "Invalid sort spec: %s" function))))
508     (if (cdr funs)
509         `(or (,function ,first ,last)
510              (and (not (,function ,last ,first))
511                   ,(gnus-make-sort-function-1 (cdr funs))))
512       `(,function ,first ,last))))
513
514 (defun gnus-turn-off-edit-menu (type)
515   "Turn off edit menu in `gnus-TYPE-mode-map'."
516   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
517     [menu-bar edit] 'undefined))
518
519 (defun gnus-prin1 (form)
520   "Use `prin1' on FORM in the current buffer.
521 Bind `print-quoted' and `print-readably' to t while printing."
522   (let ((print-quoted t)
523         (print-readably t)
524         (print-escape-multibyte nil)
525         print-level print-length)
526     (prin1 form (current-buffer))))
527
528 (defun gnus-prin1-to-string (form)
529   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
530   (let ((print-quoted t)
531         (print-readably t))
532     (prin1-to-string form)))
533
534 (defun gnus-make-directory (directory)
535   "Make DIRECTORY (and all its parents) if it doesn't exist."
536   (require 'nnmail)
537   (let ((file-name-coding-system nnmail-pathname-coding-system))
538     (when (and directory
539                (not (file-exists-p directory)))
540       (make-directory directory t)))
541   t)
542
543 (defun gnus-write-buffer (file)
544   "Write the current buffer's contents to FILE."
545   ;; Make sure the directory exists.
546   (gnus-make-directory (file-name-directory file))
547   (let ((file-name-coding-system nnmail-pathname-coding-system))
548     ;; Write the buffer.
549     (write-region (point-min) (point-max) file nil 'quietly)))
550
551 (defun gnus-delete-file (file)
552   "Delete FILE if it exists."
553   (when (file-exists-p file)
554     (delete-file file)))
555
556 (defun gnus-strip-whitespace (string)
557   "Return STRING stripped of all whitespace."
558   (while (string-match "[\r\n\t ]+" string)
559     (setq string (replace-match "" t t string)))
560   string)
561
562 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
563   "The same as `put-text-property', but don't put this prop on any newlines in the region."
564   (save-match-data
565     (save-excursion
566       (save-restriction
567         (goto-char beg)
568         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
569           (gnus-put-text-property beg (match-beginning 0) prop val)
570           (setq beg (point)))
571         (gnus-put-text-property beg (point) prop val)))))
572
573 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
574                                                                    prop val)
575   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
576   (let ((b beg))
577     (while (/= b end)
578       (when (get-text-property b 'gnus-face)
579         (setq b (next-single-property-change b 'gnus-face nil end)))
580       (when (/= b end)
581         (gnus-put-text-property
582          b (setq b (next-single-property-change b 'gnus-face nil end))
583          prop val)))))
584
585 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
586 ;;; The primary idea here is to try to protect internal datastructures
587 ;;; from becoming corrupted when the user hits C-g, or if a hook or
588 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
589 ;;; updated at the same time, or information can be lost.
590
591 (defvar gnus-atomic-be-safe t
592   "If t, certain operations will be protected from interruption by C-g.")
593
594 (defmacro gnus-atomic-progn (&rest forms)
595   "Evaluate FORMS atomically, which means to protect the evaluation
596 from being interrupted by the user.  An error from the forms themselves
597 will return without finishing the operation.  Since interrupts from
598 the user are disabled, it is recommended that only the most minimal
599 operations are performed by FORMS.  If you wish to assign many
600 complicated values atomically, compute the results into temporary
601 variables and then do only the assignment atomically."
602   `(let ((inhibit-quit gnus-atomic-be-safe))
603      ,@forms))
604
605 (put 'gnus-atomic-progn 'lisp-indent-function 0)
606
607 (defmacro gnus-atomic-progn-assign (protect &rest forms)
608   "Evaluate FORMS, but insure that the variables listed in PROTECT
609 are not changed if anything in FORMS signals an error or otherwise
610 non-locally exits.  The variables listed in PROTECT are updated atomically.
611 It is safe to use gnus-atomic-progn-assign with long computations.
612
613 Note that if any of the symbols in PROTECT were unbound, they will be
614 set to nil on a sucessful assignment.  In case of an error or other
615 non-local exit, it will still be unbound."
616   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
617                                                   (concat (symbol-name x)
618                                                           "-tmp"))
619                                                  x))
620                                protect))
621          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
622                                temp-sym-map))
623          (temp-sym-let (mapcar (lambda (x) (list (car x)
624                                                  `(and (boundp ',(cadr x))
625                                                        ,(cadr x))))
626                                temp-sym-map))
627          (sym-temp-let sym-temp-map)
628          (temp-sym-assign (apply 'append temp-sym-map))
629          (sym-temp-assign (apply 'append sym-temp-map))
630          (result (make-symbol "result-tmp")))
631     `(let (,@temp-sym-let
632            ,result)
633        (let ,sym-temp-let
634          (setq ,result (progn ,@forms))
635          (setq ,@temp-sym-assign))
636        (let ((inhibit-quit gnus-atomic-be-safe))
637          (setq ,@sym-temp-assign))
638        ,result)))
639
640 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
641 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
642
643 (defmacro gnus-atomic-setq (&rest pairs)
644   "Similar to setq, except that the real symbols are only assigned when
645 there are no errors.  And when the real symbols are assigned, they are
646 done so atomically.  If other variables might be changed via side-effect,
647 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
648 with potentially long computations."
649   (let ((tpairs pairs)
650         syms)
651     (while tpairs
652       (push (car tpairs) syms)
653       (setq tpairs (cddr tpairs)))
654     `(gnus-atomic-progn-assign ,syms
655        (setq ,@pairs))))
656
657 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
658
659
660 ;;; Functions for saving to babyl/mail files.
661
662 (defvar rmail-default-rmail-file)
663 (defun gnus-output-to-rmail (filename &optional ask)
664   "Append the current article to an Rmail file named FILENAME."
665   (require 'rmail)
666   ;; Most of these codes are borrowed from rmailout.el.
667   (setq filename (expand-file-name filename))
668   (setq rmail-default-rmail-file filename)
669   (let ((artbuf (current-buffer))
670         (tmpbuf (get-buffer-create " *Gnus-output*")))
671     (save-excursion
672       (or (get-file-buffer filename)
673           (file-exists-p filename)
674           (if (or (not ask)
675                   (gnus-yes-or-no-p
676                    (concat "\"" filename "\" does not exist, create it? ")))
677               (let ((file-buffer (create-file-buffer filename)))
678                 (save-excursion
679                   (set-buffer file-buffer)
680                   (rmail-insert-rmail-file-header)
681                   (let ((require-final-newline nil)
682                         (coding-system-for-write mm-text-coding-system))
683                     (gnus-write-buffer filename)))
684                 (kill-buffer file-buffer))
685             (error "Output file does not exist")))
686       (set-buffer tmpbuf)
687       (erase-buffer)
688       (insert-buffer-substring artbuf)
689       (gnus-convert-article-to-rmail)
690       ;; Decide whether to append to a file or to an Emacs buffer.
691       (let ((outbuf (get-file-buffer filename)))
692         (if (not outbuf)
693             (let ((file-name-coding-system nnmail-pathname-coding-system))
694               (mm-append-to-file (point-min) (point-max) filename))
695           ;; File has been visited, in buffer OUTBUF.
696           (set-buffer outbuf)
697           (let ((buffer-read-only nil)
698                 (msg (and (boundp 'rmail-current-message)
699                           (symbol-value 'rmail-current-message))))
700             ;; If MSG is non-nil, buffer is in RMAIL mode.
701             (when msg
702               (widen)
703               (narrow-to-region (point-max) (point-max)))
704             (insert-buffer-substring tmpbuf)
705             (when msg
706               (goto-char (point-min))
707               (widen)
708               (search-backward "\n\^_")
709               (narrow-to-region (point) (point-max))
710               (rmail-count-new-messages t)
711               (when (rmail-summary-exists)
712                 (rmail-select-summary
713                  (rmail-update-summary)))
714               (rmail-count-new-messages t)
715               (rmail-show-message msg))
716             (save-buffer)))))
717     (kill-buffer tmpbuf)))
718
719 (defun gnus-output-to-mail (filename &optional ask)
720   "Append the current article to a mail file named FILENAME."
721   (setq filename (expand-file-name filename))
722   (let ((artbuf (current-buffer))
723         (tmpbuf (get-buffer-create " *Gnus-output*")))
724     (save-excursion
725       ;; Create the file, if it doesn't exist.
726       (when (and (not (get-file-buffer filename))
727                  (not (file-exists-p filename)))
728         (if (or (not ask)
729                 (gnus-y-or-n-p
730                  (concat "\"" filename "\" does not exist, create it? ")))
731             (let ((file-buffer (create-file-buffer filename)))
732               (save-excursion
733                 (set-buffer file-buffer)
734                 (let ((require-final-newline nil)
735                       (coding-system-for-write mm-text-coding-system))
736                   (gnus-write-buffer filename)))
737               (kill-buffer file-buffer))
738           (error "Output file does not exist")))
739       (set-buffer tmpbuf)
740       (erase-buffer)
741       (insert-buffer-substring artbuf)
742       (goto-char (point-min))
743       (if (looking-at "From ")
744           (forward-line 1)
745         (insert "From nobody " (current-time-string) "\n"))
746       (let (case-fold-search)
747         (while (re-search-forward "^From " nil t)
748           (beginning-of-line)
749           (insert ">")))
750       ;; Decide whether to append to a file or to an Emacs buffer.
751       (let ((outbuf (get-file-buffer filename)))
752         (if (not outbuf)
753             (let ((buffer-read-only nil))
754               (save-excursion
755                 (goto-char (point-max))
756                 (forward-char -2)
757                 (unless (looking-at "\n\n")
758                   (goto-char (point-max))
759                   (unless (bolp)
760                     (insert "\n"))
761                   (insert "\n"))
762                 (goto-char (point-max))
763                 (let ((file-name-coding-system nnmail-pathname-coding-system))
764                   (mm-append-to-file (point-min) (point-max) filename))))
765           ;; File has been visited, in buffer OUTBUF.
766           (set-buffer outbuf)
767           (let ((buffer-read-only nil))
768             (goto-char (point-max))
769             (unless (eobp)
770               (insert "\n"))
771             (insert "\n")
772             (insert-buffer-substring tmpbuf)))))
773     (kill-buffer tmpbuf)))
774
775 (defun gnus-convert-article-to-rmail ()
776   "Convert article in current buffer to Rmail message format."
777   (let ((buffer-read-only nil))
778     ;; Convert article directly into Babyl format.
779     (goto-char (point-min))
780     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
781     (while (search-forward "\n\^_" nil t) ;single char
782       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
783     (goto-char (point-max))
784     (insert "\^_")))
785
786 (defun gnus-map-function (funs arg)
787   "Applies the result of the first function in FUNS to the second, and so on.
788 ARG is passed to the first function."
789   (let ((myfuns funs))
790     (while myfuns
791       (setq arg (funcall (pop myfuns) arg)))
792     arg))
793
794 (defun gnus-run-hooks (&rest funcs)
795   "Does the same as `run-hooks', but saves excursion."
796   (let ((buf (current-buffer)))
797     (unwind-protect
798         (apply 'run-hooks funcs)
799       (set-buffer buf))))
800
801 ;;;
802 ;;; .netrc and .authinforc parsing
803 ;;;
804
805 (defun gnus-parse-netrc (file)
806   "Parse FILE and return an list of all entries in the file."
807   (when (file-exists-p file)
808     (with-temp-buffer
809       (let ((tokens '("machine" "default" "login"
810                       "password" "account" "macdef" "force"
811                       "port"))
812             alist elem result pair)
813         (insert-file-contents file)
814         (goto-char (point-min))
815         ;; Go through the file, line by line.
816         (while (not (eobp))
817           (narrow-to-region (point) (gnus-point-at-eol))
818           ;; For each line, get the tokens and values.
819           (while (not (eobp))
820             (skip-chars-forward "\t ")
821             ;; Skip lines that begin with a "#".
822             (if (eq (char-after) ?#)
823                 (goto-char (point-max))
824               (unless (eobp)
825                 (setq elem
826                       (if (= (following-char) ?\")
827                           (read (current-buffer))
828                         (buffer-substring
829                          (point) (progn (skip-chars-forward "^\t ")
830                                         (point)))))
831                 (cond
832                  ((equal elem "macdef")
833                   ;; We skip past the macro definition.
834                   (widen)
835                   (while (and (zerop (forward-line 1))
836                               (looking-at "$")))
837                   (narrow-to-region (point) (point)))
838                  ((member elem tokens)
839                   ;; Tokens that don't have a following value are ignored,
840                   ;; except "default".
841                   (when (and pair (or (cdr pair)
842                                       (equal (car pair) "default")))
843                     (push pair alist))
844                   (setq pair (list elem)))
845                  (t
846                   ;; Values that haven't got a preceding token are ignored.
847                   (when pair
848                     (setcdr pair elem)
849                     (push pair alist)
850                     (setq pair nil)))))))
851           (when alist
852             (push (nreverse alist) result))
853           (setq alist nil
854                 pair nil)
855           (widen)
856           (forward-line 1))
857         (nreverse result)))))
858
859 (defun gnus-netrc-machine (list machine &optional port defaultport)
860   "Return the netrc values from LIST for MACHINE or for the default entry.
861 If PORT specified, only return entries with matching port tokens.
862 Entries without port tokens default to DEFAULTPORT."
863   (let ((rest list)
864         result)
865     (while list
866       (when (equal (cdr (assoc "machine" (car list))) machine)
867         (push (car list) result))
868       (pop list))
869     (unless result
870       ;; No machine name matches, so we look for default entries.
871       (while rest
872         (when (assoc "default" (car rest))
873           (push (car rest) result))
874         (pop rest)))
875     (when result
876       (setq result (nreverse result))
877       (while (and result
878                   (not (equal (or port defaultport "nntp")
879                               (or (gnus-netrc-get (car result) "port")
880                                   defaultport "nntp"))))
881         (pop result))
882       (car result))))
883
884 (defun gnus-netrc-get (alist type)
885   "Return the value of token TYPE from ALIST."
886   (cdr (assoc type alist)))
887
888 ;;; Various
889
890 (defvar gnus-group-buffer)              ; Compiler directive
891 (defun gnus-alive-p ()
892   "Say whether Gnus is running or not."
893   (and (boundp 'gnus-group-buffer)
894        (get-buffer gnus-group-buffer)
895        (save-excursion
896          (set-buffer gnus-group-buffer)
897          (eq major-mode 'gnus-group-mode))))
898
899 (defun gnus-remove-duplicates (list)
900   (let (new (tail list))
901     (while tail
902       (or (member (car tail) new)
903           (setq new (cons (car tail) new)))
904       (setq tail (cdr tail)))
905     (nreverse new)))
906
907 (defun gnus-delete-if (predicate list)
908   "Delete elements from LIST that satisfy PREDICATE."
909   (let (out)
910     (while list
911       (unless (funcall predicate (car list))
912         (push (car list) out))
913       (pop list))
914     (nreverse out)))
915
916 (if (fboundp 'assq-delete-all)
917     (defalias 'gnus-delete-alist 'assq-delete-all)
918   (defun gnus-delete-alist (key alist)
919     "Delete from ALIST all elements whose car is KEY.
920 Return the modified alist."
921     (let (entry)
922       (while (setq entry (assq key alist))
923         (setq alist (delq entry alist)))
924       alist)))
925
926 (defmacro gnus-pull (key alist &optional assoc-p)
927   "Modify ALIST to be without KEY."
928   (unless (symbolp alist)
929     (error "Not a symbol: %s" alist))
930   (let ((fun (if assoc-p 'assoc 'assq)))
931     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
932
933 (defun gnus-globalify-regexp (re)
934   "Returns a regexp that matches a whole line, iff RE matches a part of it."
935   (concat (unless (string-match "^\\^" re) "^.*")
936           re
937           (unless (string-match "\\$$" re) ".*$")))
938
939 (defun gnus-set-window-start (&optional point)
940   "Set the window start to POINT, or (point) if nil."
941   (let ((win (get-buffer-window (current-buffer) t)))
942     (when win
943       (set-window-start win (or point (point))))))
944
945 (defun gnus-annotation-in-region-p (b e)
946   (if (= b e)
947       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
948     (text-property-any b e 'gnus-undeletable t)))
949
950 (defun gnus-or (&rest elems)
951   "Return non-nil if any of the elements are non-nil."
952   (catch 'found
953     (while elems
954       (when (pop elems)
955         (throw 'found t)))))
956
957 (defun gnus-and (&rest elems)
958   "Return non-nil if all of the elements are non-nil."
959   (catch 'found
960     (while elems
961       (unless (pop elems)
962         (throw 'found nil)))
963     t))
964
965 (defun gnus-write-active-file (file hashtb &optional full-names)
966   (let ((coding-system-for-write nnmail-active-file-coding-system))
967     (with-temp-file file
968       (mapatoms
969        (lambda (sym)
970          (when (and sym
971                     (boundp sym)
972                     (symbol-value sym))
973            (insert (format "%S %d %d y\n"
974                            (if full-names
975                                sym
976                              (intern (gnus-group-real-name (symbol-name sym))))
977                            (or (cdr (symbol-value sym))
978                                (car (symbol-value sym)))
979                            (car (symbol-value sym))))))
980        hashtb)
981       (goto-char (point-max))
982       (while (search-backward "\\." nil t)
983         (delete-char 1)))))
984
985 (if (fboundp 'union)
986     (defalias 'gnus-union 'union)
987   (defun gnus-union (l1 l2)
988     "Set union of lists L1 and L2."
989     (cond ((null l1) l2)
990           ((null l2) l1)
991           ((equal l1 l2) l1)
992           (t
993            (or (>= (length l1) (length l2))
994                (setq l1 (prog1 l2 (setq l2 l1))))
995            (while l2
996              (or (member (car l2) l1)
997                  (push (car l2) l1))
998              (pop l2))
999            l1))))
1000
1001 (defun gnus-add-text-properties-when
1002   (property value start end properties &optional object)
1003   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1004   (let (point)
1005     (while (and start
1006                 (< start end) ;; XEmacs will loop for every when start=end.
1007                 (setq point (text-property-not-all start end property value)))
1008       (gnus-add-text-properties start point properties object)
1009       (setq start (text-property-any point end property value)))
1010     (if start
1011         (gnus-add-text-properties start end properties object))))
1012
1013 (defun gnus-remove-text-properties-when
1014   (property value start end properties &optional object)
1015   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1016   (let (point)
1017     (while (and start
1018                 (< start end)
1019                 (setq point (text-property-not-all start end property value)))
1020       (remove-text-properties start point properties object)
1021       (setq start (text-property-any point end property value)))
1022     (if start
1023         (remove-text-properties start end properties object))
1024     t))
1025
1026 (defun gnus-string-equal (x y)
1027   "Like `string-equal', except it compares case-insensitively."
1028   (and (= (length x) (length y))
1029        (or (string-equal x y)
1030            (string-equal (downcase x) (downcase y)))))
1031
1032 (defcustom gnus-use-byte-compile t
1033   "If non-nil, byte-compile crucial run-time codes."
1034   :type 'boolean
1035   :version "21.1"
1036   :group 'gnus-various)
1037
1038 (defun gnus-byte-compile (form)
1039   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1040   (if gnus-use-byte-compile
1041       (progn
1042         (require 'bytecomp)
1043         (defalias 'gnus-byte-compile 'byte-compile)
1044         (byte-compile form))
1045     form))
1046
1047 (defun gnus-remassoc (key alist)
1048   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1049 The modified LIST is returned.  If the first member
1050 of LIST has a car that is `equal' to KEY, there is no way to remove it
1051 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1052 sure of changing the value of `foo'."
1053   (when alist
1054     (if (equal key (caar alist))
1055         (cdr alist)
1056       (setcdr alist (gnus-remassoc key (cdr alist)))
1057       alist)))
1058
1059 (defun gnus-update-alist-soft (key value alist)
1060   (if value
1061       (cons (cons key value) (gnus-remassoc key alist))
1062     (gnus-remassoc key alist)))
1063
1064 (defun gnus-create-info-command (node)
1065   "Create a command that will go to info NODE."
1066   `(lambda ()
1067      (interactive)
1068      ,(concat "Enter the info system at node " node)
1069      (Info-goto-node ,node)
1070      (setq gnus-info-buffer (current-buffer))
1071      (gnus-configure-windows 'info)))
1072
1073 (defun gnus-not-ignore (&rest args)
1074   t)
1075
1076 (provide 'gnus-util)
1077
1078 ;;; gnus-util.el ends here