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