T-gnus 6.14.6; synch up with Gnus v5.8.8.
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; Keywords: mail, news, MIME
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; Nothing in this file depends on any other parts of Gnus -- all
29 ;; functions and macros in this file are utility functions that are
30 ;; used by Gnus and may be used by any other package without loading
31 ;; Gnus first.
32
33 ;;; Code:
34
35 (eval-when-compile (require 'cl))
36 (eval-when-compile (require 'static))
37
38 (require 'custom)
39 (require 'nnheader)
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   (defalias 'gnus-point-at-bol 'point-at-bol))
121  ((fboundp 'line-beginning-position)
122   (defalias '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   (defalias 'gnus-point-at-eol 'point-at-eol))
135  ((fboundp 'line-end-position)
136   (defalias '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     (list (if (string= name "") nil name) (or address from))))
200
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 YYYYMMDDTHHMMSS format."
346   (format-time-string "%Y%m%dT%H%M%S" time))
347
348 (defun gnus-date-iso8601 (date)
349   "Convert the DATE to YYYYMMDDTHHMMSS."
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 (defvar gnus-work-buffer " *gnus work*")
486
487 (defun gnus-set-work-buffer ()
488   "Put point in the empty Gnus work buffer."
489   (if (get-buffer gnus-work-buffer)
490       (progn
491         (set-buffer gnus-work-buffer)
492         (erase-buffer))
493     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
494     (kill-all-local-variables)))
495
496 (defmacro gnus-group-real-name (group)
497   "Find the real name of a foreign newsgroup."
498   `(let ((gname ,group))
499      (if (string-match "^[^:]+:" gname)
500          (substring gname (match-end 0))
501        gname)))
502
503 (defun gnus-make-sort-function (funs)
504   "Return a composite sort condition based on the functions in FUNC."
505   (cond
506    ;; Just a simple function.
507    ((gnus-functionp funs) funs)
508    ;; No functions at all.
509    ((null funs) funs)
510    ;; A list of functions.
511    ((or (cdr funs)
512         (listp (car funs)))
513     `(lambda (t1 t2)
514        ,(gnus-make-sort-function-1 (reverse funs))))
515    ;; A list containing just one function.
516    (t
517     (car funs))))
518
519 (defun gnus-make-sort-function-1 (funs)
520   "Return a composite sort condition based on the functions in FUNC."
521   (let ((function (car funs))
522         (first 't1)
523         (last 't2))
524     (when (consp function)
525       (cond
526        ;; Reversed spec.
527        ((eq (car function) 'not)
528         (setq function (cadr function)
529               first 't2
530               last 't1))
531        ((gnus-functionp function)
532         ;; Do nothing.
533         )
534        (t
535         (error "Invalid sort spec: %s" function))))
536     (if (cdr funs)
537         `(or (,function ,first ,last)
538              (and (not (,function ,last ,first))
539                   ,(gnus-make-sort-function-1 (cdr funs))))
540       `(,function ,first ,last))))
541
542 (defun gnus-turn-off-edit-menu (type)
543   "Turn off edit menu in `gnus-TYPE-mode-map'."
544   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
545     [menu-bar edit] 'undefined))
546
547 (defun gnus-prin1 (form)
548   "Use `prin1' on FORM in the current buffer.
549 Bind `print-quoted' and `print-readably' to t while printing."
550   (let ((print-quoted t)
551         (print-readably t)
552         (print-escape-multibyte nil)
553         print-level print-length)
554     (prin1 form (current-buffer))))
555
556 (defun gnus-prin1-to-string (form)
557   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
558   (let ((print-quoted t)
559         (print-readably t))
560     (prin1-to-string form)))
561
562 (defun gnus-make-directory (directory)
563   "Make DIRECTORY (and all its parents) if it doesn't exist."
564   (let ((file-name-coding-system nnmail-pathname-coding-system)
565         (pathname-coding-system nnmail-pathname-coding-system))
566     (when (and directory
567                (not (file-exists-p directory)))
568       (make-directory directory t)))
569   t)
570
571 (defun gnus-write-buffer (file)
572   "Write the current buffer's contents to FILE."
573   ;; Make sure the directory exists.
574   (gnus-make-directory (file-name-directory file))
575   (let ((file-name-coding-system nnmail-pathname-coding-system)
576         (pathname-coding-system nnmail-pathname-coding-system))
577     ;; Write the buffer.
578     (write-region (point-min) (point-max) file nil 'quietly)))
579
580 (defun gnus-write-buffer-as-binary (file)
581   "Write the current buffer's contents to FILE without code conversion."
582   ;; Make sure the directory exists.
583   (gnus-make-directory (file-name-directory file))
584   ;; Write the buffer.
585   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
586
587 (defun gnus-write-buffer-as-coding-system (coding-system file)
588   "Write the current buffer's contents to FILE with code conversion."
589   ;; Make sure the directory exists.
590   (gnus-make-directory (file-name-directory file))
591   ;; Write the buffer.
592   (write-region-as-coding-system
593    coding-system (point-min) (point-max) file nil 'quietly))
594
595 (defun gnus-delete-file (file)
596   "Delete FILE if it exists."
597   (when (file-exists-p file)
598     (delete-file file)))
599
600 (defun gnus-strip-whitespace (string)
601   "Return STRING stripped of all whitespace."
602   (while (string-match "[\r\n\t ]+" string)
603     (setq string (replace-match "" t t string)))
604   string)
605
606 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
607   "The same as `put-text-property', but don't put this prop on any newlines in the region."
608   (save-match-data
609     (save-excursion
610       (save-restriction
611         (goto-char beg)
612         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
613           (gnus-put-text-property beg (match-beginning 0) prop val)
614           (setq beg (point)))
615         (gnus-put-text-property beg (point) prop val)))))
616
617 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
618                                                                    prop val)
619   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
620   (let ((b beg))
621     (while (/= b end)
622       (when (get-text-property b 'gnus-face)
623         (setq b (next-single-property-change b 'gnus-face nil end)))
624       (when (/= b end)
625         (gnus-put-text-property
626          b (setq b (next-single-property-change b 'gnus-face nil end))
627          prop val)))))
628
629 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
630 ;;; The primary idea here is to try to protect internal datastructures
631 ;;; from becoming corrupted when the user hits C-g, or if a hook or
632 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
633 ;;; updated at the same time, or information can be lost.
634
635 (defvar gnus-atomic-be-safe t
636   "If t, certain operations will be protected from interruption by C-g.")
637
638 (defmacro gnus-atomic-progn (&rest forms)
639   "Evaluate FORMS atomically, which means to protect the evaluation
640 from being interrupted by the user.  An error from the forms themselves
641 will return without finishing the operation.  Since interrupts from
642 the user are disabled, it is recommended that only the most minimal
643 operations are performed by FORMS.  If you wish to assign many
644 complicated values atomically, compute the results into temporary
645 variables and then do only the assignment atomically."
646   `(let ((inhibit-quit gnus-atomic-be-safe))
647      ,@forms))
648
649 (put 'gnus-atomic-progn 'lisp-indent-function 0)
650
651 (defmacro gnus-atomic-progn-assign (protect &rest forms)
652   "Evaluate FORMS, but insure that the variables listed in PROTECT
653 are not changed if anything in FORMS signals an error or otherwise
654 non-locally exits.  The variables listed in PROTECT are updated atomically.
655 It is safe to use gnus-atomic-progn-assign with long computations.
656
657 Note that if any of the symbols in PROTECT were unbound, they will be
658 set to nil on a sucessful assignment.  In case of an error or other
659 non-local exit, it will still be unbound."
660   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
661                                                   (concat (symbol-name x)
662                                                           "-tmp"))
663                                                  x))
664                                protect))
665          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
666                                temp-sym-map))
667          (temp-sym-let (mapcar (lambda (x) (list (car x)
668                                                  `(and (boundp ',(cadr x))
669                                                        ,(cadr x))))
670                                temp-sym-map))
671          (sym-temp-let sym-temp-map)
672          (temp-sym-assign (apply 'append temp-sym-map))
673          (sym-temp-assign (apply 'append sym-temp-map))
674          (result (make-symbol "result-tmp")))
675     `(let (,@temp-sym-let
676            ,result)
677        (let ,sym-temp-let
678          (setq ,result (progn ,@forms))
679          (setq ,@temp-sym-assign))
680        (let ((inhibit-quit gnus-atomic-be-safe))
681          (setq ,@sym-temp-assign))
682        ,result)))
683
684 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
685 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
686
687 (defmacro gnus-atomic-setq (&rest pairs)
688   "Similar to setq, except that the real symbols are only assigned when
689 there are no errors.  And when the real symbols are assigned, they are
690 done so atomically.  If other variables might be changed via side-effect,
691 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
692 with potentially long computations."
693   (let ((tpairs pairs)
694         syms)
695     (while tpairs
696       (push (car tpairs) syms)
697       (setq tpairs (cddr tpairs)))
698     `(gnus-atomic-progn-assign ,syms
699        (setq ,@pairs))))
700
701 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
702
703
704 ;;; Functions for saving to babyl/mail files.
705
706 (defvar rmail-default-rmail-file)
707 (defun gnus-output-to-rmail (filename &optional ask)
708   "Append the current article to an Rmail file named FILENAME."
709   (require 'rmail)
710   ;; Most of these codes are borrowed from rmailout.el.
711   (setq filename (expand-file-name filename))
712   (setq rmail-default-rmail-file filename)
713   (let ((artbuf (current-buffer))
714         (tmpbuf (get-buffer-create " *Gnus-output*")))
715     (save-excursion
716       (or (get-file-buffer filename)
717           (file-exists-p filename)
718           (if (or (not ask)
719                   (gnus-yes-or-no-p
720                    (concat "\"" filename "\" does not exist, create it? ")))
721               (let ((file-buffer (create-file-buffer filename)))
722                 (save-excursion
723                   (set-buffer file-buffer)
724                   (rmail-insert-rmail-file-header)
725                   (let ((require-final-newline nil))
726                     (gnus-write-buffer-as-coding-system
727                      nnheader-text-coding-system filename)))
728                 (kill-buffer file-buffer))
729             (error "Output file does not exist")))
730       (set-buffer tmpbuf)
731       (erase-buffer)
732       (insert-buffer-substring artbuf)
733       (gnus-convert-article-to-rmail)
734       ;; Decide whether to append to a file or to an Emacs buffer.
735       (let ((outbuf (get-file-buffer filename)))
736         (if (not outbuf)
737             (write-region-as-binary (point-min) (point-max) filename 'append)
738           ;; File has been visited, in buffer OUTBUF.
739           (set-buffer outbuf)
740           (let ((buffer-read-only nil)
741                 (msg (and (boundp 'rmail-current-message)
742                           (symbol-value 'rmail-current-message))))
743             ;; If MSG is non-nil, buffer is in RMAIL mode.
744             (when msg
745               (widen)
746               (narrow-to-region (point-max) (point-max)))
747             (insert-buffer-substring tmpbuf)
748             (when msg
749               (goto-char (point-min))
750               (widen)
751               (search-backward "\n\^_")
752               (narrow-to-region (point) (point-max))
753               (rmail-count-new-messages t)
754               (when (rmail-summary-exists)
755                 (rmail-select-summary
756                  (rmail-update-summary)))
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-as-coding-system
779                    nnheader-text-coding-system filename)))
780               (kill-buffer file-buffer))
781           (error "Output file does not exist")))
782       (set-buffer tmpbuf)
783       (erase-buffer)
784       (insert-buffer-substring artbuf)
785       (goto-char (point-min))
786       (if (looking-at "From ")
787           (forward-line 1)
788         (insert "From nobody " (current-time-string) "\n"))
789       (let (case-fold-search)
790         (while (re-search-forward "^From " nil t)
791           (beginning-of-line)
792           (insert ">")))
793       ;; Decide whether to append to a file or to an Emacs buffer.
794       (let ((outbuf (get-file-buffer filename)))
795         (if (not outbuf)
796             (let ((buffer-read-only nil))
797               (save-excursion
798                 (goto-char (point-max))
799                 (forward-char -2)
800                 (unless (looking-at "\n\n")
801                   (goto-char (point-max))
802                   (unless (bolp)
803                     (insert "\n"))
804                   (insert "\n"))
805                 (goto-char (point-max))
806                 (write-region-as-binary (point-min) (point-max)
807                                         filename 'append)))
808           ;; File has been visited, in buffer OUTBUF.
809           (set-buffer outbuf)
810           (let ((buffer-read-only nil))
811             (goto-char (point-max))
812             (unless (eobp)
813               (insert "\n"))
814             (insert "\n")
815             (insert-buffer-substring tmpbuf)))))
816     (kill-buffer tmpbuf)))
817
818 (defun gnus-convert-article-to-rmail ()
819   "Convert article in current buffer to Rmail message format."
820   (let ((buffer-read-only nil))
821     ;; Convert article directly into Babyl format.
822     (goto-char (point-min))
823     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
824     (while (search-forward "\n\^_" nil t) ;single char
825       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
826     (goto-char (point-max))
827     (insert "\^_")))
828
829 (defun gnus-map-function (funs arg)
830   "Applies the result of the first function in FUNS to the second, and so on.
831 ARG is passed to the first function."
832   (let ((myfuns funs))
833     (while myfuns
834       (setq arg (funcall (pop myfuns) arg)))
835     arg))
836
837 (defun gnus-run-hooks (&rest funcs)
838   "Does the same as `run-hooks', but saves excursion."
839   (let ((buf (current-buffer)))
840     (unwind-protect
841         (apply 'run-hooks funcs)
842       (set-buffer buf))))
843
844 ;;;
845 ;;; .netrc and .authinforc parsing
846 ;;;
847
848 (defun gnus-parse-netrc (file)
849   "Parse FILE and return an list of all entries in the file."
850   (when (file-exists-p file)
851     (with-temp-buffer
852       (let ((tokens '("machine" "default" "login"
853                       "password" "account" "macdef" "force"
854                       "port"))
855             alist elem result pair)
856         (insert-file-contents file)
857         (goto-char (point-min))
858         ;; Go through the file, line by line.
859         (while (not (eobp))
860           (narrow-to-region (point) (gnus-point-at-eol))
861           ;; For each line, get the tokens and values.
862           (while (not (eobp))
863             (skip-chars-forward "\t ")
864             ;; Skip lines that begin with a "#".
865             (if (eq (char-after) ?#)
866                 (goto-char (point-max))
867               (unless (eobp)
868                 (setq elem
869                       (if (= (following-char) ?\")
870                           (read (current-buffer))
871                         (buffer-substring
872                          (point) (progn (skip-chars-forward "^\t ")
873                                         (point)))))
874                 (cond
875                  ((equal elem "macdef")
876                   ;; We skip past the macro definition.
877                   (widen)
878                   (while (and (zerop (forward-line 1))
879                               (looking-at "$")))
880                   (narrow-to-region (point) (point)))
881                  ((member elem tokens)
882                   ;; Tokens that don't have a following value are ignored,
883                   ;; except "default".
884                   (when (and pair (or (cdr pair)
885                                       (equal (car pair) "default")))
886                     (push pair alist))
887                   (setq pair (list elem)))
888                  (t
889                   ;; Values that haven't got a preceding token are ignored.
890                   (when pair
891                     (setcdr pair elem)
892                     (push pair alist)
893                     (setq pair nil)))))))
894           (when alist
895             (push (nreverse alist) result))
896           (setq alist nil
897                 pair nil)
898           (widen)
899           (forward-line 1))
900         (nreverse result)))))
901
902 (defun gnus-netrc-machine (list machine &optional port defaultport)
903   "Return the netrc values from LIST for MACHINE or for the default entry.
904 If PORT specified, only return entries with matching port tokens.
905 Entries without port tokens default to DEFAULTPORT."
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 (or port defaultport "nntp")
922                               (or (gnus-netrc-get (car result) "port")
923                                   defaultport "nntp"))))
924         (pop result))
925       (car result))))
926
927 (defun gnus-netrc-get (alist type)
928   "Return the value of token TYPE from ALIST."
929   (cdr (assoc type alist)))
930
931 ;;; Various
932
933 (defvar gnus-group-buffer)              ; Compiler directive
934 (defun gnus-alive-p ()
935   "Say whether Gnus is running or not."
936   (and (boundp 'gnus-group-buffer)
937        (get-buffer gnus-group-buffer)
938        (save-excursion
939          (set-buffer gnus-group-buffer)
940          (eq major-mode 'gnus-group-mode))))
941
942 (defun gnus-remove-duplicates (list)
943   (let (new (tail list))
944     (while tail
945       (or (member (car tail) new)
946           (setq new (cons (car tail) new)))
947       (setq tail (cdr tail)))
948     (nreverse new)))
949
950 (defun gnus-delete-if (predicate list)
951   "Delete elements from LIST that satisfy PREDICATE."
952   (let (out)
953     (while list
954       (unless (funcall predicate (car list))
955         (push (car list) out))
956       (pop list))
957     (nreverse out)))
958
959 (defun gnus-delete-alist (key alist)
960   "Delete all entries in ALIST that have a key eq to KEY."
961   (let (entry)
962     (while (setq entry (assq key alist))
963       (setq alist (delq entry alist)))
964     alist))
965
966 (defmacro gnus-pull (key alist &optional assoc-p)
967   "Modify ALIST to be without KEY."
968   (unless (symbolp alist)
969     (error "Not a symbol: %s" alist))
970   (let ((fun (if assoc-p 'assoc 'assq)))
971     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
972
973 (defun gnus-globalify-regexp (re)
974   "Returns a regexp that matches a whole line, iff RE matches a part of it."
975   (concat (unless (string-match "^\\^" re) "^.*")
976           re
977           (unless (string-match "\\$$" re) ".*$")))
978
979 (defun gnus-set-window-start (&optional point)
980   "Set the window start to POINT, or (point) if nil."
981   (let ((win (get-buffer-window (current-buffer) t)))
982     (when win
983       (set-window-start win (or point (point))))))
984
985 (defun gnus-annotation-in-region-p (b e)
986   (if (= b e)
987       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
988     (text-property-any b e 'gnus-undeletable t)))
989
990 (defun gnus-or (&rest elems)
991   "Return non-nil if any of the elements are non-nil."
992   (catch 'found
993     (while elems
994       (when (pop elems)
995         (throw 'found t)))))
996
997 (defun gnus-and (&rest elems)
998   "Return non-nil if all of the elements are non-nil."
999   (catch 'found
1000     (while elems
1001       (unless (pop elems)
1002         (throw 'found nil)))
1003     t))
1004
1005 (defun gnus-write-active-file (file hashtb &optional full-names)
1006   (let ((output-coding-system nnmail-active-file-coding-system)
1007         (coding-system-for-write nnmail-active-file-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 (if (fboundp 'union)
1027     (defalias 'gnus-union 'union)
1028   (defun gnus-union (l1 l2)
1029     "Set union of lists L1 and L2."
1030     (cond ((null l1) l2)
1031           ((null l2) l1)
1032           ((equal l1 l2) l1)
1033           (t
1034            (or (>= (length l1) (length l2))
1035                (setq l1 (prog1 l2 (setq l2 l1))))
1036            (while l2
1037              (or (member (car l2) l1)
1038                  (push (car l2) l1))
1039              (pop l2))
1040            l1))))
1041
1042 (defun gnus-add-text-properties-when
1043   (property value start end properties &optional object)
1044   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1045   (let (point)
1046     (while (and start
1047                 (< start end) ;; XEmacs will loop for every when start=end.
1048                 (setq point (text-property-not-all start end property value)))
1049       (gnus-add-text-properties start point properties object)
1050       (setq start (text-property-any point end property value)))
1051     (if start
1052         (gnus-add-text-properties start end properties object))))
1053
1054 (defun gnus-remove-text-properties-when
1055   (property value start end properties &optional object)
1056   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1057   (let (point)
1058     (while (and start
1059                 (< start end)
1060                 (setq point (text-property-not-all start end property value)))
1061       (remove-text-properties start point properties object)
1062       (setq start (text-property-any point end property value)))
1063     (if start
1064         (remove-text-properties start end properties object))
1065     t))
1066
1067 (provide 'gnus-util)
1068
1069 ;;; gnus-util.el ends here