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