2f8e2e2dc29db3379faebf1dd1f0b16cedb33cd5
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996-2000 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   (condition-case ()
295       (format-time-string "%d-%b" (safe-date-to-time messy-date))
296     (error "  -   ")))
297
298 (defmacro gnus-date-get-time (date)
299   "Convert DATE string to Emacs time.
300 Cache the result as a text property stored in DATE."
301   ;; Either return the cached value...
302   `(let ((d ,date))
303      (if (equal "" d)
304          '(0 0)
305        (or (get-text-property 0 'gnus-time d)
306            ;; or compute the value...
307            (let ((time (safe-date-to-time d)))
308              ;; and store it back in the string.
309              (put-text-property 0 1 'gnus-time time d)
310              time)))))
311
312 (defsubst gnus-time-iso8601 (time)
313   "Return a string of TIME in YYMMDDTHHMMSS format."
314   (format-time-string "%Y%m%dT%H%M%S" time))
315
316 (defun gnus-date-iso8601 (date)
317   "Convert the DATE to YYMMDDTHHMMSS."
318   (condition-case ()
319       (gnus-time-iso8601 (gnus-date-get-time date))
320     (error "")))
321
322 (defun gnus-mode-string-quote (string)
323   "Quote all \"%\"'s in STRING."
324   (save-excursion
325     (gnus-set-work-buffer)
326     (insert string)
327     (goto-char (point-min))
328     (while (search-forward "%" nil t)
329       (insert "%"))
330     (buffer-string)))
331
332 ;; Make a hash table (default and minimum size is 256).
333 ;; Optional argument HASHSIZE specifies the table size.
334 (defun gnus-make-hashtable (&optional hashsize)
335   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
336
337 ;; Make a number that is suitable for hashing; bigger than MIN and
338 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
339 ;; hardware modulo operation, so they implement it in software.  On
340 ;; many sparcs over 50% of the time to intern is spent in the modulo.
341 ;; Yes, it's slower than actually computing the hash from the string!
342 ;; So we use powers of 2 so people can optimize the modulo to a mask.
343 (defun gnus-create-hash-size (min)
344   (let ((i 1))
345     (while (< i min)
346       (setq i (* 2 i)))
347     i))
348
349 (defcustom gnus-verbose 7
350   "*Integer that says how verbose Gnus should be.
351 The higher the number, the more messages Gnus will flash to say what
352 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
353 display most important messages; and at ten, Gnus will keep on
354 jabbering all the time."
355   :group 'gnus-start
356   :type 'integer)
357
358 ;; Show message if message has a lower level than `gnus-verbose'.
359 ;; Guideline for numbers:
360 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
361 ;; for things that take a long time, 7 - not very important messages
362 ;; on stuff, 9 - messages inside loops.
363 (defun gnus-message (level &rest args)
364   (if (<= level gnus-verbose)
365       (apply 'message args)
366     ;; We have to do this format thingy here even if the result isn't
367     ;; shown - the return value has to be the same as the return value
368     ;; from `message'.
369     (apply 'format args)))
370
371 (defun gnus-error (level &rest args)
372   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
373   (when (<= (floor level) gnus-verbose)
374     (apply 'message args)
375     (ding)
376     (let (duration)
377       (when (and (floatp level)
378                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
379         (sit-for duration))))
380   nil)
381
382 (defun gnus-split-references (references)
383   "Return a list of Message-IDs in REFERENCES."
384   (let ((beg 0)
385         ids)
386     (while (string-match "<[^>]+>" references beg)
387       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
388             ids))
389     (nreverse ids)))
390
391 (defsubst gnus-parent-id (references &optional n)
392   "Return the last Message-ID in REFERENCES.
393 If N, return the Nth ancestor instead."
394   (when references
395     (let ((ids (inline (gnus-split-references references))))
396       (while (nthcdr (or n 1) ids)
397         (setq ids (cdr ids)))
398       (car ids))))
399
400 (defsubst gnus-buffer-live-p (buffer)
401   "Say whether BUFFER is alive or not."
402   (and buffer
403        (get-buffer buffer)
404        (buffer-name (get-buffer buffer))))
405
406 (defun gnus-horizontal-recenter ()
407   "Recenter the current buffer horizontally."
408   (if (< (current-column) (/ (window-width) 2))
409       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
410     (let* ((orig (point))
411            (end (window-end (get-buffer-window (current-buffer) t)))
412            (max 0))
413       (when end
414         ;; Find the longest line currently displayed in the window.
415         (goto-char (window-start))
416         (while (and (not (eobp))
417                     (< (point) end))
418           (end-of-line)
419           (setq max (max max (current-column)))
420           (forward-line 1))
421         (goto-char orig)
422         ;; Scroll horizontally to center (sort of) the point.
423         (if (> max (window-width))
424             (set-window-hscroll
425              (get-buffer-window (current-buffer) t)
426              (min (- (current-column) (/ (window-width) 3))
427                   (+ 2 (- max (window-width)))))
428           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
429         max))))
430
431 (defun gnus-read-event-char ()
432   "Get the next event."
433   (let ((event (read-event)))
434     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
435     (cons (and (numberp event) event) event)))
436
437 (defun gnus-sortable-date (date)
438   "Make string suitable for sorting from DATE."
439   (gnus-time-iso8601 (date-to-time date)))
440
441 (defun gnus-copy-file (file &optional to)
442   "Copy FILE to TO."
443   (interactive
444    (list (read-file-name "Copy file: " default-directory)
445          (read-file-name "Copy file to: " default-directory)))
446   (unless to
447     (setq to (read-file-name "Copy file to: " default-directory)))
448   (when (file-directory-p to)
449     (setq to (concat (file-name-as-directory to)
450                      (file-name-nondirectory file))))
451   (copy-file file to))
452
453 (defun gnus-kill-all-overlays ()
454   "Delete all overlays in the current buffer."
455   (let* ((overlayss (overlay-lists))
456          (buffer-read-only nil)
457          (overlays (delq nil (nconc (car overlayss) (cdr overlayss)))))
458     (while overlays
459       (delete-overlay (pop overlays)))))
460
461 (defvar gnus-work-buffer " *gnus work*")
462
463 (defun gnus-set-work-buffer ()
464   "Put point in the empty Gnus work buffer."
465   (if (get-buffer gnus-work-buffer)
466       (progn
467         (set-buffer gnus-work-buffer)
468         (erase-buffer))
469     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
470     (kill-all-local-variables)
471     (mm-enable-multibyte)))
472
473 (defmacro gnus-group-real-name (group)
474   "Find the real name of a foreign newsgroup."
475   `(let ((gname ,group))
476      (if (string-match "^[^:]+:" gname)
477          (substring gname (match-end 0))
478        gname)))
479
480 (defun gnus-make-sort-function (funs)
481   "Return a composite sort condition based on the functions in FUNC."
482   (cond
483    ;; Just a simple function.
484    ((gnus-functionp funs) funs)
485    ;; No functions at all.
486    ((null funs) funs)
487    ;; A list of functions.
488    ((or (cdr funs)
489         (listp (car funs)))
490     `(lambda (t1 t2)
491        ,(gnus-make-sort-function-1 (reverse funs))))
492    ;; A list containing just one function.
493    (t
494     (car funs))))
495
496 (defun gnus-make-sort-function-1 (funs)
497   "Return a composite sort condition based on the functions in FUNC."
498   (let ((function (car funs))
499         (first 't1)
500         (last 't2))
501     (when (consp function)
502       (cond
503        ;; Reversed spec.
504        ((eq (car function) 'not)
505         (setq function (cadr function)
506               first 't2
507               last 't1))
508        ((gnus-functionp function)
509         ;; Do nothing.
510         )
511        (t
512         (error "Invalid sort spec: %s" function))))
513     (if (cdr funs)
514         `(or (,function ,first ,last)
515              (and (not (,function ,last ,first))
516                   ,(gnus-make-sort-function-1 (cdr funs))))
517       `(,function ,first ,last))))
518
519 (defun gnus-turn-off-edit-menu (type)
520   "Turn off edit menu in `gnus-TYPE-mode-map'."
521   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
522     [menu-bar edit] 'undefined))
523
524 (defun gnus-prin1 (form)
525   "Use `prin1' on FORM in the current buffer.
526 Bind `print-quoted' and `print-readably' to t while printing."
527   (let ((print-quoted t)
528         (print-readably t)
529         (print-escape-multibyte nil)
530         print-level print-length)
531     (prin1 form (current-buffer))))
532
533 (defun gnus-prin1-to-string (form)
534   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
535   (let ((print-quoted t)
536         (print-readably t))
537     (prin1-to-string form)))
538
539 (defun gnus-make-directory (directory)
540   "Make DIRECTORY (and all its parents) if it doesn't exist."
541   (when (and directory
542              (not (file-exists-p directory)))
543     (make-directory directory t))
544   t)
545
546 (defun gnus-write-buffer (file)
547   "Write the current buffer's contents to FILE."
548   ;; Make sure the directory exists.
549   (gnus-make-directory (file-name-directory file))
550   ;; Write the buffer.
551   (write-region (point-min) (point-max) file nil 'quietly))
552
553 (defun gnus-delete-file (file)
554   "Delete FILE if it exists."
555   (when (file-exists-p file)
556     (delete-file file)))
557
558 (defun gnus-strip-whitespace (string)
559   "Return STRING stripped of all whitespace."
560   (while (string-match "[\r\n\t ]+" string)
561     (setq string (replace-match "" t t string)))
562   string)
563
564 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
565   "The same as `put-text-property', but don't put this prop on any newlines in the region."
566   (save-match-data
567     (save-excursion
568       (save-restriction
569         (goto-char beg)
570         (while (re-search-forward "[ \t]*\n" end 'move)
571           (gnus-put-text-property beg (match-beginning 0) prop val)
572           (setq beg (point)))
573         (gnus-put-text-property beg (point) prop val)))))
574
575 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
576                                                                    prop val)
577   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
578   (let ((b beg))
579     (while (/= b end)
580       (when (get-text-property b 'gnus-face)
581         (setq b (next-single-property-change b 'gnus-face nil end)))
582       (when (/= b end)
583         (gnus-put-text-property
584          b (setq b (next-single-property-change b 'gnus-face nil end))
585          prop val)))))
586
587 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
588 ;;; The primary idea here is to try to protect internal datastructures
589 ;;; from becoming corrupted when the user hits C-g, or if a hook or
590 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
591 ;;; updated at the same time, or information can be lost.
592
593 (defvar gnus-atomic-be-safe t
594   "If t, certain operations will be protected from interruption by C-g.")
595
596 (defmacro gnus-atomic-progn (&rest forms)
597   "Evaluate FORMS atomically, which means to protect the evaluation
598 from being interrupted by the user.  An error from the forms themselves
599 will return without finishing the operation.  Since interrupts from
600 the user are disabled, it is recommended that only the most minimal
601 operations are performed by FORMS.  If you wish to assign many
602 complicated values atomically, compute the results into temporary
603 variables and then do only the assignment atomically."
604   `(let ((inhibit-quit gnus-atomic-be-safe))
605      ,@forms))
606
607 (put 'gnus-atomic-progn 'lisp-indent-function 0)
608
609 (defmacro gnus-atomic-progn-assign (protect &rest forms)
610   "Evaluate FORMS, but insure that the variables listed in PROTECT
611 are not changed if anything in FORMS signals an error or otherwise
612 non-locally exits.  The variables listed in PROTECT are updated atomically.
613 It is safe to use gnus-atomic-progn-assign with long computations.
614
615 Note that if any of the symbols in PROTECT were unbound, they will be
616 set to nil on a sucessful assignment.  In case of an error or other
617 non-local exit, it will still be unbound."
618   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
619                                                   (concat (symbol-name x)
620                                                           "-tmp"))
621                                                  x))
622                                protect))
623          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
624                                temp-sym-map))
625          (temp-sym-let (mapcar (lambda (x) (list (car x)
626                                                  `(and (boundp ',(cadr x))
627                                                        ,(cadr x))))
628                                temp-sym-map))
629          (sym-temp-let sym-temp-map)
630          (temp-sym-assign (apply 'append temp-sym-map))
631          (sym-temp-assign (apply 'append sym-temp-map))
632          (result (make-symbol "result-tmp")))
633     `(let (,@temp-sym-let
634            ,result)
635        (let ,sym-temp-let
636          (setq ,result (progn ,@forms))
637          (setq ,@temp-sym-assign))
638        (let ((inhibit-quit gnus-atomic-be-safe))
639          (setq ,@sym-temp-assign))
640        ,result)))
641
642 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
643 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
644
645 (defmacro gnus-atomic-setq (&rest pairs)
646   "Similar to setq, except that the real symbols are only assigned when
647 there are no errors.  And when the real symbols are assigned, they are
648 done so atomically.  If other variables might be changed via side-effect,
649 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
650 with potentially long computations."
651   (let ((tpairs pairs)
652         syms)
653     (while tpairs
654       (push (car tpairs) syms)
655       (setq tpairs (cddr tpairs)))
656     `(gnus-atomic-progn-assign ,syms
657        (setq ,@pairs))))
658
659 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
660
661
662 ;;; Functions for saving to babyl/mail files.
663
664 (defvar rmail-default-rmail-file)
665 (defun gnus-output-to-rmail (filename &optional ask)
666   "Append the current article to an Rmail file named FILENAME."
667   (require 'rmail)
668   ;; Most of these codes are borrowed from rmailout.el.
669   (setq filename (expand-file-name filename))
670   (setq rmail-default-rmail-file filename)
671   (let ((artbuf (current-buffer))
672         (tmpbuf (get-buffer-create " *Gnus-output*")))
673     (save-excursion
674       (or (get-file-buffer filename)
675           (file-exists-p filename)
676           (if (or (not ask)
677                   (gnus-yes-or-no-p
678                    (concat "\"" filename "\" does not exist, create it? ")))
679               (let ((file-buffer (create-file-buffer filename)))
680                 (save-excursion
681                   (set-buffer file-buffer)
682                   (rmail-insert-rmail-file-header)
683                   (let ((require-final-newline nil))
684                     (gnus-write-buffer filename)))
685                 (kill-buffer file-buffer))
686             (error "Output file does not exist")))
687       (set-buffer tmpbuf)
688       (erase-buffer)
689       (insert-buffer-substring artbuf)
690       (gnus-convert-article-to-rmail)
691       ;; Decide whether to append to a file or to an Emacs buffer.
692       (let ((outbuf (get-file-buffer filename)))
693         (if (not outbuf)
694             (mm-append-to-file (point-min) (point-max) filename)
695           ;; File has been visited, in buffer OUTBUF.
696           (set-buffer outbuf)
697           (let ((buffer-read-only nil)
698                 (msg (and (boundp 'rmail-current-message)
699                           (symbol-value 'rmail-current-message))))
700             ;; If MSG is non-nil, buffer is in RMAIL mode.
701             (when msg
702               (widen)
703               (narrow-to-region (point-max) (point-max)))
704             (insert-buffer-substring tmpbuf)
705             (when msg
706               (goto-char (point-min))
707               (widen)
708               (search-backward "\n\^_")
709               (narrow-to-region (point) (point-max))
710               (rmail-count-new-messages t)
711               (when (rmail-summary-exists)
712                 (rmail-select-summary
713                  (rmail-update-summary)))
714               (rmail-count-new-messages t)
715               (rmail-show-message msg))
716             (save-buffer)))))
717     (kill-buffer tmpbuf)))
718
719 (defun gnus-output-to-mail (filename &optional ask)
720   "Append the current article to a mail file named FILENAME."
721   (setq filename (expand-file-name filename))
722   (let ((artbuf (current-buffer))
723         (tmpbuf (get-buffer-create " *Gnus-output*")))
724     (save-excursion
725       ;; Create the file, if it doesn't exist.
726       (when (and (not (get-file-buffer filename))
727                  (not (file-exists-p filename)))
728         (if (or (not ask)
729                 (gnus-y-or-n-p
730                  (concat "\"" filename "\" does not exist, create it? ")))
731             (let ((file-buffer (create-file-buffer filename)))
732               (save-excursion
733                 (set-buffer file-buffer)
734                 (let ((require-final-newline nil))
735                   (gnus-write-buffer filename)))
736               (kill-buffer file-buffer))
737           (error "Output file does not exist")))
738       (set-buffer tmpbuf)
739       (erase-buffer)
740       (insert-buffer-substring artbuf)
741       (goto-char (point-min))
742       (if (looking-at "From ")
743           (forward-line 1)
744         (insert "From nobody " (current-time-string) "\n"))
745       (let (case-fold-search)
746         (while (re-search-forward "^From " nil t)
747           (beginning-of-line)
748           (insert ">")))
749       ;; Decide whether to append to a file or to an Emacs buffer.
750       (let ((outbuf (get-file-buffer filename)))
751         (if (not outbuf)
752             (let ((buffer-read-only nil))
753               (save-excursion
754                 (goto-char (point-max))
755                 (forward-char -2)
756                 (unless (looking-at "\n\n")
757                   (goto-char (point-max))
758                   (unless (bolp)
759                     (insert "\n"))
760                   (insert "\n"))
761                 (goto-char (point-max))
762                 (mm-append-to-file (point-min) (point-max) filename)))
763           ;; File has been visited, in buffer OUTBUF.
764           (set-buffer outbuf)
765           (let ((buffer-read-only nil))
766             (goto-char (point-max))
767             (unless (eobp)
768               (insert "\n"))
769             (insert "\n")
770             (insert-buffer-substring tmpbuf)))))
771     (kill-buffer tmpbuf)))
772
773 (defun gnus-convert-article-to-rmail ()
774   "Convert article in current buffer to Rmail message format."
775   (let ((buffer-read-only nil))
776     ;; Convert article directly into Babyl format.
777     (goto-char (point-min))
778     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
779     (while (search-forward "\n\^_" nil t) ;single char
780       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
781     (goto-char (point-max))
782     (insert "\^_")))
783
784 (defun gnus-map-function (funs arg)
785   "Applies the result of the first function in FUNS to the second, and so on.
786 ARG is passed to the first function."
787   (let ((myfuns funs))
788     (while myfuns
789       (setq arg (funcall (pop myfuns) arg)))
790     arg))
791
792 (defun gnus-run-hooks (&rest funcs)
793   "Does the same as `run-hooks', but saves excursion."
794   (let ((buf (current-buffer)))
795     (unwind-protect
796         (apply 'run-hooks funcs)
797       (set-buffer buf))))
798
799 ;;;
800 ;;; .netrc and .authinforc parsing
801 ;;;
802
803 (defun gnus-parse-netrc (file)
804   "Parse FILE and return an list of all entries in the file."
805   (when (file-exists-p file)
806     (with-temp-buffer
807       (let ((tokens '("machine" "default" "login"
808                       "password" "account" "macdef" "force"
809                       "port"))
810             alist elem result pair)
811         (insert-file-contents file)
812         (goto-char (point-min))
813         ;; Go through the file, line by line.
814         (while (not (eobp))
815           (narrow-to-region (point) (gnus-point-at-eol))
816           ;; For each line, get the tokens and values.
817           (while (not (eobp))
818             (skip-chars-forward "\t ")
819             ;; Skip lines that begin with a "#".
820             (if (eq (char-after) ?#)
821                 (goto-char (point-max))
822               (unless (eobp)
823                 (setq elem
824                       (if (= (following-char) ?\")
825                           (read (current-buffer))
826                         (buffer-substring
827                          (point) (progn (skip-chars-forward "^\t ")
828                                         (point)))))
829                 (cond
830                  ((equal elem "macdef")
831                   ;; We skip past the macro definition.
832                   (widen)
833                   (while (and (zerop (forward-line 1))
834                               (looking-at "$")))
835                   (narrow-to-region (point) (point)))
836                  ((member elem tokens)
837                   ;; Tokens that don't have a following value are ignored,
838                   ;; except "default".
839                   (when (and pair (or (cdr pair)
840                                       (equal (car pair) "default")))
841                     (push pair alist))
842                   (setq pair (list elem)))
843                  (t
844                   ;; Values that haven't got a preceding token are ignored.
845                   (when pair
846                     (setcdr pair elem)
847                     (push pair alist)
848                     (setq pair nil)))))))
849           (when alist
850             (push (nreverse alist) result))
851           (setq alist nil
852                 pair nil)
853           (widen)
854           (forward-line 1))
855         (nreverse result)))))
856
857 (defun gnus-netrc-machine (list machine &optional port)
858   "Return the netrc values from LIST for MACHINE or for the default entry."
859   (let ((rest list)
860         result)
861     (while list
862       (when (equal (cdr (assoc "machine" (car list))) machine)
863         (push (car list) result))
864       (pop list))
865     (unless result
866       ;; No machine name matches, so we look for default entries.
867       (while rest
868         (when (assoc "default" (car rest))
869           (push (car rest) result))
870         (pop rest)))
871     (when result
872       (setq result (nreverse result))
873       (while (and result
874                   (not (equal port (gnus-netrc-get (car result) "port"))))
875         (pop result))
876       (car result))))
877
878 (defun gnus-netrc-get (alist type)
879   "Return the value of token TYPE from ALIST."
880   (cdr (assoc type alist)))
881
882 ;;; Various
883
884 (defvar gnus-group-buffer)              ; Compiler directive
885 (defun gnus-alive-p ()
886   "Say whether Gnus is running or not."
887   (and (boundp 'gnus-group-buffer)
888        (get-buffer gnus-group-buffer)
889        (save-excursion
890          (set-buffer gnus-group-buffer)
891          (eq major-mode 'gnus-group-mode))))
892
893 (defun gnus-remove-duplicates (list)
894   (let (new (tail list))
895     (while tail
896       (or (member (car tail) new)
897           (setq new (cons (car tail) new)))
898       (setq tail (cdr tail)))
899     (nreverse new)))
900
901 (defun gnus-delete-if (predicate list)
902   "Delete elements from LIST that satisfy PREDICATE."
903   (let (out)
904     (while list
905       (unless (funcall predicate (car list))
906         (push (car list) out))
907       (pop list))
908     (nreverse out)))
909
910 (defun gnus-delete-alist (key alist)
911   "Delete all entries in ALIST that have a key eq to KEY."
912   (let (entry)
913     (while (setq entry (assq key alist))
914       (setq alist (delq entry alist)))
915     alist))
916
917 (defmacro gnus-pull (key alist &optional assoc-p)
918   "Modify ALIST to be without KEY."
919   (unless (symbolp alist)
920     (error "Not a symbol: %s" alist))
921   (let ((fun (if assoc-p 'assoc 'assq)))
922     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
923
924 (defun gnus-globalify-regexp (re)
925   "Returns a regexp that matches a whole line, iff RE matches a part of it."
926   (concat (unless (string-match "^\\^" re) "^.*")
927           re
928           (unless (string-match "\\$$" re) ".*$")))
929
930 (defun gnus-set-window-start (&optional point)
931   "Set the window start to POINT, or (point) if nil."
932   (let ((win (get-buffer-window (current-buffer) t)))
933     (when win
934       (set-window-start win (or point (point))))))
935
936 (defun gnus-annotation-in-region-p (b e)
937   (if (= b e)
938       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
939     (text-property-any b e 'gnus-undeletable t)))
940
941 (defun gnus-or (&rest elems)
942   "Return non-nil if any of the elements are non-nil."
943   (catch 'found
944     (while elems
945       (when (pop elems)
946         (throw 'found t)))))
947
948 (defun gnus-and (&rest elems)
949   "Return non-nil if all of the elements are non-nil."
950   (catch 'found
951     (while elems
952       (unless (pop elems)
953         (throw 'found nil)))
954     t))
955
956 (defun gnus-write-active-file (file hashtb &optional full-names)
957   (with-temp-file file
958     (mapatoms
959      (lambda (sym)
960        (when (and sym
961                   (boundp sym)
962                   (symbol-value sym))
963          (insert (format "%S %d %d y\n"
964                          (if full-names
965                              sym
966                            (intern (gnus-group-real-name (symbol-name sym))))
967                          (or (cdr (symbol-value sym))
968                              (car (symbol-value sym)))
969                          (car (symbol-value sym))))))
970      hashtb)
971     (goto-char (point-max))
972     (while (search-backward "\\." nil t)
973       (delete-char 1))))
974
975 (provide 'gnus-util)
976
977 ;;; gnus-util.el ends here