* Makefile.in (install-package-ja): Compile and install lisp files first.
[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 'message)
41 (require 'time-date)
42
43 (eval-and-compile
44   (autoload 'rmail-insert-rmail-file-header "rmail")
45   (autoload 'rmail-count-new-messages "rmail")
46   (autoload 'rmail-show-message "rmail"))
47
48 (defun gnus-boundp (variable)
49   "Return non-nil if VARIABLE is bound and non-nil."
50   (and (boundp variable)
51        (symbol-value variable)))
52
53 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
54   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
55   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
56         (w (make-symbol "w"))
57         (buf (make-symbol "buf"))
58         (frame (make-symbol "frame")))
59     `(let* ((,tempvar (selected-window))
60             (,buf ,buffer)
61             (,w (get-buffer-window ,buf 'visible))
62             ,frame)
63        (unwind-protect
64            (progn
65              (if ,w
66                  (progn
67                    (select-window ,w)
68                    (set-buffer (window-buffer ,w)))
69                (pop-to-buffer ,buf))
70              ,@forms)
71          (setq ,frame (selected-frame))
72          (select-window ,tempvar)
73          (select-frame ,frame)))))
74
75 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
76 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
77
78 (defmacro gnus-intern-safe (string hashtable)
79   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
80   `(let ((symbol (intern ,string ,hashtable)))
81      (or (boundp symbol)
82          (set symbol nil))
83      symbol))
84
85 ;; Avoid byte-compile warning.
86 ;; In Mule, this function will be redefined to `truncate-string',
87 ;; which takes 3 or 4 args.
88 (defun gnus-truncate-string (str width &rest ignore)
89   (substring str 0 width))
90
91 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
92 ;; to limit the length of a string.  This function is necessary since
93 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
94 (defsubst gnus-limit-string (str width)
95   (if (> (length str) width)
96       (substring str 0 width)
97     str))
98
99 (defsubst gnus-functionp (form)
100   "Return non-nil if FORM is funcallable."
101   (or (and (symbolp form) (fboundp form))
102       (and (listp form) (eq (car form) 'lambda))
103       (byte-code-function-p form)))
104
105 (defsubst gnus-goto-char (point)
106   (and point (goto-char point)))
107
108 (defmacro gnus-buffer-exists-p (buffer)
109   `(let ((buffer ,buffer))
110      (when buffer
111        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
112                 buffer))))
113
114 (defmacro gnus-kill-buffer (buffer)
115   `(let ((buf ,buffer))
116      (when (gnus-buffer-exists-p buf)
117        (kill-buffer buf))))
118
119 (static-cond
120  ((fboundp 'point-at-bol)
121   (defalias 'gnus-point-at-bol 'point-at-bol))
122  ((fboundp 'line-beginning-position)
123   (defalias 'gnus-point-at-bol 'line-beginning-position))
124  (t
125   (defun gnus-point-at-bol ()
126     "Return point at the beginning of the line."
127     (let ((p (point)))
128       (beginning-of-line)
129       (prog1
130           (point)
131         (goto-char p))))
132   ))
133 (static-cond
134  ((fboundp 'point-at-eol)
135   (defalias 'gnus-point-at-eol 'point-at-eol))
136  ((fboundp 'line-end-position)
137   (defalias 'gnus-point-at-eol 'line-end-position))
138  (t
139   (defun gnus-point-at-eol ()
140     "Return point at the end of the line."
141     (let ((p (point)))
142       (end-of-line)
143       (prog1
144           (point)
145         (goto-char p))))
146   ))
147
148 (defun gnus-delete-first (elt list)
149   "Delete by side effect the first occurrence of ELT as a member of LIST."
150   (if (equal (car list) elt)
151       (cdr list)
152     (let ((total list))
153       (while (and (cdr list)
154                   (not (equal (cadr list) elt)))
155         (setq list (cdr list)))
156       (when (cdr list)
157         (setcdr list (cddr list)))
158       total)))
159
160 ;; Delete the current line (and the next N lines).
161 (defmacro gnus-delete-line (&optional n)
162   `(delete-region (progn (beginning-of-line) (point))
163                   (progn (forward-line ,(or n 1)) (point))))
164
165 (defun gnus-byte-code (func)
166   "Return a form that can be `eval'ed based on FUNC."
167   (let ((fval (indirect-function func)))
168     (if (byte-code-function-p fval)
169         (let ((flist (append fval nil)))
170           (setcar flist 'byte-code)
171           flist)
172       (cons 'progn (cddr fval)))))
173
174 (defun gnus-extract-address-components (from)
175   (let (name address)
176     ;; First find the address - the thing with the @ in it.  This may
177     ;; not be accurate in mail addresses, but does the trick most of
178     ;; the time in news messages.
179     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
180       (setq address (substring from (match-beginning 0) (match-end 0))))
181     ;; Then we check whether the "name <address>" format is used.
182     (and address
183          ;; Linear white space is not required.
184          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
185          (and (setq name (substring from 0 (match-beginning 0)))
186               ;; Strip any quotes from the name.
187               (string-match "\".*\"" name)
188               (setq name (substring name 1 (1- (match-end 0))))))
189     ;; If not, then "address (name)" is used.
190     (or name
191         (and (string-match "(.+)" from)
192              (setq name (substring from (1+ (match-beginning 0))
193                                    (1- (match-end 0)))))
194         (and (string-match "()" from)
195              (setq name address))
196         ;; XOVER might not support folded From headers.
197         (and (string-match "(.*" from)
198              (setq name (substring from (1+ (match-beginning 0))
199                                    (match-end 0)))))
200     (list (if (string= name "") nil name) (or address from))))
201
202
203 (defun gnus-fetch-field (field)
204   "Return the value of the header FIELD of current article."
205   (save-excursion
206     (save-restriction
207       (let ((case-fold-search t)
208             (inhibit-point-motion-hooks t))
209         (nnheader-narrow-to-headers)
210         (message-fetch-field field)))))
211
212 (defun gnus-goto-colon ()
213   (beginning-of-line)
214   (search-forward ":" (gnus-point-at-eol) t))
215
216 (defun gnus-remove-text-with-property (prop)
217   "Delete all text in the current buffer with text property PROP."
218   (save-excursion
219     (goto-char (point-min))
220     (while (not (eobp))
221       (while (get-text-property (point) prop)
222         (delete-char 1))
223       (goto-char (next-single-property-change (point) prop nil (point-max))))))
224
225 (defun gnus-newsgroup-directory-form (newsgroup)
226   "Make hierarchical directory name from NEWSGROUP name."
227   (let ((newsgroup (gnus-newsgroup-savable-name newsgroup))
228         (len (length newsgroup))
229         idx)
230     ;; If this is a foreign group, we don't want to translate the
231     ;; entire name.
232     (if (setq idx (string-match ":" newsgroup))
233         (aset newsgroup idx ?/)
234       (setq idx 0))
235     ;; Replace all occurrences of `.' with `/'.
236     (while (< idx len)
237       (when (= (aref newsgroup idx) ?.)
238         (aset newsgroup idx ?/))
239       (setq idx (1+ idx)))
240     newsgroup))
241
242 (defun gnus-newsgroup-savable-name (group)
243   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
244   ;; with dots.
245   (nnheader-replace-chars-in-string group ?/ ?.))
246
247 (defun gnus-string> (s1 s2)
248   (not (or (string< s1 s2)
249            (string= s1 s2))))
250
251 ;;; Time functions.
252
253 (defun gnus-file-newer-than (file date)
254   (let ((fdate (nth 5 (file-attributes file))))
255     (or (> (car fdate) (car date))
256         (and (= (car fdate) (car date))
257              (> (nth 1 fdate) (nth 1 date))))))
258
259 ;;; Keymap macros.
260
261 (defmacro gnus-local-set-keys (&rest plist)
262   "Set the keys in PLIST in the current keymap."
263   `(gnus-define-keys-1 (current-local-map) ',plist))
264
265 (defmacro gnus-define-keys (keymap &rest plist)
266   "Define all keys in PLIST in KEYMAP."
267   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
268
269 (defmacro gnus-define-keys-safe (keymap &rest plist)
270   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
271   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
272
273 (put 'gnus-define-keys 'lisp-indent-function 1)
274 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
275 (put 'gnus-local-set-keys 'lisp-indent-function 1)
276
277 (defmacro gnus-define-keymap (keymap &rest plist)
278   "Define all keys in PLIST in KEYMAP."
279   `(gnus-define-keys-1 ,keymap (quote ,plist)))
280
281 (put 'gnus-define-keymap 'lisp-indent-function 1)
282
283 (defun gnus-define-keys-1 (keymap plist &optional safe)
284   (when (null keymap)
285     (error "Can't set keys in a null keymap"))
286   (cond ((symbolp keymap)
287          (setq keymap (symbol-value keymap)))
288         ((keymapp keymap))
289         ((listp keymap)
290          (set (car keymap) nil)
291          (define-prefix-command (car keymap))
292          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
293          (setq keymap (symbol-value (car keymap)))))
294   (let (key)
295     (while plist
296       (when (symbolp (setq key (pop plist)))
297         (setq key (symbol-value key)))
298       (if (or (not safe)
299               (eq (lookup-key keymap key) 'undefined))
300           (define-key keymap key (pop plist))
301         (pop plist)))))
302
303 (defun gnus-completing-read (default prompt &rest args)
304   ;; Like `completing-read', except that DEFAULT is the default argument.
305   (let* ((prompt (if default
306                      (concat prompt " (default " default ") ")
307                    (concat prompt " ")))
308          (answer (apply 'completing-read prompt args)))
309     (if (or (null answer) (zerop (length answer)))
310         default
311       answer)))
312
313 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
314 ;; the echo area.
315 (defun gnus-y-or-n-p (prompt)
316   (prog1
317       (y-or-n-p prompt)
318     (message "")))
319
320 (defun gnus-yes-or-no-p (prompt)
321   (prog1
322       (yes-or-no-p prompt)
323     (message "")))
324
325 (defun gnus-dd-mmm (messy-date)
326   "Return a string like DD-MMM from a big messy string."
327   (condition-case ()
328       (format-time-string "%d-%b" (safe-date-to-time messy-date))
329     (error "  -   ")))
330
331 (defmacro gnus-date-get-time (date)
332   "Convert DATE string to Emacs time.
333 Cache the result as a text property stored in DATE."
334   ;; Either return the cached value...
335   `(let ((d ,date))
336      (if (equal "" d)
337          '(0 0)
338        (or (get-text-property 0 'gnus-time d)
339            ;; or compute the value...
340            (let ((time (safe-date-to-time d)))
341              ;; and store it back in the string.
342              (put-text-property 0 1 'gnus-time time d)
343              time)))))
344
345 (defsubst gnus-time-iso8601 (time)
346   "Return a string of TIME in YYYYMMDDTHHMMSS format."
347   (format-time-string "%Y%m%dT%H%M%S" time))
348
349 (defun gnus-date-iso8601 (date)
350   "Convert the DATE to YYYYMMDDTHHMMSS."
351   (condition-case ()
352       (gnus-time-iso8601 (gnus-date-get-time date))
353     (error "")))
354
355 (defun gnus-mode-string-quote (string)
356   "Quote all \"%\"'s in STRING."
357   (save-excursion
358     (gnus-set-work-buffer)
359     (insert string)
360     (goto-char (point-min))
361     (while (search-forward "%" nil t)
362       (insert "%"))
363     (buffer-string)))
364
365 ;; Make a hash table (default and minimum size is 256).
366 ;; Optional argument HASHSIZE specifies the table size.
367 (defun gnus-make-hashtable (&optional hashsize)
368   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
369
370 ;; Make a number that is suitable for hashing; bigger than MIN and
371 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
372 ;; hardware modulo operation, so they implement it in software.  On
373 ;; many sparcs over 50% of the time to intern is spent in the modulo.
374 ;; Yes, it's slower than actually computing the hash from the string!
375 ;; So we use powers of 2 so people can optimize the modulo to a mask.
376 (defun gnus-create-hash-size (min)
377   (let ((i 1))
378     (while (< i min)
379       (setq i (* 2 i)))
380     i))
381
382 (defcustom gnus-verbose 7
383   "*Integer that says how verbose Gnus should be.
384 The higher the number, the more messages Gnus will flash to say what
385 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
386 display most important messages; and at ten, Gnus will keep on
387 jabbering all the time."
388   :group 'gnus-start
389   :type 'integer)
390
391 ;; Show message if message has a lower level than `gnus-verbose'.
392 ;; Guideline for numbers:
393 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
394 ;; for things that take a long time, 7 - not very important messages
395 ;; on stuff, 9 - messages inside loops.
396 (defun gnus-message (level &rest args)
397   (if (<= level gnus-verbose)
398       (apply 'message args)
399     ;; We have to do this format thingy here even if the result isn't
400     ;; shown - the return value has to be the same as the return value
401     ;; from `message'.
402     (apply 'format args)))
403
404 (defun gnus-error (level &rest args)
405   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
406   (when (<= (floor level) gnus-verbose)
407     (apply 'message args)
408     (ding)
409     (let (duration)
410       (when (and (floatp level)
411                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
412         (sit-for duration))))
413   nil)
414
415 (defun gnus-split-references (references)
416   "Return a list of Message-IDs in REFERENCES."
417   (let ((beg 0)
418         ids)
419     (while (string-match "<[^>]+>" references beg)
420       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
421             ids))
422     (nreverse ids)))
423
424 (defsubst gnus-parent-id (references &optional n)
425   "Return the last Message-ID in REFERENCES.
426 If N, return the Nth ancestor instead."
427   (when references
428     (let ((ids (inline (gnus-split-references references))))
429       (while (nthcdr (or n 1) ids)
430         (setq ids (cdr ids)))
431       (car ids))))
432
433 (defsubst gnus-buffer-live-p (buffer)
434   "Say whether BUFFER is alive or not."
435   (and buffer
436        (get-buffer buffer)
437        (buffer-name (get-buffer buffer))))
438
439 (defun gnus-horizontal-recenter ()
440   "Recenter the current buffer horizontally."
441   (if (< (current-column) (/ (window-width) 2))
442       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
443     (let* ((orig (point))
444            (end (window-end (get-buffer-window (current-buffer) t)))
445            (max 0))
446       (when end
447         ;; Find the longest line currently displayed in the window.
448         (goto-char (window-start))
449         (while (and (not (eobp))
450                     (< (point) end))
451           (end-of-line)
452           (setq max (max max (current-column)))
453           (forward-line 1))
454         (goto-char orig)
455         ;; Scroll horizontally to center (sort of) the point.
456         (if (> max (window-width))
457             (set-window-hscroll
458              (get-buffer-window (current-buffer) t)
459              (min (- (current-column) (/ (window-width) 3))
460                   (+ 2 (- max (window-width)))))
461           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
462         max))))
463
464 (defun gnus-read-event-char ()
465   "Get the next event."
466   (let ((event (read-event)))
467     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
468     (cons (and (numberp event) event) event)))
469
470 (defun gnus-sortable-date (date)
471   "Make string suitable for sorting from DATE."
472   (gnus-time-iso8601 (date-to-time date)))
473
474 (defun gnus-copy-file (file &optional to)
475   "Copy FILE to TO."
476   (interactive
477    (list (read-file-name "Copy file: " default-directory)
478          (read-file-name "Copy file to: " default-directory)))
479   (unless to
480     (setq to (read-file-name "Copy file to: " default-directory)))
481   (when (file-directory-p to)
482     (setq to (concat (file-name-as-directory to)
483                      (file-name-nondirectory file))))
484   (copy-file file to))
485
486 (defvar gnus-work-buffer " *gnus work*")
487
488 (defun gnus-set-work-buffer ()
489   "Put point in the empty Gnus work buffer."
490   (if (get-buffer gnus-work-buffer)
491       (progn
492         (set-buffer gnus-work-buffer)
493         (erase-buffer))
494     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
495     (kill-all-local-variables)))
496
497 (defmacro gnus-group-real-name (group)
498   "Find the real name of a foreign newsgroup."
499   `(let ((gname ,group))
500      (if (string-match "^[^:]+:" gname)
501          (substring gname (match-end 0))
502        gname)))
503
504 (defun gnus-make-sort-function (funs)
505   "Return a composite sort condition based on the functions in FUNC."
506   (cond
507    ;; Just a simple function.
508    ((gnus-functionp funs) funs)
509    ;; No functions at all.
510    ((null funs) funs)
511    ;; A list of functions.
512    ((or (cdr funs)
513         (listp (car funs)))
514     `(lambda (t1 t2)
515        ,(gnus-make-sort-function-1 (reverse funs))))
516    ;; A list containing just one function.
517    (t
518     (car funs))))
519
520 (defun gnus-make-sort-function-1 (funs)
521   "Return a composite sort condition based on the functions in FUNC."
522   (let ((function (car funs))
523         (first 't1)
524         (last 't2))
525     (when (consp function)
526       (cond
527        ;; Reversed spec.
528        ((eq (car function) 'not)
529         (setq function (cadr function)
530               first 't2
531               last 't1))
532        ((gnus-functionp function)
533         ;; Do nothing.
534         )
535        (t
536         (error "Invalid sort spec: %s" function))))
537     (if (cdr funs)
538         `(or (,function ,first ,last)
539              (and (not (,function ,last ,first))
540                   ,(gnus-make-sort-function-1 (cdr funs))))
541       `(,function ,first ,last))))
542
543 (defun gnus-turn-off-edit-menu (type)
544   "Turn off edit menu in `gnus-TYPE-mode-map'."
545   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
546     [menu-bar edit] 'undefined))
547
548 (defun gnus-prin1 (form)
549   "Use `prin1' on FORM in the current buffer.
550 Bind `print-quoted' and `print-readably' to t while printing."
551   (let ((print-quoted t)
552         (print-readably t)
553         (print-escape-multibyte nil)
554         print-level print-length)
555     (prin1 form (current-buffer))))
556
557 (defun gnus-prin1-to-string (form)
558   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
559   (let ((print-quoted t)
560         (print-readably t))
561     (prin1-to-string form)))
562
563 (defun gnus-make-directory (directory)
564   "Make DIRECTORY (and all its parents) if it doesn't exist."
565   (let ((file-name-coding-system nnmail-pathname-coding-system)
566         (pathname-coding-system nnmail-pathname-coding-system))
567     (when (and directory
568                (not (file-exists-p directory)))
569       (make-directory directory t)))
570   t)
571
572 (defun gnus-write-buffer (file)
573   "Write the current buffer's contents to FILE."
574   ;; Make sure the directory exists.
575   (gnus-make-directory (file-name-directory file))
576   (let ((file-name-coding-system nnmail-pathname-coding-system)
577         (pathname-coding-system nnmail-pathname-coding-system))
578     ;; Write the buffer.
579     (write-region (point-min) (point-max) file nil 'quietly)))
580
581 (defun gnus-write-buffer-as-binary (file)
582   "Write the current buffer's contents to FILE without code conversion."
583   ;; Make sure the directory exists.
584   (gnus-make-directory (file-name-directory file))
585   ;; Write the buffer.
586   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
587
588 (defun gnus-write-buffer-as-coding-system (coding-system file)
589   "Write the current buffer's contents to FILE with code conversion."
590   ;; Make sure the directory exists.
591   (gnus-make-directory (file-name-directory file))
592   ;; Write the buffer.
593   (write-region-as-coding-system
594    coding-system (point-min) (point-max) file nil 'quietly))
595
596 (defun gnus-delete-file (file)
597   "Delete FILE if it exists."
598   (when (file-exists-p file)
599     (delete-file file)))
600
601 (defun gnus-strip-whitespace (string)
602   "Return STRING stripped of all whitespace."
603   (while (string-match "[\r\n\t ]+" string)
604     (setq string (replace-match "" t t string)))
605   string)
606
607 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
608   "The same as `put-text-property', but don't put this prop on any newlines in the region."
609   (save-match-data
610     (save-excursion
611       (save-restriction
612         (goto-char beg)
613         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
614           (gnus-put-text-property beg (match-beginning 0) prop val)
615           (setq beg (point)))
616         (gnus-put-text-property beg (point) prop val)))))
617
618 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
619                                                                    prop val)
620   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
621   (let ((b beg))
622     (while (/= b end)
623       (when (get-text-property b 'gnus-face)
624         (setq b (next-single-property-change b 'gnus-face nil end)))
625       (when (/= b end)
626         (gnus-put-text-property
627          b (setq b (next-single-property-change b 'gnus-face nil end))
628          prop val)))))
629
630 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
631 ;;; The primary idea here is to try to protect internal datastructures
632 ;;; from becoming corrupted when the user hits C-g, or if a hook or
633 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
634 ;;; updated at the same time, or information can be lost.
635
636 (defvar gnus-atomic-be-safe t
637   "If t, certain operations will be protected from interruption by C-g.")
638
639 (defmacro gnus-atomic-progn (&rest forms)
640   "Evaluate FORMS atomically, which means to protect the evaluation
641 from being interrupted by the user.  An error from the forms themselves
642 will return without finishing the operation.  Since interrupts from
643 the user are disabled, it is recommended that only the most minimal
644 operations are performed by FORMS.  If you wish to assign many
645 complicated values atomically, compute the results into temporary
646 variables and then do only the assignment atomically."
647   `(let ((inhibit-quit gnus-atomic-be-safe))
648      ,@forms))
649
650 (put 'gnus-atomic-progn 'lisp-indent-function 0)
651
652 (defmacro gnus-atomic-progn-assign (protect &rest forms)
653   "Evaluate FORMS, but insure that the variables listed in PROTECT
654 are not changed if anything in FORMS signals an error or otherwise
655 non-locally exits.  The variables listed in PROTECT are updated atomically.
656 It is safe to use gnus-atomic-progn-assign with long computations.
657
658 Note that if any of the symbols in PROTECT were unbound, they will be
659 set to nil on a sucessful assignment.  In case of an error or other
660 non-local exit, it will still be unbound."
661   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
662                                                   (concat (symbol-name x)
663                                                           "-tmp"))
664                                                  x))
665                                protect))
666          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
667                                temp-sym-map))
668          (temp-sym-let (mapcar (lambda (x) (list (car x)
669                                                  `(and (boundp ',(cadr x))
670                                                        ,(cadr x))))
671                                temp-sym-map))
672          (sym-temp-let sym-temp-map)
673          (temp-sym-assign (apply 'append temp-sym-map))
674          (sym-temp-assign (apply 'append sym-temp-map))
675          (result (make-symbol "result-tmp")))
676     `(let (,@temp-sym-let
677            ,result)
678        (let ,sym-temp-let
679          (setq ,result (progn ,@forms))
680          (setq ,@temp-sym-assign))
681        (let ((inhibit-quit gnus-atomic-be-safe))
682          (setq ,@sym-temp-assign))
683        ,result)))
684
685 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
686 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
687
688 (defmacro gnus-atomic-setq (&rest pairs)
689   "Similar to setq, except that the real symbols are only assigned when
690 there are no errors.  And when the real symbols are assigned, they are
691 done so atomically.  If other variables might be changed via side-effect,
692 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
693 with potentially long computations."
694   (let ((tpairs pairs)
695         syms)
696     (while tpairs
697       (push (car tpairs) syms)
698       (setq tpairs (cddr tpairs)))
699     `(gnus-atomic-progn-assign ,syms
700        (setq ,@pairs))))
701
702 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
703
704
705 ;;; Functions for saving to babyl/mail files.
706
707 (defvar rmail-default-rmail-file)
708 (defun gnus-output-to-rmail (filename &optional ask)
709   "Append the current article to an Rmail file named FILENAME."
710   (require 'rmail)
711   ;; Most of these codes are borrowed from rmailout.el.
712   (setq filename (expand-file-name filename))
713   (setq rmail-default-rmail-file filename)
714   (let ((artbuf (current-buffer))
715         (tmpbuf (get-buffer-create " *Gnus-output*")))
716     (save-excursion
717       (or (get-file-buffer filename)
718           (file-exists-p filename)
719           (if (or (not ask)
720                   (gnus-yes-or-no-p
721                    (concat "\"" filename "\" does not exist, create it? ")))
722               (let ((file-buffer (create-file-buffer filename)))
723                 (save-excursion
724                   (set-buffer file-buffer)
725                   (rmail-insert-rmail-file-header)
726                   (let ((require-final-newline nil))
727                     (gnus-write-buffer-as-coding-system
728                      nnheader-text-coding-system filename)))
729                 (kill-buffer file-buffer))
730             (error "Output file does not exist")))
731       (set-buffer tmpbuf)
732       (erase-buffer)
733       (insert-buffer-substring artbuf)
734       (gnus-convert-article-to-rmail)
735       ;; Decide whether to append to a file or to an Emacs buffer.
736       (let ((outbuf (get-file-buffer filename)))
737         (if (not outbuf)
738             (write-region-as-binary (point-min) (point-max) filename 'append)
739           ;; File has been visited, in buffer OUTBUF.
740           (set-buffer outbuf)
741           (let ((buffer-read-only nil)
742                 (msg (and (boundp 'rmail-current-message)
743                           (symbol-value 'rmail-current-message))))
744             ;; If MSG is non-nil, buffer is in RMAIL mode.
745             (when msg
746               (widen)
747               (narrow-to-region (point-max) (point-max)))
748             (insert-buffer-substring tmpbuf)
749             (when msg
750               (goto-char (point-min))
751               (widen)
752               (search-backward "\n\^_")
753               (narrow-to-region (point) (point-max))
754               (rmail-count-new-messages t)
755               (when (rmail-summary-exists)
756                 (rmail-select-summary
757                  (rmail-update-summary)))
758               (rmail-count-new-messages t)
759               (rmail-show-message msg))
760             (save-buffer)))))
761     (kill-buffer tmpbuf)))
762
763 (defun gnus-output-to-mail (filename &optional ask)
764   "Append the current article to a mail file named FILENAME."
765   (setq filename (expand-file-name filename))
766   (let ((artbuf (current-buffer))
767         (tmpbuf (get-buffer-create " *Gnus-output*")))
768     (save-excursion
769       ;; Create the file, if it doesn't exist.
770       (when (and (not (get-file-buffer filename))
771                  (not (file-exists-p filename)))
772         (if (or (not ask)
773                 (gnus-y-or-n-p
774                  (concat "\"" filename "\" does not exist, create it? ")))
775             (let ((file-buffer (create-file-buffer filename)))
776               (save-excursion
777                 (set-buffer file-buffer)
778                 (let ((require-final-newline nil))
779                   (gnus-write-buffer-as-coding-system
780                    nnheader-text-coding-system 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                       "port"))
856             alist elem result pair)
857         (insert-file-contents file)
858         (goto-char (point-min))
859         ;; Go through the file, line by line.
860         (while (not (eobp))
861           (narrow-to-region (point) (gnus-point-at-eol))
862           ;; For each line, get the tokens and values.
863           (while (not (eobp))
864             (skip-chars-forward "\t ")
865             ;; Skip lines that begin with a "#".
866             (if (eq (char-after) ?#)
867                 (goto-char (point-max))
868               (unless (eobp)
869                 (setq elem
870                       (if (= (following-char) ?\")
871                           (read (current-buffer))
872                         (buffer-substring
873                          (point) (progn (skip-chars-forward "^\t ")
874                                         (point)))))
875                 (cond
876                  ((equal elem "macdef")
877                   ;; We skip past the macro definition.
878                   (widen)
879                   (while (and (zerop (forward-line 1))
880                               (looking-at "$")))
881                   (narrow-to-region (point) (point)))
882                  ((member elem tokens)
883                   ;; Tokens that don't have a following value are ignored,
884                   ;; except "default".
885                   (when (and pair (or (cdr pair)
886                                       (equal (car pair) "default")))
887                     (push pair alist))
888                   (setq pair (list elem)))
889                  (t
890                   ;; Values that haven't got a preceding token are ignored.
891                   (when pair
892                     (setcdr pair elem)
893                     (push pair alist)
894                     (setq pair nil)))))))
895           (when alist
896             (push (nreverse alist) result))
897           (setq alist nil
898                 pair nil)
899           (widen)
900           (forward-line 1))
901         (nreverse result)))))
902
903 (defun gnus-netrc-machine (list machine &optional port defaultport)
904   "Return the netrc values from LIST for MACHINE or for the default entry.
905 If PORT specified, only return entries with matching port tokens.
906 Entries without port tokens default to DEFAULTPORT."
907   (let ((rest list)
908         result)
909     (while list
910       (when (equal (cdr (assoc "machine" (car list))) machine)
911         (push (car list) result))
912       (pop list))
913     (unless result
914       ;; No machine name matches, so we look for default entries.
915       (while rest
916         (when (assoc "default" (car rest))
917           (push (car rest) result))
918         (pop rest)))
919     (when result
920       (setq result (nreverse result))
921       (while (and result
922                   (not (equal (or port defaultport "nntp")
923                               (or (gnus-netrc-get (car result) "port")
924                                   defaultport "nntp"))))
925         (pop result))
926       (car result))))
927
928 (defun gnus-netrc-get (alist type)
929   "Return the value of token TYPE from ALIST."
930   (cdr (assoc type alist)))
931
932 ;;; Various
933
934 (defvar gnus-group-buffer)              ; Compiler directive
935 (defun gnus-alive-p ()
936   "Say whether Gnus is running or not."
937   (and (boundp 'gnus-group-buffer)
938        (get-buffer gnus-group-buffer)
939        (save-excursion
940          (set-buffer gnus-group-buffer)
941          (eq major-mode 'gnus-group-mode))))
942
943 (defun gnus-remove-duplicates (list)
944   (let (new (tail list))
945     (while tail
946       (or (member (car tail) new)
947           (setq new (cons (car tail) new)))
948       (setq tail (cdr tail)))
949     (nreverse new)))
950
951 (defun gnus-delete-if (predicate list)
952   "Delete elements from LIST that satisfy PREDICATE."
953   (let (out)
954     (while list
955       (unless (funcall predicate (car list))
956         (push (car list) out))
957       (pop list))
958     (nreverse out)))
959
960 (defun gnus-delete-alist (key alist)
961   "Delete all entries in ALIST that have a key eq to KEY."
962   (let (entry)
963     (while (setq entry (assq key alist))
964       (setq alist (delq entry alist)))
965     alist))
966
967 (defmacro gnus-pull (key alist &optional assoc-p)
968   "Modify ALIST to be without KEY."
969   (unless (symbolp alist)
970     (error "Not a symbol: %s" alist))
971   (let ((fun (if assoc-p 'assoc 'assq)))
972     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
973
974 (defun gnus-globalify-regexp (re)
975   "Returns a regexp that matches a whole line, iff RE matches a part of it."
976   (concat (unless (string-match "^\\^" re) "^.*")
977           re
978           (unless (string-match "\\$$" re) ".*$")))
979
980 (defun gnus-set-window-start (&optional point)
981   "Set the window start to POINT, or (point) if nil."
982   (let ((win (get-buffer-window (current-buffer) t)))
983     (when win
984       (set-window-start win (or point (point))))))
985
986 (defun gnus-annotation-in-region-p (b e)
987   (if (= b e)
988       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
989     (text-property-any b e 'gnus-undeletable t)))
990
991 (defun gnus-or (&rest elems)
992   "Return non-nil if any of the elements are non-nil."
993   (catch 'found
994     (while elems
995       (when (pop elems)
996         (throw 'found t)))))
997
998 (defun gnus-and (&rest elems)
999   "Return non-nil if all of the elements are non-nil."
1000   (catch 'found
1001     (while elems
1002       (unless (pop elems)
1003         (throw 'found nil)))
1004     t))
1005
1006 (defun gnus-write-active-file (file hashtb &optional full-names)
1007   (let ((output-coding-system nnmail-active-file-coding-system)
1008         (coding-system-for-write nnmail-active-file-coding-system))
1009     (with-temp-file file
1010       (mapatoms
1011        (lambda (sym)
1012          (when (and sym
1013                     (boundp sym)
1014                     (symbol-value sym))
1015            (insert (format "%S %d %d y\n"
1016                            (if full-names
1017                                sym
1018                              (intern (gnus-group-real-name (symbol-name sym))))
1019                            (or (cdr (symbol-value sym))
1020                                (car (symbol-value sym)))
1021                            (car (symbol-value sym))))))
1022        hashtb)
1023       (goto-char (point-max))
1024       (while (search-backward "\\." nil t)
1025         (delete-char 1)))))
1026
1027 (if (fboundp 'union)
1028     (defalias 'gnus-union 'union)
1029   (defun gnus-union (l1 l2)
1030     "Set union of lists L1 and L2."
1031     (cond ((null l1) l2)
1032           ((null l2) l1)
1033           ((equal l1 l2) l1)
1034           (t
1035            (or (>= (length l1) (length l2))
1036                (setq l1 (prog1 l2 (setq l2 l1))))
1037            (while l2
1038              (or (member (car l2) l1)
1039                  (push (car l2) l1))
1040              (pop l2))
1041            l1))))
1042
1043 (provide 'gnus-util)
1044
1045 ;;; gnus-util.el ends here