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