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