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