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