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