Require `gnus-ems'.
[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 (require 'custom)
37 (require 'nnheader)
38 (require 'message)
39 (require 'time-date)
40 (require 'gnus-ems)
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         )
541        (t
542         (error "Invalid sort spec: %s" function))))
543     (if (cdr funs)
544         `(or (,function ,first ,last)
545              (and (not (,function ,last ,first))
546                   ,(gnus-make-sort-function-1 (cdr funs))))
547       `(,function ,first ,last))))
548
549 (defun gnus-turn-off-edit-menu (type)
550   "Turn off edit menu in `gnus-TYPE-mode-map'."
551   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
552     [menu-bar edit] 'undefined))
553
554 (defun gnus-prin1 (form)
555   "Use `prin1' on FORM in the current buffer.
556 Bind `print-quoted' and `print-readably' to t while printing."
557   (let ((print-quoted t)
558         (print-readably t)
559         (print-escape-multibyte nil)
560         print-level print-length)
561     (prin1 form (current-buffer))))
562
563 (defun gnus-prin1-to-string (form)
564   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
565   (let ((print-quoted t)
566         (print-readably t))
567     (prin1-to-string form)))
568
569 (defun gnus-make-directory (directory)
570   "Make DIRECTORY (and all its parents) if it doesn't exist."
571   (when (and directory
572              (not (file-exists-p directory)))
573     (make-directory directory t))
574   t)
575
576 (defun gnus-write-buffer (file)
577   "Write the current buffer's contents to FILE."
578   ;; Make sure the directory exists.
579   (gnus-make-directory (file-name-directory file))
580   ;; Write the buffer.
581   (write-region (point-min) (point-max) file nil 'quietly))
582
583 (defun gnus-write-buffer-as-binary (file)
584   "Write the current buffer's contents to FILE without code conversion."
585   ;; Make sure the directory exists.
586   (gnus-make-directory (file-name-directory file))
587   ;; Write the buffer.
588   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
589
590 (defun gnus-write-buffer-as-coding-system (coding-system file)
591   "Write the current buffer's contents to FILE with code conversion."
592   ;; Make sure the directory exists.
593   (gnus-make-directory (file-name-directory file))
594   ;; Write the buffer.
595   (write-region-as-coding-system
596    coding-system (point-min) (point-max) file nil 'quietly))
597
598 (defun gnus-delete-file (file)
599   "Delete FILE if it exists."
600   (when (file-exists-p file)
601     (delete-file file)))
602
603 (defun gnus-strip-whitespace (string)
604   "Return STRING stripped of all whitespace."
605   (while (string-match "[\r\n\t ]+" string)
606     (setq string (replace-match "" t t string)))
607   string)
608
609 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
610   "The same as `put-text-property', but don't put this prop on any newlines in the region."
611   (save-match-data
612     (save-excursion
613       (save-restriction
614         (goto-char beg)
615         (while (re-search-forward "[ \t]*\n" end 'move)
616           (gnus-put-text-property beg (match-beginning 0) prop val)
617           (setq beg (point)))
618         (gnus-put-text-property beg (point) prop val)))))
619
620 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
621                                                                    prop val)
622   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
623   (let ((b beg))
624     (while (/= b end)
625       (when (get-text-property b 'gnus-face)
626         (setq b (next-single-property-change b 'gnus-face nil end)))
627       (when (/= b end)
628         (gnus-put-text-property
629          b (setq b (next-single-property-change b 'gnus-face nil end))
630          prop val)))))
631
632 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
633 ;;; The primary idea here is to try to protect internal datastructures
634 ;;; from becoming corrupted when the user hits C-g, or if a hook or
635 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
636 ;;; updated at the same time, or information can be lost.
637
638 (defvar gnus-atomic-be-safe t
639   "If t, certain operations will be protected from interruption by C-g.")
640
641 (defmacro gnus-atomic-progn (&rest forms)
642   "Evaluate FORMS atomically, which means to protect the evaluation
643 from being interrupted by the user.  An error from the forms themselves
644 will return without finishing the operation.  Since interrupts from
645 the user are disabled, it is recommended that only the most minimal
646 operations are performed by FORMS.  If you wish to assign many
647 complicated values atomically, compute the results into temporary
648 variables and then do only the assignment atomically."
649   `(let ((inhibit-quit gnus-atomic-be-safe))
650      ,@forms))
651
652 (put 'gnus-atomic-progn 'lisp-indent-function 0)
653
654 (defmacro gnus-atomic-progn-assign (protect &rest forms)
655   "Evaluate FORMS, but insure that the variables listed in PROTECT
656 are not changed if anything in FORMS signals an error or otherwise
657 non-locally exits.  The variables listed in PROTECT are updated atomically.
658 It is safe to use gnus-atomic-progn-assign with long computations.
659
660 Note that if any of the symbols in PROTECT were unbound, they will be
661 set to nil on a sucessful assignment.  In case of an error or other
662 non-local exit, it will still be unbound."
663   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
664                                                   (concat (symbol-name x)
665                                                           "-tmp"))
666                                                  x))
667                                protect))
668          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
669                                temp-sym-map))
670          (temp-sym-let (mapcar (lambda (x) (list (car x)
671                                                  `(and (boundp ',(cadr x))
672                                                        ,(cadr x))))
673                                temp-sym-map))
674          (sym-temp-let sym-temp-map)
675          (temp-sym-assign (apply 'append temp-sym-map))
676          (sym-temp-assign (apply 'append sym-temp-map))
677          (result (make-symbol "result-tmp")))
678     `(let (,@temp-sym-let
679            ,result)
680        (let ,sym-temp-let
681          (setq ,result (progn ,@forms))
682          (setq ,@temp-sym-assign))
683        (let ((inhibit-quit gnus-atomic-be-safe))
684          (setq ,@sym-temp-assign))
685        ,result)))
686
687 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
688 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
689
690 (defmacro gnus-atomic-setq (&rest pairs)
691   "Similar to setq, except that the real symbols are only assigned when
692 there are no errors.  And when the real symbols are assigned, they are
693 done so atomically.  If other variables might be changed via side-effect,
694 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
695 with potentially long computations."
696   (let ((tpairs pairs)
697         syms)
698     (while tpairs
699       (push (car tpairs) syms)
700       (setq tpairs (cddr tpairs)))
701     `(gnus-atomic-progn-assign ,syms
702        (setq ,@pairs))))
703
704 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
705
706
707 ;;; Functions for saving to babyl/mail files.
708
709 (defvar rmail-default-rmail-file)
710 (defun gnus-output-to-rmail (filename &optional ask)
711   "Append the current article to an Rmail file named FILENAME."
712   (require 'rmail)
713   ;; Most of these codes are borrowed from rmailout.el.
714   (setq filename (expand-file-name filename))
715   (setq rmail-default-rmail-file filename)
716   (let ((artbuf (current-buffer))
717         (tmpbuf (get-buffer-create " *Gnus-output*")))
718     (save-excursion
719       (or (get-file-buffer filename)
720           (file-exists-p filename)
721           (if (or (not ask)
722                   (gnus-yes-or-no-p
723                    (concat "\"" filename "\" does not exist, create it? ")))
724               (let ((file-buffer (create-file-buffer filename)))
725                 (save-excursion
726                   (set-buffer file-buffer)
727                   (rmail-insert-rmail-file-header)
728                   (let ((require-final-newline nil))
729                     (gnus-write-buffer filename)))
730                 (kill-buffer file-buffer))
731             (error "Output file does not exist")))
732       (set-buffer tmpbuf)
733       (erase-buffer)
734       (insert-buffer-substring artbuf)
735       (gnus-convert-article-to-rmail)
736       ;; Decide whether to append to a file or to an Emacs buffer.
737       (let ((outbuf (get-file-buffer filename)))
738         (if (not outbuf)
739             (write-region-as-binary (point-min) (point-max) filename 'append)
740           ;; File has been visited, in buffer OUTBUF.
741           (set-buffer outbuf)
742           (let ((buffer-read-only nil)
743                 (msg (and (boundp 'rmail-current-message)
744                           (symbol-value 'rmail-current-message))))
745             ;; If MSG is non-nil, buffer is in RMAIL mode.
746             (when msg
747               (widen)
748               (narrow-to-region (point-max) (point-max)))
749             (insert-buffer-substring tmpbuf)
750             (when msg
751               (goto-char (point-min))
752               (widen)
753               (search-backward "\n\^_")
754               (narrow-to-region (point) (point-max))
755               (rmail-count-new-messages t)
756               (when (rmail-summary-exists)
757                 (rmail-select-summary
758                  (rmail-update-summary)))
759               (rmail-count-new-messages t)
760               (rmail-show-message msg))
761             (save-buffer)))))
762     (kill-buffer tmpbuf)))
763
764 (defun gnus-output-to-mail (filename &optional ask)
765   "Append the current article to a mail file named FILENAME."
766   (setq filename (expand-file-name filename))
767   (let ((artbuf (current-buffer))
768         (tmpbuf (get-buffer-create " *Gnus-output*")))
769     (save-excursion
770       ;; Create the file, if it doesn't exist.
771       (when (and (not (get-file-buffer filename))
772                  (not (file-exists-p filename)))
773         (if (or (not ask)
774                 (gnus-y-or-n-p
775                  (concat "\"" filename "\" does not exist, create it? ")))
776             (let ((file-buffer (create-file-buffer filename)))
777               (save-excursion
778                 (set-buffer file-buffer)
779                 (let ((require-final-newline nil))
780                   (gnus-write-buffer-as-binary filename)))
781               (kill-buffer file-buffer))
782           (error "Output file does not exist")))
783       (set-buffer tmpbuf)
784       (erase-buffer)
785       (insert-buffer-substring artbuf)
786       (goto-char (point-min))
787       (if (looking-at "From ")
788           (forward-line 1)
789         (insert "From nobody " (current-time-string) "\n"))
790       (let (case-fold-search)
791         (while (re-search-forward "^From " nil t)
792           (beginning-of-line)
793           (insert ">")))
794       ;; Decide whether to append to a file or to an Emacs buffer.
795       (let ((outbuf (get-file-buffer filename)))
796         (if (not outbuf)
797             (let ((buffer-read-only nil))
798               (save-excursion
799                 (goto-char (point-max))
800                 (forward-char -2)
801                 (unless (looking-at "\n\n")
802                   (goto-char (point-max))
803                   (unless (bolp)
804                     (insert "\n"))
805                   (insert "\n"))
806                 (goto-char (point-max))
807                 (write-region-as-binary (point-min) (point-max)
808                                         filename 'append)))
809           ;; File has been visited, in buffer OUTBUF.
810           (set-buffer outbuf)
811           (let ((buffer-read-only nil))
812             (goto-char (point-max))
813             (unless (eobp)
814               (insert "\n"))
815             (insert "\n")
816             (insert-buffer-substring tmpbuf)))))
817     (kill-buffer tmpbuf)))
818
819 (defun gnus-convert-article-to-rmail ()
820   "Convert article in current buffer to Rmail message format."
821   (let ((buffer-read-only nil))
822     ;; Convert article directly into Babyl format.
823     (goto-char (point-min))
824     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
825     (while (search-forward "\n\^_" nil t) ;single char
826       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
827     (goto-char (point-max))
828     (insert "\^_")))
829
830 (defun gnus-map-function (funs arg)
831   "Applies the result of the first function in FUNS to the second, and so on.
832 ARG is passed to the first function."
833   (let ((myfuns funs))
834     (while myfuns
835       (setq arg (funcall (pop myfuns) arg)))
836     arg))
837
838 (defun gnus-run-hooks (&rest funcs)
839   "Does the same as `run-hooks', but saves excursion."
840   (let ((buf (current-buffer)))
841     (unwind-protect
842         (apply 'run-hooks funcs)
843       (set-buffer buf))))
844
845 ;;;
846 ;;; .netrc and .authinforc parsing
847 ;;;
848
849 (defun gnus-parse-netrc (file)
850   "Parse FILE and return an list of all entries in the file."
851   (when (file-exists-p file)
852     (with-temp-buffer
853       (let ((tokens '("machine" "default" "login"
854                       "password" "account" "macdef" "force"))
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)
903   "Return the netrc values from LIST for MACHINE or for the default entry."
904   (let ((rest list))
905     (while (and list
906                 (not (equal (cdr (assoc "machine" (car list))) machine)))
907       (pop list))
908     (car (or list
909              (progn (while (and rest (not (assoc "default" (car rest))))
910                       (pop rest))
911                     rest)))))
912
913 (defun gnus-netrc-get (alist type)
914   "Return the value of token TYPE from ALIST."
915   (cdr (assoc type alist)))
916
917 ;;; Various
918
919 (defvar gnus-group-buffer)              ; Compiler directive
920 (defun gnus-alive-p ()
921   "Say whether Gnus is running or not."
922   (and (boundp 'gnus-group-buffer)
923        (get-buffer gnus-group-buffer)
924        (save-excursion
925          (set-buffer gnus-group-buffer)
926          (eq major-mode 'gnus-group-mode))))
927
928 (defun gnus-remove-duplicates (list)
929   (let (new (tail list))
930     (while tail
931       (or (member (car tail) new)
932           (setq new (cons (car tail) new)))
933       (setq tail (cdr tail)))
934     (nreverse new)))
935
936 (defun gnus-delete-if (predicate list)
937   "Delete elements from LIST that satisfy PREDICATE."
938   (let (out)
939     (while list
940       (unless (funcall predicate (car list))
941         (push (car list) out))
942       (pop list))
943     (nreverse out)))
944
945 (defun gnus-delete-alist (key alist)
946   "Delete all entries in ALIST that have a key eq to KEY."
947   (let (entry)
948     (while (setq entry (assq key alist))
949       (setq alist (delq entry alist)))
950     alist))
951
952 (defmacro gnus-pull (key alist &optional assoc-p)
953   "Modify ALIST to be without KEY."
954   (unless (symbolp alist)
955     (error "Not a symbol: %s" alist))
956   (let ((fun (if assoc-p 'assoc 'assq)))
957     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
958
959 (defun gnus-globalify-regexp (re)
960   "Returns a regexp that matches a whole line, iff RE matches a part of it."
961   (concat (unless (string-match "^\\^" re) "^.*")
962           re
963           (unless (string-match "\\$$" re) ".*$")))
964
965 (defun gnus-set-window-start (&optional point)
966   "Set the window start to POINT, or (point) if nil."
967   (let ((win (get-buffer-window (current-buffer) t)))
968     (when win
969       (set-window-start win (or point (point))))))
970
971 (defun gnus-annotation-in-region-p (b e)
972   (if (= b e)
973       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
974     (text-property-any b e 'gnus-undeletable t)))
975
976 (defun gnus-or (&rest elems)
977   "Return non-nil if any of the elements are non-nil."
978   (catch 'found
979     (while elems
980       (when (pop elems)
981         (throw 'found t)))))
982
983 (defun gnus-and (&rest elems)
984   "Return non-nil if all of the elements are non-nil."
985   (catch 'found
986     (while elems
987       (unless (pop elems)
988         (throw 'found nil)))
989     t))
990
991 (defun gnus-write-active-file-as-coding-system (coding-system file hashtb
992                                                               &optional
993                                                               full-names)
994   (let ((output-coding-system coding-system)
995         (coding-system-for-write coding-system))
996     (with-temp-file file
997       (mapatoms
998        (lambda (sym)
999          (when (and sym
1000                     (boundp sym)
1001                     (symbol-value sym))
1002            (insert (format "%S %d %d y\n"
1003                            (if full-names
1004                                sym
1005                              (intern (gnus-group-real-name (symbol-name sym))))
1006                            (or (cdr (symbol-value sym))
1007                                (car (symbol-value sym)))
1008                            (car (symbol-value sym))))))
1009        hashtb)
1010       (goto-char (point-max))
1011       (while (search-backward "\\." nil t)
1012         (delete-char 1)))))
1013
1014 (defun gnus-union (a b)
1015   "Add members of list A to list B if they are not equal to items already
1016 in B.  This function is copied from `shadow-union' in file shadowfile.el.
1017 It is faster than cl-`union' and it uses `member' even though cl-`union'
1018 uses `memq' for comparing each element."
1019   (if (null a)
1020       b
1021     (if (member (car a) b)
1022         (gnus-union (cdr a) b)
1023       (gnus-union (cdr a) (cons (car a) b)))))
1024
1025 (gnus-ems-redefine)
1026
1027 (provide 'gnus-util)
1028
1029 ;;; gnus-util.el ends here