Synch with Oort Gnus.
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
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
36   (require 'cl)
37   ;; Fixme: this should be a gnus variable, not nnmail-.
38   (defvar nnmail-pathname-coding-system))
39 (eval-when-compile (require 'static))
40
41 (require 'custom)
42 (require 'nnheader)
43 (require 'time-date)
44
45 (eval-and-compile
46   (autoload 'message-fetch-field "message")
47   (autoload 'rmail-insert-rmail-file-header "rmail")
48   (autoload 'rmail-count-new-messages "rmail")
49   (autoload 'rmail-show-message "rmail"))
50
51 (defun gnus-boundp (variable)
52   "Return non-nil if VARIABLE is bound and non-nil."
53   (and (boundp variable)
54        (symbol-value variable)))
55
56 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
57   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
58   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
59         (w (make-symbol "w"))
60         (buf (make-symbol "buf"))
61         (frame (make-symbol "frame")))
62     `(let* ((,tempvar (selected-window))
63             (,buf ,buffer)
64             (,w (get-buffer-window ,buf 'visible))
65             ,frame)
66        (unwind-protect
67            (progn
68              (if ,w
69                  (progn
70                    (select-window ,w)
71                    (set-buffer (window-buffer ,w)))
72                (pop-to-buffer ,buf))
73              ,@forms)
74          (setq ,frame (selected-frame))
75          (select-window ,tempvar)
76          (select-frame ,frame)))))
77
78 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
79 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
80
81 (defmacro gnus-intern-safe (string hashtable)
82   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
83   `(let ((symbol (intern ,string ,hashtable)))
84      (or (boundp symbol)
85          (set symbol nil))
86      symbol))
87
88 ;; Avoid byte-compile warning.
89 ;; In Mule, this function will be redefined to `truncate-string',
90 ;; which takes 3 or 4 args.
91 (defun gnus-truncate-string (str width &rest ignore)
92   (substring str 0 width))
93
94 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
95 ;; to limit the length of a string.  This function is necessary since
96 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
97 (defsubst gnus-limit-string (str width)
98   (if (> (length str) width)
99       (substring str 0 width)
100     str))
101
102 (defsubst gnus-functionp (form)
103   "Return non-nil if FORM is funcallable."
104   (or (and (symbolp form) (fboundp form))
105       (and (listp form) (eq (car form) 'lambda))
106       (byte-code-function-p form)))
107
108 (defsubst gnus-goto-char (point)
109   (and point (goto-char point)))
110
111 (defmacro gnus-buffer-exists-p (buffer)
112   `(let ((buffer ,buffer))
113      (when buffer
114        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
115                 buffer))))
116
117 (defmacro gnus-kill-buffer (buffer)
118   `(let ((buf ,buffer))
119      (when (gnus-buffer-exists-p buf)
120        (kill-buffer buf))))
121
122 (static-cond
123  ((fboundp 'point-at-bol)
124   (defalias 'gnus-point-at-bol 'point-at-bol))
125  ((fboundp 'line-beginning-position)
126   (defalias 'gnus-point-at-bol 'line-beginning-position))
127  (t
128   (defun gnus-point-at-bol ()
129     "Return point at the beginning of the line."
130     (let ((p (point)))
131       (beginning-of-line)
132       (prog1
133           (point)
134         (goto-char p))))
135   ))
136 (static-cond
137  ((fboundp 'point-at-eol)
138   (defalias 'gnus-point-at-eol 'point-at-eol))
139  ((fboundp 'line-end-position)
140   (defalias 'gnus-point-at-eol 'line-end-position))
141  (t
142   (defun gnus-point-at-eol ()
143     "Return point at the end of the line."
144     (let ((p (point)))
145       (end-of-line)
146       (prog1
147           (point)
148         (goto-char p))))
149   ))
150
151 (defun gnus-delete-first (elt list)
152   "Delete by side effect the first occurrence of ELT as a member of LIST."
153   (if (equal (car list) elt)
154       (cdr list)
155     (let ((total list))
156       (while (and (cdr list)
157                   (not (equal (cadr list) elt)))
158         (setq list (cdr list)))
159       (when (cdr list)
160         (setcdr list (cddr list)))
161       total)))
162
163 ;; Delete the current line (and the next N lines).
164 (defmacro gnus-delete-line (&optional n)
165   `(delete-region (progn (beginning-of-line) (point))
166                   (progn (forward-line ,(or n 1)) (point))))
167
168 (defun gnus-byte-code (func)
169   "Return a form that can be `eval'ed based on FUNC."
170   (let ((fval (indirect-function func)))
171     (if (byte-code-function-p fval)
172         (let ((flist (append fval nil)))
173           (setcar flist 'byte-code)
174           flist)
175       (cons 'progn (cddr fval)))))
176
177 (defun gnus-extract-address-components (from)
178   (let (name address)
179     ;; First find the address - the thing with the @ in it.  This may
180     ;; not be accurate in mail addresses, but does the trick most of
181     ;; the time in news messages.
182     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
183       (setq address (substring from (match-beginning 0) (match-end 0))))
184     ;; Then we check whether the "name <address>" format is used.
185     (and address
186          ;; Linear white space is not required.
187          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
188          (and (setq name (substring from 0 (match-beginning 0)))
189               ;; Strip any quotes from the name.
190               (string-match "\".*\"" name)
191               (setq name (substring name 1 (1- (match-end 0))))))
192     ;; If not, then "address (name)" is used.
193     (or name
194         (and (string-match "(.+)" from)
195              (setq name (substring from (1+ (match-beginning 0))
196                                    (1- (match-end 0)))))
197         (and (string-match "()" from)
198              (setq name address))
199         ;; XOVER might not support folded From headers.
200         (and (string-match "(.*" from)
201              (setq name (substring from (1+ (match-beginning 0))
202                                    (match-end 0)))))
203     (list (if (string= name "") nil name) (or address from))))
204
205
206 (defun gnus-fetch-field (field)
207   "Return the value of the header FIELD of current article."
208   (save-excursion
209     (save-restriction
210       (let ((case-fold-search t)
211             (inhibit-point-motion-hooks t))
212         (nnheader-narrow-to-headers)
213         (message-fetch-field field)))))
214
215 (defun gnus-goto-colon ()
216   (beginning-of-line)
217   (search-forward ":" (gnus-point-at-eol) t))
218
219 (defun gnus-remove-text-with-property (prop)
220   "Delete all text in the current buffer with text property PROP."
221   (save-excursion
222     (goto-char (point-min))
223     (while (not (eobp))
224       (while (get-text-property (point) prop)
225         (delete-char 1))
226       (goto-char (next-single-property-change (point) prop nil (point-max))))))
227
228 (require 'nnheader)
229 (defun gnus-newsgroup-directory-form (newsgroup)
230   "Make hierarchical directory name from NEWSGROUP name."
231   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
232          (idx (string-match ":" newsgroup)))
233     (concat
234      (if idx (substring newsgroup 0 idx))
235      (if idx "/")
236      (nnheader-replace-chars-in-string
237       (if idx (substring newsgroup (1+ idx)) newsgroup)
238       ?. ?/))))
239
240 (defun gnus-newsgroup-savable-name (group)
241   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
242   ;; with dots.
243   (nnheader-replace-chars-in-string group ?/ ?.))
244
245 (defun gnus-string> (s1 s2)
246   (not (or (string< s1 s2)
247            (string= s1 s2))))
248
249 ;;; Time functions.
250
251 (defun gnus-file-newer-than (file date)
252   (let ((fdate (nth 5 (file-attributes file))))
253     (or (> (car fdate) (car date))
254         (and (= (car fdate) (car date))
255              (> (nth 1 fdate) (nth 1 date))))))
256
257 ;;; Keymap macros.
258
259 (defmacro gnus-local-set-keys (&rest plist)
260   "Set the keys in PLIST in the current keymap."
261   `(gnus-define-keys-1 (current-local-map) ',plist))
262
263 (defmacro gnus-define-keys (keymap &rest plist)
264   "Define all keys in PLIST in KEYMAP."
265   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
266
267 (defmacro gnus-define-keys-safe (keymap &rest plist)
268   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
269   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
270
271 (put 'gnus-define-keys 'lisp-indent-function 1)
272 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
273 (put 'gnus-local-set-keys 'lisp-indent-function 1)
274
275 (defmacro gnus-define-keymap (keymap &rest plist)
276   "Define all keys in PLIST in KEYMAP."
277   `(gnus-define-keys-1 ,keymap (quote ,plist)))
278
279 (put 'gnus-define-keymap 'lisp-indent-function 1)
280
281 (defun gnus-define-keys-1 (keymap plist &optional safe)
282   (when (null keymap)
283     (error "Can't set keys in a null keymap"))
284   (cond ((symbolp keymap)
285          (setq keymap (symbol-value keymap)))
286         ((keymapp keymap))
287         ((listp keymap)
288          (set (car keymap) nil)
289          (define-prefix-command (car keymap))
290          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
291          (setq keymap (symbol-value (car keymap)))))
292   (let (key)
293     (while plist
294       (when (symbolp (setq key (pop plist)))
295         (setq key (symbol-value key)))
296       (if (or (not safe)
297               (eq (lookup-key keymap key) 'undefined))
298           (define-key keymap key (pop plist))
299         (pop plist)))))
300
301 (defun gnus-completing-read (default prompt &rest args)
302   ;; Like `completing-read', except that DEFAULT is the default argument.
303   (let* ((prompt (if default
304                      (concat prompt " (default " default ") ")
305                    (concat prompt " ")))
306          (answer (apply 'completing-read prompt args)))
307     (if (or (null answer) (zerop (length answer)))
308         default
309       answer)))
310
311 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
312 ;; the echo area.
313 (defun gnus-y-or-n-p (prompt)
314   (prog1
315       (y-or-n-p prompt)
316     (message "")))
317
318 (defun gnus-yes-or-no-p (prompt)
319   (prog1
320       (yes-or-no-p prompt)
321     (message "")))
322
323 (defun gnus-dd-mmm (messy-date)
324   "Return a string like DD-MMM from a big messy string."
325   (condition-case ()
326       (format-time-string "%d-%b" (safe-date-to-time messy-date))
327     (error "  -   ")))
328
329 (defmacro gnus-date-get-time (date)
330   "Convert DATE string to Emacs time.
331 Cache the result as a text property stored in DATE."
332   ;; Either return the cached value...
333   `(let ((d ,date))
334      (if (equal "" d)
335          '(0 0)
336        (or (get-text-property 0 'gnus-time d)
337            ;; or compute the value...
338            (let ((time (safe-date-to-time d)))
339              ;; and store it back in the string.
340              (put-text-property 0 1 'gnus-time time d)
341              time)))))
342
343 (defsubst gnus-time-iso8601 (time)
344   "Return a string of TIME in YYYYMMDDTHHMMSS format."
345   (format-time-string "%Y%m%dT%H%M%S" time))
346
347 (defun gnus-date-iso8601 (date)
348   "Convert the DATE to YYYYMMDDTHHMMSS."
349   (condition-case ()
350       (gnus-time-iso8601 (gnus-date-get-time date))
351     (error "")))
352
353 (defun gnus-mode-string-quote (string)
354   "Quote all \"%\"'s in STRING."
355   (save-excursion
356     (gnus-set-work-buffer)
357     (insert string)
358     (goto-char (point-min))
359     (while (search-forward "%" nil t)
360       (insert "%"))
361     (buffer-string)))
362
363 ;; Make a hash table (default and minimum size is 256).
364 ;; Optional argument HASHSIZE specifies the table size.
365 (defun gnus-make-hashtable (&optional hashsize)
366   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
367
368 ;; Make a number that is suitable for hashing; bigger than MIN and
369 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
370 ;; hardware modulo operation, so they implement it in software.  On
371 ;; many sparcs over 50% of the time to intern is spent in the modulo.
372 ;; Yes, it's slower than actually computing the hash from the string!
373 ;; So we use powers of 2 so people can optimize the modulo to a mask.
374 (defun gnus-create-hash-size (min)
375   (let ((i 1))
376     (while (< i min)
377       (setq i (* 2 i)))
378     i))
379
380 (defcustom gnus-verbose 7
381   "*Integer that says how verbose Gnus should be.
382 The higher the number, the more messages Gnus will flash to say what
383 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
384 display most important messages; and at ten, Gnus will keep on
385 jabbering all the time."
386   :group 'gnus-start
387   :type 'integer)
388
389 ;; Show message if message has a lower level than `gnus-verbose'.
390 ;; Guideline for numbers:
391 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
392 ;; for things that take a long time, 7 - not very important messages
393 ;; on stuff, 9 - messages inside loops.
394 (defun gnus-message (level &rest args)
395   (if (<= level gnus-verbose)
396       (apply 'message args)
397     ;; We have to do this format thingy here even if the result isn't
398     ;; shown - the return value has to be the same as the return value
399     ;; from `message'.
400     (apply 'format args)))
401
402 (defun gnus-error (level &rest args)
403   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
404   (when (<= (floor level) gnus-verbose)
405     (apply 'message args)
406     (ding)
407     (let (duration)
408       (when (and (floatp level)
409                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
410         (sit-for duration))))
411   nil)
412
413 (defun gnus-split-references (references)
414   "Return a list of Message-IDs in REFERENCES."
415   (let ((beg 0)
416         ids)
417     (while (string-match "<[^> \t]+>" references beg)
418       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
419             ids))
420     (nreverse ids)))
421
422 (defsubst gnus-parent-id (references &optional n)
423   "Return the last Message-ID in REFERENCES.
424 If N, return the Nth ancestor instead."
425   (when references
426     (let ((ids (inline (gnus-split-references references))))
427       (while (nthcdr (or n 1) ids)
428         (setq ids (cdr ids)))
429       (car ids))))
430
431 (defsubst gnus-buffer-live-p (buffer)
432   "Say whether BUFFER is alive or not."
433   (and buffer
434        (get-buffer buffer)
435        (buffer-name (get-buffer buffer))))
436
437 (defun gnus-horizontal-recenter ()
438   "Recenter the current buffer horizontally."
439   (if (< (current-column) (/ (window-width) 2))
440       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
441     (let* ((orig (point))
442            (end (window-end (get-buffer-window (current-buffer) t)))
443            (max 0))
444       (when end
445         ;; Find the longest line currently displayed in the window.
446         (goto-char (window-start))
447         (while (and (not (eobp))
448                     (< (point) end))
449           (end-of-line)
450           (setq max (max max (current-column)))
451           (forward-line 1))
452         (goto-char orig)
453         ;; Scroll horizontally to center (sort of) the point.
454         (if (> max (window-width))
455             (set-window-hscroll
456              (get-buffer-window (current-buffer) t)
457              (min (- (current-column) (/ (window-width) 3))
458                   (+ 2 (- max (window-width)))))
459           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
460         max))))
461
462 (defun gnus-read-event-char ()
463   "Get the next event."
464   (let ((event (read-event)))
465     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
466     (cons (and (numberp event) event) event)))
467
468 (defun gnus-sortable-date (date)
469   "Make string suitable for sorting from DATE."
470   (gnus-time-iso8601 (date-to-time date)))
471
472 (defun gnus-copy-file (file &optional to)
473   "Copy FILE to TO."
474   (interactive
475    (list (read-file-name "Copy file: " default-directory)
476          (read-file-name "Copy file to: " default-directory)))
477   (unless to
478     (setq to (read-file-name "Copy file to: " default-directory)))
479   (when (file-directory-p to)
480     (setq to (concat (file-name-as-directory to)
481                      (file-name-nondirectory file))))
482   (copy-file file to))
483
484 (defvar gnus-work-buffer " *gnus work*")
485
486 (defun gnus-set-work-buffer ()
487   "Put point in the empty Gnus work buffer."
488   (if (get-buffer gnus-work-buffer)
489       (progn
490         (set-buffer gnus-work-buffer)
491         (erase-buffer))
492     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
493     (kill-all-local-variables)))
494
495 (defmacro gnus-group-real-name (group)
496   "Find the real name of a foreign newsgroup."
497   `(let ((gname ,group))
498      (if (string-match "^[^:]+:" gname)
499          (substring gname (match-end 0))
500        gname)))
501
502 (defun gnus-make-sort-function (funs)
503   "Return a composite sort condition based on the functions in FUNC."
504   (cond
505    ;; Just a simple function.
506    ((gnus-functionp funs) funs)
507    ;; No functions at all.
508    ((null funs) funs)
509    ;; A list of functions.
510    ((or (cdr funs)
511         (listp (car funs)))
512     (gnus-byte-compile
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   (require 'nnmail)
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 (if (fboundp 'assq-delete-all)
961     (defalias 'gnus-delete-alist 'assq-delete-all)
962   (defun gnus-delete-alist (key alist)
963     "Delete from ALIST all elements whose car is KEY.
964 Return the modified alist."
965     (let (entry)
966       (while (setq entry (assq key alist))
967         (setq alist (delq entry alist)))
968       alist)))
969
970 (defmacro gnus-pull (key alist &optional assoc-p)
971   "Modify ALIST to be without KEY."
972   (unless (symbolp alist)
973     (error "Not a symbol: %s" alist))
974   (let ((fun (if assoc-p 'assoc 'assq)))
975     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
976
977 (defun gnus-globalify-regexp (re)
978   "Returns a regexp that matches a whole line, iff RE matches a part of it."
979   (concat (unless (string-match "^\\^" re) "^.*")
980           re
981           (unless (string-match "\\$$" re) ".*$")))
982
983 (defun gnus-set-window-start (&optional point)
984   "Set the window start to POINT, or (point) if nil."
985   (let ((win (get-buffer-window (current-buffer) t)))
986     (when win
987       (set-window-start win (or point (point))))))
988
989 (defun gnus-annotation-in-region-p (b e)
990   (if (= b e)
991       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
992     (text-property-any b e 'gnus-undeletable t)))
993
994 (defun gnus-or (&rest elems)
995   "Return non-nil if any of the elements are non-nil."
996   (catch 'found
997     (while elems
998       (when (pop elems)
999         (throw 'found t)))))
1000
1001 (defun gnus-and (&rest elems)
1002   "Return non-nil if all of the elements are non-nil."
1003   (catch 'found
1004     (while elems
1005       (unless (pop elems)
1006         (throw 'found nil)))
1007     t))
1008
1009 (defun gnus-write-active-file (file hashtb &optional full-names)
1010   (let ((output-coding-system nnmail-active-file-coding-system)
1011         (coding-system-for-write nnmail-active-file-coding-system))
1012     (with-temp-file file
1013       (mapatoms
1014        (lambda (sym)
1015          (when (and sym
1016                     (boundp sym)
1017                     (symbol-value sym))
1018            (insert (format "%S %d %d y\n"
1019                            (if full-names
1020                                sym
1021                              (intern (gnus-group-real-name (symbol-name sym))))
1022                            (or (cdr (symbol-value sym))
1023                                (car (symbol-value sym)))
1024                            (car (symbol-value sym))))))
1025        hashtb)
1026       (goto-char (point-max))
1027       (while (search-backward "\\." nil t)
1028         (delete-char 1)))))
1029
1030 (if (fboundp 'union)
1031     (defalias 'gnus-union 'union)
1032   (defun gnus-union (l1 l2)
1033     "Set union of lists L1 and L2."
1034     (cond ((null l1) l2)
1035           ((null l2) l1)
1036           ((equal l1 l2) l1)
1037           (t
1038            (or (>= (length l1) (length l2))
1039                (setq l1 (prog1 l2 (setq l2 l1))))
1040            (while l2
1041              (or (member (car l2) l1)
1042                  (push (car l2) l1))
1043              (pop l2))
1044            l1))))
1045
1046 (defun gnus-add-text-properties-when
1047   (property value start end properties &optional object)
1048   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1049   (let (point)
1050     (while (and start
1051                 (< start end) ;; XEmacs will loop for every when start=end.
1052                 (setq point (text-property-not-all start end property value)))
1053       (gnus-add-text-properties start point properties object)
1054       (setq start (text-property-any point end property value)))
1055     (if start
1056         (gnus-add-text-properties start end properties object))))
1057
1058 (defun gnus-remove-text-properties-when
1059   (property value start end properties &optional object)
1060   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1061   (let (point)
1062     (while (and start
1063                 (< start end)
1064                 (setq point (text-property-not-all start end property value)))
1065       (remove-text-properties start point properties object)
1066       (setq start (text-property-any point end property value)))
1067     (if start
1068         (remove-text-properties start end properties object))
1069     t))
1070
1071 (defun gnus-string-equal (x y)
1072   "Like `string-equal', except it compares case-insensitively."
1073   (and (= (length x) (length y))
1074        (or (string-equal x y)
1075            (string-equal (downcase x) (downcase y)))))
1076
1077 (defcustom gnus-use-byte-compile t
1078   "If non-nil, byte-compile crucial run-time codes."
1079   :type 'boolean
1080   :version "21.1"
1081   :group 'gnus-various)
1082
1083 (defun gnus-byte-compile (form)
1084   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1085   (if gnus-use-byte-compile
1086       (progn
1087         (require 'bytecomp)
1088         (defalias 'gnus-byte-compile 'byte-compile)
1089         (byte-compile form))
1090     form))
1091
1092 (provide 'gnus-util)
1093
1094 ;;; gnus-util.el ends here