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