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