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