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