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