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