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