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