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