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