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