*** empty log message ***
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996,97,98 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       (if (eq (car function) 'not)
501           (setq function (cadr function)
502                 first 't2
503                 last 't1)
504         (error "Invalid sort spec: %s" function)))
505     (if (cdr funs)
506         `(or (,function ,first ,last)
507              (and (not (,function ,last ,first))
508                   ,(gnus-make-sort-function-1 (cdr funs))))
509       `(,function ,first ,last))))
510
511 (defun gnus-turn-off-edit-menu (type)
512   "Turn off edit menu in `gnus-TYPE-mode-map'."
513   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
514     [menu-bar edit] 'undefined))
515
516 (defun gnus-prin1 (form)
517   "Use `prin1' on FORM in the current buffer.
518 Bind `print-quoted' and `print-readably' to t while printing."
519   (let ((print-quoted t)
520         (print-readably t)
521         (print-escape-multibyte nil)
522         print-level print-length)
523     (prin1 form (current-buffer))))
524
525 (defun gnus-prin1-to-string (form)
526   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
527   (let ((print-quoted t)
528         (print-readably t))
529     (prin1-to-string form)))
530
531 (defun gnus-make-directory (directory)
532   "Make DIRECTORY (and all its parents) if it doesn't exist."
533   (when (and directory
534              (not (file-exists-p directory)))
535     (make-directory directory t))
536   t)
537
538 (defun gnus-write-buffer (file)
539   "Write the current buffer's contents to FILE."
540   ;; Make sure the directory exists.
541   (gnus-make-directory (file-name-directory file))
542   ;; Write the buffer.
543   (write-region (point-min) (point-max) file nil 'quietly))
544
545 (defun gnus-delete-file (file)
546   "Delete FILE if it exists."
547   (when (file-exists-p file)
548     (delete-file file)))
549
550 (defun gnus-strip-whitespace (string)
551   "Return STRING stripped of all whitespace."
552   (while (string-match "[\r\n\t ]+" string)
553     (setq string (replace-match "" t t string)))
554   string)
555
556 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
557   "The same as `put-text-property', but don't put this prop on any newlines in the region."
558   (save-match-data
559     (save-excursion
560       (save-restriction
561         (goto-char beg)
562         (while (re-search-forward "[ \t]*\n" end 'move)
563           (gnus-put-text-property beg (match-beginning 0) prop val)
564           (setq beg (point)))
565         (gnus-put-text-property beg (point) prop val)))))
566
567 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
568                                                                    prop val)
569   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
570   (let ((b beg))
571     (while (/= b end)
572       (when (get-text-property b 'gnus-face)
573         (setq b (next-single-property-change b 'gnus-face nil end)))
574       (when (/= b end)
575         (gnus-put-text-property
576          b (setq b (next-single-property-change b 'gnus-face nil end))
577          prop val)))))
578   
579 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
580 ;;; The primary idea here is to try to protect internal datastructures
581 ;;; from becoming corrupted when the user hits C-g, or if a hook or
582 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
583 ;;; updated at the same time, or information can be lost.
584
585 (defvar gnus-atomic-be-safe t
586   "If t, certain operations will be protected from interruption by C-g.")
587
588 (defmacro gnus-atomic-progn (&rest forms)
589   "Evaluate FORMS atomically, which means to protect the evaluation
590 from being interrupted by the user.  An error from the forms themselves
591 will return without finishing the operation.  Since interrupts from
592 the user are disabled, it is recommended that only the most minimal
593 operations are performed by FORMS.  If you wish to assign many
594 complicated values atomically, compute the results into temporary
595 variables and then do only the assignment atomically."
596   `(let ((inhibit-quit gnus-atomic-be-safe))
597      ,@forms))
598
599 (put 'gnus-atomic-progn 'lisp-indent-function 0)
600
601 (defmacro gnus-atomic-progn-assign (protect &rest forms)
602   "Evaluate FORMS, but insure that the variables listed in PROTECT
603 are not changed if anything in FORMS signals an error or otherwise
604 non-locally exits.  The variables listed in PROTECT are updated atomically.
605 It is safe to use gnus-atomic-progn-assign with long computations.
606
607 Note that if any of the symbols in PROTECT were unbound, they will be
608 set to nil on a sucessful assignment.  In case of an error or other
609 non-local exit, it will still be unbound."
610   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
611                                                   (concat (symbol-name x)
612                                                           "-tmp"))
613                                                  x))
614                                protect))
615          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
616                                temp-sym-map))
617          (temp-sym-let (mapcar (lambda (x) (list (car x)
618                                                  `(and (boundp ',(cadr x))
619                                                        ,(cadr x))))
620                                temp-sym-map))
621          (sym-temp-let sym-temp-map)
622          (temp-sym-assign (apply 'append temp-sym-map))
623          (sym-temp-assign (apply 'append sym-temp-map))
624          (result (make-symbol "result-tmp")))
625     `(let (,@temp-sym-let
626            ,result)
627        (let ,sym-temp-let
628          (setq ,result (progn ,@forms))
629          (setq ,@temp-sym-assign))
630        (let ((inhibit-quit gnus-atomic-be-safe))
631          (setq ,@sym-temp-assign))
632        ,result)))
633
634 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
635 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
636
637 (defmacro gnus-atomic-setq (&rest pairs)
638   "Similar to setq, except that the real symbols are only assigned when
639 there are no errors.  And when the real symbols are assigned, they are
640 done so atomically.  If other variables might be changed via side-effect,
641 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
642 with potentially long computations."
643   (let ((tpairs pairs)
644         syms)
645     (while tpairs
646       (push (car tpairs) syms)
647       (setq tpairs (cddr tpairs)))
648     `(gnus-atomic-progn-assign ,syms
649        (setq ,@pairs))))
650
651 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
652
653
654 ;;; Functions for saving to babyl/mail files.
655
656 (defvar rmail-default-rmail-file)
657 (defun gnus-output-to-rmail (filename &optional ask)
658   "Append the current article to an Rmail file named FILENAME."
659   (require 'rmail)
660   ;; Most of these codes are borrowed from rmailout.el.
661   (setq filename (expand-file-name filename))
662   (setq rmail-default-rmail-file filename)
663   (let ((artbuf (current-buffer))
664         (tmpbuf (get-buffer-create " *Gnus-output*")))
665     (save-excursion
666       (or (get-file-buffer filename)
667           (file-exists-p filename)
668           (if (or (not ask)
669                   (gnus-yes-or-no-p
670                    (concat "\"" filename "\" does not exist, create it? ")))
671               (let ((file-buffer (create-file-buffer filename)))
672                 (save-excursion
673                   (set-buffer file-buffer)
674                   (rmail-insert-rmail-file-header)
675                   (let ((require-final-newline nil))
676                     (gnus-write-buffer filename)))
677                 (kill-buffer file-buffer))
678             (error "Output file does not exist")))
679       (set-buffer tmpbuf)
680       (erase-buffer)
681       (insert-buffer-substring artbuf)
682       (gnus-convert-article-to-rmail)
683       ;; Decide whether to append to a file or to an Emacs buffer.
684       (let ((outbuf (get-file-buffer filename)))
685         (if (not outbuf)
686             (append-to-file (point-min) (point-max) filename)
687           ;; File has been visited, in buffer OUTBUF.
688           (set-buffer outbuf)
689           (let ((buffer-read-only nil)
690                 (msg (and (boundp 'rmail-current-message)
691                           (symbol-value 'rmail-current-message))))
692             ;; If MSG is non-nil, buffer is in RMAIL mode.
693             (when msg
694               (widen)
695               (narrow-to-region (point-max) (point-max)))
696             (insert-buffer-substring tmpbuf)
697             (when msg
698               (goto-char (point-min))
699               (widen)
700               (search-backward "\n\^_")
701               (narrow-to-region (point) (point-max))
702               (rmail-count-new-messages t)
703               (when (rmail-summary-exists)
704                 (rmail-select-summary
705                  (rmail-update-summary)))
706               (rmail-count-new-messages t)
707               (rmail-show-message msg))
708             (save-buffer)))))
709     (kill-buffer tmpbuf)))
710
711 (defun gnus-output-to-mail (filename &optional ask)
712   "Append the current article to a mail file named FILENAME."
713   (setq filename (expand-file-name filename))
714   (let ((artbuf (current-buffer))
715         (tmpbuf (get-buffer-create " *Gnus-output*")))
716     (save-excursion
717       ;; Create the file, if it doesn't exist.
718       (when (and (not (get-file-buffer filename))
719                  (not (file-exists-p filename)))
720         (if (or (not ask)
721                 (gnus-y-or-n-p
722                  (concat "\"" filename "\" does not exist, create it? ")))
723             (let ((file-buffer (create-file-buffer filename)))
724               (save-excursion
725                 (set-buffer file-buffer)
726                 (let ((require-final-newline nil))
727                   (gnus-write-buffer filename)))
728               (kill-buffer file-buffer))
729           (error "Output file does not exist")))
730       (set-buffer tmpbuf)
731       (erase-buffer)
732       (insert-buffer-substring artbuf)
733       (goto-char (point-min))
734       (if (looking-at "From ")
735           (forward-line 1)
736         (insert "From nobody " (current-time-string) "\n"))
737       (let (case-fold-search)
738         (while (re-search-forward "^From " nil t)
739           (beginning-of-line)
740           (insert ">")))
741       ;; Decide whether to append to a file or to an Emacs buffer.
742       (let ((outbuf (get-file-buffer filename)))
743         (if (not outbuf)
744             (let ((buffer-read-only nil))
745               (save-excursion
746                 (goto-char (point-max))
747                 (forward-char -2)
748                 (unless (looking-at "\n\n")
749                   (goto-char (point-max))
750                   (unless (bolp)
751                     (insert "\n"))
752                   (insert "\n"))
753                 (goto-char (point-max))
754                 (append-to-file (point-min) (point-max) filename)))
755           ;; File has been visited, in buffer OUTBUF.
756           (set-buffer outbuf)
757           (let ((buffer-read-only nil))
758             (goto-char (point-max))
759             (unless (eobp)
760               (insert "\n"))
761             (insert "\n")
762             (insert-buffer-substring tmpbuf)))))
763     (kill-buffer tmpbuf)))
764
765 (defun gnus-convert-article-to-rmail ()
766   "Convert article in current buffer to Rmail message format."
767   (let ((buffer-read-only nil))
768     ;; Convert article directly into Babyl format.
769     (goto-char (point-min))
770     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
771     (while (search-forward "\n\^_" nil t) ;single char
772       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
773     (goto-char (point-max))
774     (insert "\^_")))
775
776 (defun gnus-map-function (funs arg)
777   "Applies the result of the first function in FUNS to the second, and so on.
778 ARG is passed to the first function."
779   (let ((myfuns funs))
780     (while myfuns
781       (setq arg (funcall (pop myfuns) arg)))
782     arg))
783
784 (defun gnus-run-hooks (&rest funcs)
785   "Does the same as `run-hooks', but saves excursion."
786   (let ((buf (current-buffer)))
787     (unwind-protect
788         (apply 'run-hooks funcs)
789       (set-buffer buf))))
790   
791 ;;;
792 ;;; .netrc and .authinforc parsing
793 ;;;
794
795 (defvar gnus-netrc-syntax-table
796   (let ((table (copy-syntax-table text-mode-syntax-table)))
797     (modify-syntax-entry ?@ "w" table)
798     (modify-syntax-entry ?- "w" table)
799     (modify-syntax-entry ?_ "w" table)
800     (modify-syntax-entry ?! "w" table)
801     (modify-syntax-entry ?. "w" table)
802     (modify-syntax-entry ?, "w" table)
803     (modify-syntax-entry ?: "w" table)
804     (modify-syntax-entry ?\; "w" table)
805     (modify-syntax-entry ?% "w" table)
806     (modify-syntax-entry ?) "w" table)
807     (modify-syntax-entry ?( "w" table)
808     table)
809   "Syntax table when parsing .netrc files.")
810
811 (defun gnus-parse-netrc (file)
812   "Parse FILE and return an list of all entries in the file."
813   (if (not (file-exists-p file))
814       ()
815     (save-excursion
816       (let ((tokens '("machine" "default" "login"
817                       "password" "account" "macdef" "force"))
818             alist elem result pair)
819         (nnheader-set-temp-buffer " *netrc*")
820         (unwind-protect
821             (progn
822               (set-syntax-table gnus-netrc-syntax-table)
823               (insert-file-contents file)
824               (goto-char (point-min))
825               ;; Go through the file, line by line.
826               (while (not (eobp))
827                 (narrow-to-region (point) (gnus-point-at-eol))
828                 ;; For each line, get the tokens and values.
829                 (while (not (eobp))
830                   (skip-chars-forward "\t ")
831                   (unless (eobp)
832                     (setq elem (buffer-substring
833                                 (point) (progn (forward-sexp 1) (point))))
834                     (cond
835                      ((equal elem "macdef")
836                       ;; We skip past the macro definition.
837                       (widen)
838                       (while (and (zerop (forward-line 1))
839                                   (looking-at "$")))
840                       (narrow-to-region (point) (point)))
841                      ((member elem tokens)
842                       ;; Tokens that don't have a following value are ignored,
843                       ;; except "default".
844                       (when (and pair (or (cdr pair)
845                                           (equal (car pair) "default")))
846                         (push pair alist))
847                       (setq pair (list elem)))
848                      (t
849                       ;; Values that haven't got a preceding token are ignored.
850                       (when pair
851                         (setcdr pair elem)
852                         (push pair alist)
853                         (setq pair nil))))))
854                 (if alist
855                     (push (nreverse alist) result))
856                 (setq alist nil
857                       pair nil)
858                 (widen)
859                 (forward-line 1))
860               (nreverse result))
861           (kill-buffer " *netrc*"))))))
862
863 (defun gnus-netrc-machine (list machine)
864   "Return the netrc values from LIST for MACHINE or for the default entry."
865   (let ((rest list))
866     (while (and list
867                 (not (equal (cdr (assoc "machine" (car list))) machine)))
868       (pop list))
869     (car (or list
870              (progn (while (and rest (not (assoc "default" (car rest))))
871                       (pop rest))
872                     rest)))))
873
874 (defun gnus-netrc-get (alist type)
875   "Return the value of token TYPE from ALIST."
876   (cdr (assoc type alist)))
877
878 ;;; Various
879
880 (defvar gnus-group-buffer) ; Compiler directive
881 (defun gnus-alive-p ()
882   "Say whether Gnus is running or not."
883   (and (boundp 'gnus-group-buffer)
884        (get-buffer gnus-group-buffer)
885        (save-excursion
886          (set-buffer gnus-group-buffer)
887          (eq major-mode 'gnus-group-mode))))
888
889 (defun gnus-remove-duplicates (list)
890   (let (new (tail list))
891     (while tail
892       (or (member (car tail) new)
893           (setq new (cons (car tail) new)))
894       (setq tail (cdr tail)))
895     (nreverse new)))
896
897 (defun gnus-delete-if (predicate list)
898   "Delete elements from LIST that satisfy PREDICATE."
899   (let (out)
900     (while list
901       (unless (funcall predicate (car list))
902         (push (car list) out))
903       (pop list))
904     (nreverse out)))
905
906 (defun gnus-delete-alist (key alist)
907   "Delete all entries in ALIST that have a key eq to KEY."
908   (let (entry)
909     (while (setq entry (assq key alist))
910       (setq alist (delq entry alist)))
911     alist))
912
913 (defmacro gnus-pull (key alist &optional assoc-p)
914   "Modify ALIST to be without KEY."
915   (unless (symbolp alist)
916     (error "Not a symbol: %s" alist))
917   (let ((fun (if assoc-p 'assoc 'assq)))
918     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
919
920 (defun gnus-globalify-regexp (re)
921   "Returns a regexp that matches a whole line, iff RE matches a part of it."
922   (concat (unless (string-match "^\\^" re) "^.*")
923           re
924           (unless (string-match "\\$$" re) ".*$")))
925
926 (defun gnus-set-window-start (&optional point)
927   "Set the window start to POINT, or (point) if nil."
928   (let ((win (get-buffer-window (current-buffer) t)))
929     (when win
930       (set-window-start win (or point (point))))))
931
932 (defun gnus-annotation-in-region-p (b e)
933   (if (= b e)
934       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t) 
935     (text-property-any b e 'gnus-undeletable t)))
936
937 (provide 'gnus-util)
938
939 ;;; gnus-util.el ends here