*** empty log message ***
[gnus] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; Nothing in this file depends on any other parts of Gnus -- all
27 ;; functions and macros in this file are utility functions that are
28 ;; used by Gnus and may be used by any other package without loading
29 ;; Gnus first.
30
31 ;;; Code:
32
33 (require 'custom)
34 (require 'cl)
35 (require 'nnheader)
36 (require 'timezone)
37 (require 'message)
38
39 (defun gnus-boundp (variable)
40   "Return non-nil if VARIABLE is bound and non-nil."
41   (and (boundp variable)
42        (symbol-value variable)))
43
44 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
45   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
46   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
47         (w (make-symbol "w"))
48         (buf (make-symbol "buf")))
49     `(let* ((,tempvar (selected-window))
50             (,buf ,buffer)
51             (,w (get-buffer-window ,buf 'visible)))
52        (unwind-protect
53            (progn
54              (if ,w
55                  (select-window ,w)
56                (pop-to-buffer ,buf))
57              ,@forms)
58          (select-window ,tempvar)))))
59
60 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
61 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
62
63 (defmacro gnus-intern-safe (string hashtable)
64   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
65   `(let ((symbol (intern ,string ,hashtable)))
66      (or (boundp symbol)
67          (set symbol nil))
68      symbol))
69
70 ;; modified by MORIOKA Tomohiko <morioka@jaist.ac.jp>
71 ;;   function `substring' might cut on a middle of multi-octet
72 ;;   character.
73 (defun gnus-truncate-string (str width)
74   (substring str 0 width))
75
76 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
77 ;; to limit the length of a string.  This function is necessary since
78 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
79 (defsubst gnus-limit-string (str width)
80   (if (> (length str) width)
81       (substring str 0 width)
82     str))
83
84 (defsubst gnus-functionp (form)
85   "Return non-nil if FORM is funcallable."
86   (or (and (symbolp form) (fboundp form))
87       (and (listp form) (eq (car form) 'lambda))))
88
89 (defsubst gnus-goto-char (point)
90   (and point (goto-char point)))
91
92 (defmacro gnus-buffer-exists-p (buffer)
93   `(let ((buffer ,buffer))
94      (when buffer
95        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
96                 buffer))))
97
98 (defmacro gnus-kill-buffer (buffer)
99   `(let ((buf ,buffer))
100      (when (gnus-buffer-exists-p buf)
101        (kill-buffer buf))))
102
103 (defsubst gnus-point-at-bol ()
104   "Return point at the beginning of the line."
105   (let ((p (point)))
106     (beginning-of-line)
107     (prog1
108         (point)
109       (goto-char p))))
110
111 (defsubst gnus-point-at-eol ()
112   "Return point at the end of the line."
113   (let ((p (point)))
114     (end-of-line)
115     (prog1
116         (point)
117       (goto-char p))))
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 (symbol-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          ;; Fix by MORIOKA Tomohiko <morioka@jaist.ac.jp>
155          ;; Linear white space is not required.
156          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
157          (and (setq name (substring from 0 (match-beginning 0)))
158               ;; Strip any quotes from the name.
159               (string-match "\".*\"" name)
160               (setq name (substring name 1 (1- (match-end 0))))))
161     ;; If not, then "address (name)" is used.
162     (or name
163         (and (string-match "(.+)" from)
164              (setq name (substring from (1+ (match-beginning 0))
165                                    (1- (match-end 0)))))
166         (and (string-match "()" from)
167              (setq name address))
168         ;; Fix by MORIOKA Tomohiko <morioka@jaist.ac.jp>.
169         ;; XOVER might not support folded From headers.
170         (and (string-match "(.*" from)
171              (setq name (substring from (1+ (match-beginning 0))
172                                    (match-end 0)))))
173     ;; Fix by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
174     (list (or name from) (or address from))))
175
176 (defun gnus-fetch-field (field)
177   "Return the value of the header FIELD of current article."
178   (save-excursion
179     (save-restriction
180       (let ((case-fold-search t)
181             (inhibit-point-motion-hooks t))
182         (nnheader-narrow-to-headers)
183         (message-fetch-field field)))))
184
185 (defun gnus-goto-colon ()
186   (beginning-of-line)
187   (search-forward ":" (gnus-point-at-eol) t))
188
189 (defun gnus-remove-text-with-property (prop)
190   "Delete all text in the current buffer with text property PROP."
191   (save-excursion
192     (goto-char (point-min))
193     (while (not (eobp))
194       (while (get-text-property (point) prop)
195         (delete-char 1))
196       (goto-char (next-single-property-change (point) prop nil (point-max))))))
197
198 (defun gnus-newsgroup-directory-form (newsgroup)
199   "Make hierarchical directory name from NEWSGROUP name."
200   (let ((newsgroup (gnus-newsgroup-savable-name newsgroup))
201         (len (length newsgroup))
202         idx)
203     ;; If this is a foreign group, we don't want to translate the
204     ;; entire name.
205     (if (setq idx (string-match ":" newsgroup))
206         (aset newsgroup idx ?/)
207       (setq idx 0))
208     ;; Replace all occurrences of `.' with `/'.
209     (while (< idx len)
210       (when (= (aref newsgroup idx) ?.)
211         (aset newsgroup idx ?/))
212       (setq idx (1+ idx)))
213     newsgroup))
214
215 (defun gnus-newsgroup-savable-name (group)
216   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
217   ;; with dots.
218   (nnheader-replace-chars-in-string group ?/ ?.))
219
220 (defun gnus-string> (s1 s2)
221   (not (or (string< s1 s2)
222            (string= s1 s2))))
223
224 ;;; Time functions.
225
226 (defun gnus-days-between (date1 date2)
227   ;; Return the number of days between date1 and date2.
228   (- (gnus-day-number date1) (gnus-day-number date2)))
229
230 (defun gnus-day-number (date)
231   (let ((dat (mapcar (lambda (s) (and s (string-to-int s)) )
232                      (timezone-parse-date date))))
233     (timezone-absolute-from-gregorian
234      (nth 1 dat) (nth 2 dat) (car dat))))
235
236 (defun gnus-time-to-day (time)
237   "Convert TIME to day number."
238   (let ((tim (decode-time time)))
239     (timezone-absolute-from-gregorian
240      (nth 4 tim) (nth 3 tim) (nth 5 tim))))
241
242 (defun gnus-encode-date (date)
243   "Convert DATE to internal time."
244   (let* ((parse (timezone-parse-date date))
245          (date (mapcar (lambda (d) (and d (string-to-int d))) parse))
246          (time (mapcar 'string-to-int (timezone-parse-time (aref parse 3)))))
247     (encode-time (caddr time) (cadr time) (car time)
248                  (caddr date) (cadr date) (car date) (nth 4 date))))
249
250 (defun gnus-time-minus (t1 t2)
251   "Subtract two internal times."
252   (let ((borrow (< (cadr t1) (cadr t2))))
253     (list (- (car t1) (car t2) (if borrow 1 0))
254           (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2)))))
255
256 (defun gnus-time-less (t1 t2)
257   "Say whether time T1 is less than time T2."
258   (or (< (car t1) (car t2))
259       (and (= (car t1) (car t2))
260            (< (nth 1 t1) (nth 1 t2)))))
261
262 (defun gnus-file-newer-than (file date)
263   (let ((fdate (nth 5 (file-attributes file))))
264     (or (> (car fdate) (car date))
265         (and (= (car fdate) (car date))
266              (> (nth 1 fdate) (nth 1 date))))))
267
268 ;;; Keymap macros.
269
270 (defmacro gnus-local-set-keys (&rest plist)
271   "Set the keys in PLIST in the current keymap."
272   `(gnus-define-keys-1 (current-local-map) ',plist))
273
274 (defmacro gnus-define-keys (keymap &rest plist)
275   "Define all keys in PLIST in KEYMAP."
276   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
277
278 (defmacro gnus-define-keys-safe (keymap &rest plist)
279   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
280   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
281
282 (put 'gnus-define-keys 'lisp-indent-function 1)
283 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
284 (put 'gnus-local-set-keys 'lisp-indent-function 1)
285
286 (defmacro gnus-define-keymap (keymap &rest plist)
287   "Define all keys in PLIST in KEYMAP."
288   `(gnus-define-keys-1 ,keymap (quote ,plist)))
289
290 (put 'gnus-define-keymap 'lisp-indent-function 1)
291
292 (defun gnus-define-keys-1 (keymap plist &optional safe)
293   (when (null keymap)
294     (error "Can't set keys in a null keymap"))
295   (cond ((symbolp keymap)
296          (setq keymap (symbol-value keymap)))
297         ((keymapp keymap))
298         ((listp keymap)
299          (set (car keymap) nil)
300          (define-prefix-command (car keymap))
301          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
302          (setq keymap (symbol-value (car keymap)))))
303   (let (key)
304     (while plist
305       (when (symbolp (setq key (pop plist)))
306         (setq key (symbol-value key)))
307       (if (or (not safe)
308               (eq (lookup-key keymap key) 'undefined))
309           (define-key keymap key (pop plist))
310         (pop plist)))))
311
312 (defun gnus-completing-read (default prompt &rest args)
313   ;; Like `completing-read', except that DEFAULT is the default argument.
314   (let* ((prompt (if default 
315                      (concat prompt " (default " default ") ")
316                    (concat prompt " ")))
317          (answer (apply 'completing-read prompt args)))
318     (if (or (null answer) (zerop (length answer)))
319         default
320       answer)))
321
322 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
323 ;; the echo area.
324 (defun gnus-y-or-n-p (prompt)
325   (prog1
326       (y-or-n-p prompt)
327     (message "")))
328
329 (defun gnus-yes-or-no-p (prompt)
330   (prog1
331       (yes-or-no-p prompt)
332     (message "")))
333
334 ;; I suspect there's a better way, but I haven't taken the time to do
335 ;; it yet.  -erik selberg@cs.washington.edu
336 (defun gnus-dd-mmm (messy-date)
337   "Return a string like DD-MMM from a big messy string"
338   (let ((datevec (ignore-errors (timezone-parse-date messy-date))))
339     (if (not datevec)
340         "??-???"
341       (format "%2s-%s"
342               (condition-case ()
343                   ;; Make sure leading zeroes are stripped.
344                   (number-to-string (string-to-number (aref datevec 2)))
345                 (error "??"))
346               (capitalize
347                (or (car
348                     (nth (1- (string-to-number (aref datevec 1)))
349                          timezone-months-assoc))
350                    "???"))))))
351
352 (defmacro gnus-date-get-time (date)
353   "Convert DATE string to Emacs time.
354 Cache the result as a text property stored in DATE."
355   ;; Either return the cached value...
356   `(let ((d ,date))
357      (if (equal "" d)
358          '(0 0)
359        (or (get-text-property 0 'gnus-time d)
360            ;; or compute the value...
361            (let ((time (nnmail-date-to-time d)))
362              ;; and store it back in the string.
363              (put-text-property 0 1 'gnus-time time d)
364              time)))))
365
366 (defsubst gnus-time-iso8601 (time)
367   "Return a string of TIME in YYMMDDTHHMMSS format."
368   (format-time-string "%Y%m%dT%H%M%S" time))
369   
370 (defun gnus-date-iso8601 (header)
371   "Convert the date field in HEADER to YYMMDDTHHMMSS"
372   (condition-case ()
373       (gnus-time-iso8601 (gnus-date-get-time (mail-header-date header)))
374     (error "")))
375
376 (defun gnus-mode-string-quote (string)
377   "Quote all \"%\"'s in STRING."
378   (save-excursion
379     (gnus-set-work-buffer)
380     (insert string)
381     (goto-char (point-min))
382     (while (search-forward "%" nil t)
383       (insert "%"))
384     (buffer-string)))
385
386 ;; Make a hash table (default and minimum size is 256).
387 ;; Optional argument HASHSIZE specifies the table size.
388 (defun gnus-make-hashtable (&optional hashsize)
389   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
390
391 ;; Make a number that is suitable for hashing; bigger than MIN and
392 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
393 ;; hardware modulo operation, so they implement it in software.  On
394 ;; many sparcs over 50% of the time to intern is spent in the modulo.
395 ;; Yes, it's slower than actually computing the hash from the string!
396 ;; So we use powers of 2 so people can optimize the modulo to a mask.
397 (defun gnus-create-hash-size (min)
398   (let ((i 1))
399     (while (< i min)
400       (setq i (* 2 i)))
401     i))
402
403 (defcustom gnus-verbose 7
404   "*Integer that says how verbose Gnus should be.
405 The higher the number, the more messages Gnus will flash to say what
406 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
407 display most important messages; and at ten, Gnus will keep on
408 jabbering all the time."
409   :group 'gnus-start
410   :type 'integer)
411
412 ;; Show message if message has a lower level than `gnus-verbose'.
413 ;; Guideline for numbers:
414 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
415 ;; for things that take a long time, 7 - not very important messages
416 ;; on stuff, 9 - messages inside loops.
417 (defun gnus-message (level &rest args)
418   (if (<= level gnus-verbose)
419       (apply 'message args)
420     ;; We have to do this format thingy here even if the result isn't
421     ;; shown - the return value has to be the same as the return value
422     ;; from `message'.
423     (apply 'format args)))
424
425 (defun gnus-error (level &rest args)
426   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
427   (when (<= (floor level) gnus-verbose)
428     (apply 'message args)
429     (ding)
430     (let (duration)
431       (when (and (floatp level)
432                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
433         (sit-for duration))))
434   nil)
435
436 (defun gnus-parent-id (references &optional n)
437   "Return the last Message-ID in REFERENCES.
438 If N, return the Nth ancestor instead."
439   (when references
440     (let ((ids (gnus-split-references references)))
441       (car (last ids (or n 1))))))
442
443 (defun gnus-split-references (references)
444   "Return a list of Message-IDs in REFERENCES."
445   (let ((beg 0)
446         ids)
447     (while (string-match "<[^>]+>" references beg)
448       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
449             ids))
450     (nreverse ids)))
451
452 (defun gnus-buffer-live-p (buffer)
453   "Say whether BUFFER is alive or not."
454   (and buffer
455        (get-buffer buffer)
456        (buffer-name (get-buffer buffer))))
457
458 (defun gnus-horizontal-recenter ()
459   "Recenter the current buffer horizontally."
460   (if (< (current-column) (/ (window-width) 2))
461       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
462     (let* ((orig (point))
463            (end (window-end (get-buffer-window (current-buffer) t)))
464            (max 0))
465       ;; Find the longest line currently displayed in the window.
466       (goto-char (window-start))
467       (while (and (not (eobp))
468                   (< (point) end))
469         (end-of-line)
470         (setq max (max max (current-column)))
471         (forward-line 1))
472       (goto-char orig)
473       ;; Scroll horizontally to center (sort of) the point.
474       (if (> max (window-width))
475           (set-window-hscroll 
476            (get-buffer-window (current-buffer) t)
477            (min (- (current-column) (/ (window-width) 3))
478                 (+ 2 (- max (window-width)))))
479         (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
480       max)))
481
482 (defun gnus-read-event-char ()
483   "Get the next event."
484   (let ((event (read-event)))
485     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
486     (cons (and (numberp event) event) event)))
487
488 (defun gnus-sortable-date (date)
489   "Make sortable string by string-lessp from DATE.
490 Timezone package is used."
491   (condition-case ()
492       (progn
493         (setq date (inline (timezone-fix-time 
494                             date nil 
495                             (aref (inline (timezone-parse-date date)) 4))))
496         (inline
497           (timezone-make-sortable-date
498            (aref date 0) (aref date 1) (aref date 2)
499            (inline
500              (timezone-make-time-string
501               (aref date 3) (aref date 4) (aref date 5))))))
502     (error "")))
503   
504 (defun gnus-copy-file (file &optional to)
505   "Copy FILE to TO."
506   (interactive
507    (list (read-file-name "Copy file: " default-directory)
508          (read-file-name "Copy file to: " default-directory)))
509   (unless to
510     (setq to (read-file-name "Copy file to: " default-directory)))
511   (when (file-directory-p to)
512     (setq to (concat (file-name-as-directory to)
513                      (file-name-nondirectory file))))
514   (copy-file file to))
515
516 (defun gnus-kill-all-overlays ()
517   "Delete all overlays in the current buffer."
518   (when (fboundp 'overlay-lists)
519     (let* ((overlayss (overlay-lists))
520            (buffer-read-only nil)
521            (overlays (nconc (car overlayss) (cdr overlayss))))
522       (while overlays
523         (delete-overlay (pop overlays))))))
524
525 (defvar gnus-work-buffer " *gnus work*")
526
527 (defun gnus-set-work-buffer ()
528   "Put point in the empty Gnus work buffer."
529   (if (get-buffer gnus-work-buffer)
530       (progn
531         (set-buffer gnus-work-buffer)
532         (erase-buffer))
533     (set-buffer (get-buffer-create gnus-work-buffer))
534     (kill-all-local-variables)
535     (buffer-disable-undo (current-buffer))))
536
537 (defmacro gnus-group-real-name (group)
538   "Find the real name of a foreign newsgroup."
539   `(let ((gname ,group))
540      (if (string-match "^[^:]+:" gname)
541          (substring gname (match-end 0))
542        gname)))
543
544 (defun gnus-make-sort-function (funs)
545   "Return a composite sort condition based on the functions in FUNC."
546   (cond 
547    ((not (listp funs)) funs)
548    ((null funs) funs)
549    ((cdr funs)
550     `(lambda (t1 t2)
551        ,(gnus-make-sort-function-1 (reverse funs))))
552    (t
553     (car funs))))
554
555 (defun gnus-make-sort-function-1 (funs)
556   "Return a composite sort condition based on the functions in FUNC."
557   (if (cdr funs)
558       `(or (,(car funs) t1 t2)
559            (and (not (,(car funs) t2 t1))
560                 ,(gnus-make-sort-function-1 (cdr funs))))
561     `(,(car funs) t1 t2)))
562
563 (defun gnus-turn-off-edit-menu (type)
564   "Turn off edit meny in `gnus-TYPE-mode-map'."
565   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
566     [menu-bar edit] 'undefined))
567
568 (defun gnus-prin1 (form)
569   "Use `prin1' on FORM in the current buffer.
570 Bind `print-quoted' to t while printing."
571   (let ((print-quoted t))
572     (prin1 form (current-buffer))))
573
574 (defun gnus-prin1-to-string (form)
575   "The same as `prin1', but but `print-quoted' to t."
576   (let ((print-quoted t))
577     (prin1-to-string form)))
578
579 (defun gnus-make-directory (directory)
580   "Make DIRECTORY (and all its parents) if it doesn't exist."
581   (when (and directory
582              (not (file-exists-p directory)))
583     (make-directory directory t))
584   t)
585
586 (defun gnus-write-buffer (file)
587   "Write the current buffer's contents to FILE."
588   ;; Make sure the directory exists.
589   (gnus-make-directory (file-name-directory file))
590   ;; Write the buffer.
591   (write-region (point-min) (point-max) file nil 'quietly))
592
593 (defmacro gnus-delete-assq (key list)
594   `(let ((listval (eval ,list)))
595      (setq ,list (delq (assq ,key listval) listval))))
596
597 (defmacro gnus-delete-assoc (key list)
598   `(let ((listval ,list))
599      (setq ,list (delq (assoc ,key listval) listval))))
600
601 (defun gnus-delete-file (file)
602   "Delete FILE if it exists."
603   (when (file-exists-p file)
604     (delete-file file)))
605
606 (defun gnus-strip-whitespace (string)
607   "Return STRING stripped of all whitespace."
608   (while (string-match "[\r\n\t ]+" string)
609     (setq string (replace-match "" t t string)))
610   string)
611
612 (defun gnus-put-text-property-excluding-newlines (beg end prop val)
613   "The same as `put-text-property', but don't put this prop on any newlines in the region."
614   (save-match-data
615     (save-excursion
616       (save-restriction
617         (goto-char beg)
618         (while (re-search-forward "[ \t]*\n" end 'move)
619           (put-text-property beg (match-beginning 0) prop val)
620           (setq beg (point)))
621         (put-text-property beg (point) prop val)))))
622
623 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
624 ;;; The primary idea here is to try to protect internal datastructures
625 ;;; from becoming corrupted when the user hits C-g, or if a hook or
626 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
627 ;;; updated at the same time, or information can be lost.
628
629 (defvar gnus-atomic-be-safe t
630   "If t, certain operations will be protected from interruption by C-g.")
631
632 (defmacro gnus-atomic-progn (&rest forms)
633   "Evaluate FORMS atomically, which means to protect the evaluation
634 from being interrupted by the user.  An error from the forms themselves
635 will return without finishing the operation.  Since interrupts from
636 the user are disabled, it is recommended that only the most minimal
637 operations are performed by FORMS.  If you wish to assign many
638 complicated values atomically, compute the results into temporary
639 variables and then do only the assignment atomically."
640   `(let ((inhibit-quit gnus-atomic-be-safe))
641      ,@forms))
642
643 (put 'gnus-atomic-progn 'lisp-indent-function 0)
644
645 (defmacro gnus-atomic-progn-assign (protect &rest forms)
646   "Evaluate FORMS, but insure that the variables listed in PROTECT
647 are not changed if anything in FORMS signals an error or otherwise
648 non-locally exits.  The variables listed in PROTECT are updated atomically.
649 It is safe to use gnus-atomic-progn-assign with long computations.
650
651 Note that if any of the symbols in PROTECT were unbound, they will be
652 set to nil on a sucessful assignment.  In case of an error or other
653 non-local exit, it will still be unbound."
654   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
655                                                   (concat (symbol-name x)
656                                                           "-tmp"))
657                                                  x))
658                                protect))
659          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
660                                temp-sym-map))
661          (temp-sym-let (mapcar (lambda (x) (list (car x)
662                                                  `(and (boundp ',(cadr x))
663                                                        ,(cadr x))))
664                                temp-sym-map))
665          (sym-temp-let sym-temp-map)
666          (temp-sym-assign (apply 'append temp-sym-map))
667          (sym-temp-assign (apply 'append sym-temp-map))
668          (result (make-symbol "result-tmp")))
669     `(let (,@temp-sym-let
670            ,result)
671        (let ,sym-temp-let
672          (setq ,result (progn ,@forms))
673          (setq ,@temp-sym-assign))
674        (let ((inhibit-quit gnus-atomic-be-safe))
675          (setq ,@sym-temp-assign))
676        ,result)))
677
678 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
679 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
680
681 (defmacro gnus-atomic-setq (&rest pairs)
682   "Similar to setq, except that the real symbols are only assigned when
683 there are no errors.  And when the real symbols are assigned, they are
684 done so atomically.  If other variables might be changed via side-effect,
685 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
686 with potentially long computations."
687   (let ((tpairs pairs)
688         syms)
689     (while tpairs
690       (push (car tpairs) syms)
691       (setq tpairs (cddr tpairs)))
692     `(gnus-atomic-progn-assign ,syms
693        (setq ,@pairs))))
694
695 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
696
697
698 (provide 'gnus-util)
699
700 ;;; gnus-util.el ends here