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