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