* gnus-sum.el (gnus-summary-initial-limit): Inline
[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 %d '%y"))                      ;;this one is used when no
347                                             ;;other does match
348   "Alist of time in seconds and format specification used to display dates not older.
349 The first element must be a number or a function returning a
350 number. The second element is a format-specification as described in
351 the documentation for format-time-string.  The list must be ordered
352 smallest number up. When there is an element, which is not a number,
353 the corresponding format-specification will be used, disregarding any
354 following elements.  You can use the functions gnus-seconds-today,
355 gnus-seconds-month, gnus-seconds-year which will return the number of
356 seconds which passed today/this month/this year.")
357
358 (defun gnus-user-date (messy-date)
359   "Format the messy-date acording to gnus-user-date-format-alist.
360 Returns \"  ?  \" if there's bad input or if an other error occurs.
361 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
362   (condition-case ()
363       (let* ((messy-date (safe-date-to-time messy-date))
364              (now (current-time))
365              ;;If we don't find something suitable we'll use this one
366              (my-format "%b %m '%y")
367              (high (lsh (- (car now) (car messy-date)) 16)))
368         (if (and (> high -1) (= (logand high 65535) 0))
369             ;;overflow and bad input
370             (let* ((difference (+ high (- (car (cdr now))
371                                           (car (cdr messy-date)))))
372                    (templist gnus-user-date-format-alist)
373                    (top (eval (caar templist))))
374               (while (if (numberp top) (< top difference) (not top))
375                 (progn
376                   (setq templist (cdr templist))
377                   (setq top (eval (caar templist)))))
378               (if (stringp (cdr (car templist)))
379                   (setq my-format (cdr (car templist))))))
380         (format-time-string (eval my-format) messy-date))
381     (error "  ?   ")))
382 ;;end of Frank's code
383
384 (defun gnus-dd-mmm (messy-date)
385   "Return a string like DD-MMM from a big messy string."
386   (condition-case ()
387       (format-time-string "%d-%b" (safe-date-to-time messy-date))
388     (error "  -   ")))
389
390 (defmacro gnus-date-get-time (date)
391   "Convert DATE string to Emacs time.
392 Cache the result as a text property stored in DATE."
393   ;; Either return the cached value...
394   `(let ((d ,date))
395      (if (equal "" d)
396          '(0 0)
397        (or (get-text-property 0 'gnus-time d)
398            ;; or compute the value...
399            (let ((time (safe-date-to-time d)))
400              ;; and store it back in the string.
401              (put-text-property 0 1 'gnus-time time d)
402              time)))))
403
404 (defsubst gnus-time-iso8601 (time)
405   "Return a string of TIME in YYYYMMDDTHHMMSS format."
406   (format-time-string "%Y%m%dT%H%M%S" time))
407
408 (defun gnus-date-iso8601 (date)
409   "Convert the DATE to YYYYMMDDTHHMMSS."
410   (condition-case ()
411       (gnus-time-iso8601 (gnus-date-get-time date))
412     (error "")))
413
414 (defun gnus-mode-string-quote (string)
415   "Quote all \"%\"'s in STRING."
416   (gnus-replace-in-string string "%" "%%"))
417
418 ;; Make a hash table (default and minimum size is 256).
419 ;; Optional argument HASHSIZE specifies the table size.
420 (defun gnus-make-hashtable (&optional hashsize)
421   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
422
423 ;; Make a number that is suitable for hashing; bigger than MIN and
424 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
425 ;; hardware modulo operation, so they implement it in software.  On
426 ;; many sparcs over 50% of the time to intern is spent in the modulo.
427 ;; Yes, it's slower than actually computing the hash from the string!
428 ;; So we use powers of 2 so people can optimize the modulo to a mask.
429 (defun gnus-create-hash-size (min)
430   (let ((i 1))
431     (while (< i min)
432       (setq i (* 2 i)))
433     i))
434
435 (defcustom gnus-verbose 7
436   "*Integer that says how verbose Gnus should be.
437 The higher the number, the more messages Gnus will flash to say what
438 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
439 display most important messages; and at ten, Gnus will keep on
440 jabbering all the time."
441   :group 'gnus-start
442   :type 'integer)
443
444 ;; Show message if message has a lower level than `gnus-verbose'.
445 ;; Guideline for numbers:
446 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
447 ;; for things that take a long time, 7 - not very important messages
448 ;; on stuff, 9 - messages inside loops.
449 (defun gnus-message (level &rest args)
450   (if (<= level gnus-verbose)
451       (apply 'message args)
452     ;; We have to do this format thingy here even if the result isn't
453     ;; shown - the return value has to be the same as the return value
454     ;; from `message'.
455     (apply 'format args)))
456
457 (defun gnus-error (level &rest args)
458   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
459   (when (<= (floor level) gnus-verbose)
460     (apply 'message args)
461     (ding)
462     (let (duration)
463       (when (and (floatp level)
464                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
465         (sit-for duration))))
466   nil)
467
468 (defun gnus-split-references (references)
469   "Return a list of Message-IDs in REFERENCES."
470   (let ((beg 0)
471         ids)
472     (while (string-match "<[^> \t]+>" references beg)
473       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
474             ids))
475     (nreverse ids)))
476
477 (defsubst gnus-parent-id (references &optional n)
478   "Return the last Message-ID in REFERENCES.
479 If N, return the Nth ancestor instead."
480   (when (and references
481              (not (zerop (length references))))
482     (let ((ids (inline (gnus-split-references references))))
483       (while (nthcdr (or n 1) ids)
484         (setq ids (cdr ids)))
485       (car ids))))
486
487 (defun gnus-buffer-live-p (buffer)
488   "Say whether BUFFER is alive or not."
489   (and buffer
490        (get-buffer buffer)
491        (buffer-name (get-buffer buffer))))
492
493 (defun gnus-horizontal-recenter ()
494   "Recenter the current buffer horizontally."
495   (if (< (current-column) (/ (window-width) 2))
496       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
497     (let* ((orig (point))
498            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
499            (max 0))
500       (when end
501         ;; Find the longest line currently displayed in the window.
502         (goto-char (window-start))
503         (while (and (not (eobp))
504                     (< (point) end))
505           (end-of-line)
506           (setq max (max max (current-column)))
507           (forward-line 1))
508         (goto-char orig)
509         ;; Scroll horizontally to center (sort of) the point.
510         (if (> max (window-width))
511             (set-window-hscroll
512              (gnus-get-buffer-window (current-buffer) t)
513              (min (- (current-column) (/ (window-width) 3))
514                   (+ 2 (- max (window-width)))))
515           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
516         max))))
517
518 (defun gnus-read-event-char ()
519   "Get the next event."
520   (let ((event (read-event)))
521     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
522     (cons (and (numberp event) event) event)))
523
524 (defun gnus-sortable-date (date)
525   "Make string suitable for sorting from DATE."
526   (gnus-time-iso8601 (date-to-time date)))
527
528 (defun gnus-copy-file (file &optional to)
529   "Copy FILE to TO."
530   (interactive
531    (list (read-file-name "Copy file: " default-directory)
532          (read-file-name "Copy file to: " default-directory)))
533   (unless to
534     (setq to (read-file-name "Copy file to: " default-directory)))
535   (when (file-directory-p to)
536     (setq to (concat (file-name-as-directory to)
537                      (file-name-nondirectory file))))
538   (copy-file file to))
539
540 (defvar gnus-work-buffer " *gnus work*")
541
542 (defun gnus-set-work-buffer ()
543   "Put point in the empty Gnus work buffer."
544   (if (get-buffer gnus-work-buffer)
545       (progn
546         (set-buffer gnus-work-buffer)
547         (erase-buffer))
548     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
549     (kill-all-local-variables)
550     (mm-enable-multibyte)))
551
552 (defmacro gnus-group-real-name (group)
553   "Find the real name of a foreign newsgroup."
554   `(let ((gname ,group))
555      (if (string-match "^[^:]+:" gname)
556          (substring gname (match-end 0))
557        gname)))
558
559 (defun gnus-make-sort-function (funs)
560   "Return a composite sort condition based on the functions in FUNC."
561   (cond
562    ;; Just a simple function.
563    ((gnus-functionp funs) funs)
564    ;; No functions at all.
565    ((null funs) funs)
566    ;; A list of functions.
567    ((or (cdr funs)
568         (listp (car funs)))
569     (gnus-byte-compile
570      `(lambda (t1 t2)
571         ,(gnus-make-sort-function-1 (reverse funs)))))
572    ;; A list containing just one function.
573    (t
574     (car funs))))
575
576 (defun gnus-make-sort-function-1 (funs)
577   "Return a composite sort condition based on the functions in FUNC."
578   (let ((function (car funs))
579         (first 't1)
580         (last 't2))
581     (when (consp function)
582       (cond
583        ;; Reversed spec.
584        ((eq (car function) 'not)
585         (setq function (cadr function)
586               first 't2
587               last 't1))
588        ((gnus-functionp function)
589         ;; Do nothing.
590         )
591        (t
592         (error "Invalid sort spec: %s" function))))
593     (if (cdr funs)
594         `(or (,function ,first ,last)
595              (and (not (,function ,last ,first))
596                   ,(gnus-make-sort-function-1 (cdr funs))))
597       `(,function ,first ,last))))
598
599 (defun gnus-turn-off-edit-menu (type)
600   "Turn off edit menu in `gnus-TYPE-mode-map'."
601   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
602     [menu-bar edit] 'undefined))
603
604 (defun gnus-prin1 (form)
605   "Use `prin1' on FORM in the current buffer.
606 Bind `print-quoted' and `print-readably' to t while printing."
607   (let ((print-quoted t)
608         (print-readably t)
609         (print-escape-multibyte nil)
610         print-level print-length)
611     (prin1 form (current-buffer))))
612
613 (defun gnus-prin1-to-string (form)
614   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
615   (let ((print-quoted t)
616         (print-readably t))
617     (prin1-to-string form)))
618
619 (defun gnus-make-directory (directory)
620   "Make DIRECTORY (and all its parents) if it doesn't exist."
621   (require 'nnmail)
622   (let ((file-name-coding-system nnmail-pathname-coding-system))
623     (when (and directory
624                (not (file-exists-p directory)))
625       (make-directory directory t)))
626   t)
627
628 (defun gnus-write-buffer (file)
629   "Write the current buffer's contents to FILE."
630   ;; Make sure the directory exists.
631   (gnus-make-directory (file-name-directory file))
632   (let ((file-name-coding-system nnmail-pathname-coding-system))
633     ;; Write the buffer.
634     (write-region (point-min) (point-max) file nil 'quietly)))
635
636 (defun gnus-delete-file (file)
637   "Delete FILE if it exists."
638   (when (file-exists-p file)
639     (delete-file file)))
640
641 (defun gnus-strip-whitespace (string)
642   "Return STRING stripped of all whitespace."
643   (while (string-match "[\r\n\t ]+" string)
644     (setq string (replace-match "" t t string)))
645   string)
646
647 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
648   "The same as `put-text-property', but don't put this prop on any newlines in the region."
649   (save-match-data
650     (save-excursion
651       (save-restriction
652         (goto-char beg)
653         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
654           (gnus-put-text-property beg (match-beginning 0) prop val)
655           (setq beg (point)))
656         (gnus-put-text-property beg (point) prop val)))))
657
658 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
659   "The same as `put-text-property', but don't put this prop on any newlines in the region."
660   (save-match-data
661     (save-excursion
662       (save-restriction
663         (goto-char beg)
664         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
665           (gnus-overlay-put
666            (gnus-make-overlay beg (match-beginning 0))
667            prop val)
668           (setq beg (point)))
669         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
670
671 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
672                                                                    prop val)
673   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
674   (let ((b beg))
675     (while (/= b end)
676       (when (get-text-property b 'gnus-face)
677         (setq b (next-single-property-change b 'gnus-face nil end)))
678       (when (/= b end)
679         (inline
680           (gnus-put-text-property
681            b (setq b (next-single-property-change b 'gnus-face nil end))
682            prop val))))))
683
684 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
685 ;;; The primary idea here is to try to protect internal datastructures
686 ;;; from becoming corrupted when the user hits C-g, or if a hook or
687 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
688 ;;; updated at the same time, or information can be lost.
689
690 (defvar gnus-atomic-be-safe t
691   "If t, certain operations will be protected from interruption by C-g.")
692
693 (defmacro gnus-atomic-progn (&rest forms)
694   "Evaluate FORMS atomically, which means to protect the evaluation
695 from being interrupted by the user.  An error from the forms themselves
696 will return without finishing the operation.  Since interrupts from
697 the user are disabled, it is recommended that only the most minimal
698 operations are performed by FORMS.  If you wish to assign many
699 complicated values atomically, compute the results into temporary
700 variables and then do only the assignment atomically."
701   `(let ((inhibit-quit gnus-atomic-be-safe))
702      ,@forms))
703
704 (put 'gnus-atomic-progn 'lisp-indent-function 0)
705
706 (defmacro gnus-atomic-progn-assign (protect &rest forms)
707   "Evaluate FORMS, but insure that the variables listed in PROTECT
708 are not changed if anything in FORMS signals an error or otherwise
709 non-locally exits.  The variables listed in PROTECT are updated atomically.
710 It is safe to use gnus-atomic-progn-assign with long computations.
711
712 Note that if any of the symbols in PROTECT were unbound, they will be
713 set to nil on a sucessful assignment.  In case of an error or other
714 non-local exit, it will still be unbound."
715   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
716                                                   (concat (symbol-name x)
717                                                           "-tmp"))
718                                                  x))
719                                protect))
720          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
721                                temp-sym-map))
722          (temp-sym-let (mapcar (lambda (x) (list (car x)
723                                                  `(and (boundp ',(cadr x))
724                                                        ,(cadr x))))
725                                temp-sym-map))
726          (sym-temp-let sym-temp-map)
727          (temp-sym-assign (apply 'append temp-sym-map))
728          (sym-temp-assign (apply 'append sym-temp-map))
729          (result (make-symbol "result-tmp")))
730     `(let (,@temp-sym-let
731            ,result)
732        (let ,sym-temp-let
733          (setq ,result (progn ,@forms))
734          (setq ,@temp-sym-assign))
735        (let ((inhibit-quit gnus-atomic-be-safe))
736          (setq ,@sym-temp-assign))
737        ,result)))
738
739 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
740 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
741
742 (defmacro gnus-atomic-setq (&rest pairs)
743   "Similar to setq, except that the real symbols are only assigned when
744 there are no errors.  And when the real symbols are assigned, they are
745 done so atomically.  If other variables might be changed via side-effect,
746 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
747 with potentially long computations."
748   (let ((tpairs pairs)
749         syms)
750     (while tpairs
751       (push (car tpairs) syms)
752       (setq tpairs (cddr tpairs)))
753     `(gnus-atomic-progn-assign ,syms
754        (setq ,@pairs))))
755
756 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
757
758
759 ;;; Functions for saving to babyl/mail files.
760
761 (defvar rmail-default-rmail-file)
762 (defun gnus-output-to-rmail (filename &optional ask)
763   "Append the current article to an Rmail file named FILENAME."
764   (require 'rmail)
765   ;; Most of these codes are borrowed from rmailout.el.
766   (setq filename (expand-file-name filename))
767   (setq rmail-default-rmail-file filename)
768   (let ((artbuf (current-buffer))
769         (tmpbuf (get-buffer-create " *Gnus-output*")))
770     (save-excursion
771       (or (get-file-buffer filename)
772           (file-exists-p filename)
773           (if (or (not ask)
774                   (gnus-yes-or-no-p
775                    (concat "\"" filename "\" does not exist, create it? ")))
776               (let ((file-buffer (create-file-buffer filename)))
777                 (save-excursion
778                   (set-buffer file-buffer)
779                   (rmail-insert-rmail-file-header)
780                   (let ((require-final-newline nil)
781                         (coding-system-for-write mm-text-coding-system))
782                     (gnus-write-buffer filename)))
783                 (kill-buffer file-buffer))
784             (error "Output file does not exist")))
785       (set-buffer tmpbuf)
786       (erase-buffer)
787       (insert-buffer-substring artbuf)
788       (gnus-convert-article-to-rmail)
789       ;; Decide whether to append to a file or to an Emacs buffer.
790       (let ((outbuf (get-file-buffer filename)))
791         (if (not outbuf)
792             (let ((file-name-coding-system nnmail-pathname-coding-system))
793               (mm-append-to-file (point-min) (point-max) filename))
794           ;; File has been visited, in buffer OUTBUF.
795           (set-buffer outbuf)
796           (let ((buffer-read-only nil)
797                 (msg (and (boundp 'rmail-current-message)
798                           (symbol-value 'rmail-current-message))))
799             ;; If MSG is non-nil, buffer is in RMAIL mode.
800             (when msg
801               (widen)
802               (narrow-to-region (point-max) (point-max)))
803             (insert-buffer-substring tmpbuf)
804             (when msg
805               (goto-char (point-min))
806               (widen)
807               (search-backward "\n\^_")
808               (narrow-to-region (point) (point-max))
809               (rmail-count-new-messages t)
810               (when (rmail-summary-exists)
811                 (rmail-select-summary
812                  (rmail-update-summary)))
813               (rmail-count-new-messages t)
814               (rmail-show-message msg))
815             (save-buffer)))))
816     (kill-buffer tmpbuf)))
817
818 (defun gnus-output-to-mail (filename &optional ask)
819   "Append the current article to a mail file named FILENAME."
820   (setq filename (expand-file-name filename))
821   (let ((artbuf (current-buffer))
822         (tmpbuf (get-buffer-create " *Gnus-output*")))
823     (save-excursion
824       ;; Create the file, if it doesn't exist.
825       (when (and (not (get-file-buffer filename))
826                  (not (file-exists-p filename)))
827         (if (or (not ask)
828                 (gnus-y-or-n-p
829                  (concat "\"" filename "\" does not exist, create it? ")))
830             (let ((file-buffer (create-file-buffer filename)))
831               (save-excursion
832                 (set-buffer file-buffer)
833                 (let ((require-final-newline nil)
834                       (coding-system-for-write mm-text-coding-system))
835                   (gnus-write-buffer filename)))
836               (kill-buffer file-buffer))
837           (error "Output file does not exist")))
838       (set-buffer tmpbuf)
839       (erase-buffer)
840       (insert-buffer-substring artbuf)
841       (goto-char (point-min))
842       (if (looking-at "From ")
843           (forward-line 1)
844         (insert "From nobody " (current-time-string) "\n"))
845       (let (case-fold-search)
846         (while (re-search-forward "^From " nil t)
847           (beginning-of-line)
848           (insert ">")))
849       ;; Decide whether to append to a file or to an Emacs buffer.
850       (let ((outbuf (get-file-buffer filename)))
851         (if (not outbuf)
852             (let ((buffer-read-only nil))
853               (save-excursion
854                 (goto-char (point-max))
855                 (forward-char -2)
856                 (unless (looking-at "\n\n")
857                   (goto-char (point-max))
858                   (unless (bolp)
859                     (insert "\n"))
860                   (insert "\n"))
861                 (goto-char (point-max))
862                 (let ((file-name-coding-system nnmail-pathname-coding-system))
863                   (mm-append-to-file (point-min) (point-max) filename))))
864           ;; File has been visited, in buffer OUTBUF.
865           (set-buffer outbuf)
866           (let ((buffer-read-only nil))
867             (goto-char (point-max))
868             (unless (eobp)
869               (insert "\n"))
870             (insert "\n")
871             (insert-buffer-substring tmpbuf)))))
872     (kill-buffer tmpbuf)))
873
874 (defun gnus-convert-article-to-rmail ()
875   "Convert article in current buffer to Rmail message format."
876   (let ((buffer-read-only nil))
877     ;; Convert article directly into Babyl format.
878     (goto-char (point-min))
879     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
880     (while (search-forward "\n\^_" nil t) ;single char
881       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
882     (goto-char (point-max))
883     (insert "\^_")))
884
885 (defun gnus-map-function (funs arg)
886   "Applies the result of the first function in FUNS to the second, and so on.
887 ARG is passed to the first function."
888   (let ((myfuns funs))
889     (while myfuns
890       (setq arg (funcall (pop myfuns) arg)))
891     arg))
892
893 (defun gnus-run-hooks (&rest funcs)
894   "Does the same as `run-hooks', but saves excursion."
895   (let ((buf (current-buffer)))
896     (unwind-protect
897         (apply 'run-hooks funcs)
898       (set-buffer buf))))
899
900 ;;;
901 ;;; .netrc and .authinforc parsing
902 ;;;
903
904 (defun gnus-parse-netrc (file)
905   "Parse FILE and return an list of all entries in the file."
906   (when (file-exists-p file)
907     (with-temp-buffer
908       (let ((tokens '("machine" "default" "login"
909                       "password" "account" "macdef" "force"
910                       "port"))
911             alist elem result pair)
912         (insert-file-contents file)
913         (goto-char (point-min))
914         ;; Go through the file, line by line.
915         (while (not (eobp))
916           (narrow-to-region (point) (gnus-point-at-eol))
917           ;; For each line, get the tokens and values.
918           (while (not (eobp))
919             (skip-chars-forward "\t ")
920             ;; Skip lines that begin with a "#".
921             (if (eq (char-after) ?#)
922                 (goto-char (point-max))
923               (unless (eobp)
924                 (setq elem
925                       (if (= (following-char) ?\")
926                           (read (current-buffer))
927                         (buffer-substring
928                          (point) (progn (skip-chars-forward "^\t ")
929                                         (point)))))
930                 (cond
931                  ((equal elem "macdef")
932                   ;; We skip past the macro definition.
933                   (widen)
934                   (while (and (zerop (forward-line 1))
935                               (looking-at "$")))
936                   (narrow-to-region (point) (point)))
937                  ((member elem tokens)
938                   ;; Tokens that don't have a following value are ignored,
939                   ;; except "default".
940                   (when (and pair (or (cdr pair)
941                                       (equal (car pair) "default")))
942                     (push pair alist))
943                   (setq pair (list elem)))
944                  (t
945                   ;; Values that haven't got a preceding token are ignored.
946                   (when pair
947                     (setcdr pair elem)
948                     (push pair alist)
949                     (setq pair nil)))))))
950           (when alist
951             (push (nreverse alist) result))
952           (setq alist nil
953                 pair nil)
954           (widen)
955           (forward-line 1))
956         (nreverse result)))))
957
958 (defun gnus-netrc-machine (list machine &optional port defaultport)
959   "Return the netrc values from LIST for MACHINE or for the default entry.
960 If PORT specified, only return entries with matching port tokens.
961 Entries without port tokens default to DEFAULTPORT."
962   (let ((rest list)
963         result)
964     (while list
965       (when (equal (cdr (assoc "machine" (car list))) machine)
966         (push (car list) result))
967       (pop list))
968     (unless result
969       ;; No machine name matches, so we look for default entries.
970       (while rest
971         (when (assoc "default" (car rest))
972           (push (car rest) result))
973         (pop rest)))
974     (when result
975       (setq result (nreverse result))
976       (while (and result
977                   (not (equal (or port defaultport "nntp")
978                               (or (gnus-netrc-get (car result) "port")
979                                   defaultport "nntp"))))
980         (pop result))
981       (car result))))
982
983 (defun gnus-netrc-get (alist type)
984   "Return the value of token TYPE from ALIST."
985   (cdr (assoc type alist)))
986
987 ;;; Various
988
989 (defvar gnus-group-buffer)              ; Compiler directive
990 (defun gnus-alive-p ()
991   "Say whether Gnus is running or not."
992   (and (boundp 'gnus-group-buffer)
993        (get-buffer gnus-group-buffer)
994        (save-excursion
995          (set-buffer gnus-group-buffer)
996          (eq major-mode 'gnus-group-mode))))
997
998 (defun gnus-remove-duplicates (list)
999   (let (new (tail list))
1000     (while tail
1001       (or (member (car tail) new)
1002           (setq new (cons (car tail) new)))
1003       (setq tail (cdr tail)))
1004     (nreverse new)))
1005
1006 (defun gnus-delete-if (predicate list)
1007   "Delete elements from LIST that satisfy PREDICATE."
1008   (let (out)
1009     (while list
1010       (unless (funcall predicate (car list))
1011         (push (car list) out))
1012       (pop list))
1013     (nreverse out)))
1014
1015 (if (fboundp 'assq-delete-all)
1016     (defalias 'gnus-delete-alist 'assq-delete-all)
1017   (defun gnus-delete-alist (key alist)
1018     "Delete from ALIST all elements whose car is KEY.
1019 Return the modified alist."
1020     (let (entry)
1021       (while (setq entry (assq key alist))
1022         (setq alist (delq entry alist)))
1023       alist)))
1024
1025 (defmacro gnus-pull (key alist &optional assoc-p)
1026   "Modify ALIST to be without KEY."
1027   (unless (symbolp alist)
1028     (error "Not a symbol: %s" alist))
1029   (let ((fun (if assoc-p 'assoc 'assq)))
1030     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1031
1032 (defun gnus-globalify-regexp (re)
1033   "Returns a regexp that matches a whole line, iff RE matches a part of it."
1034   (concat (unless (string-match "^\\^" re) "^.*")
1035           re
1036           (unless (string-match "\\$$" re) ".*$")))
1037
1038 (defun gnus-set-window-start (&optional point)
1039   "Set the window start to POINT, or (point) if nil."
1040   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1041     (when win
1042       (set-window-start win (or point (point))))))
1043
1044 (defun gnus-annotation-in-region-p (b e)
1045   (if (= b e)
1046       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1047     (text-property-any b e 'gnus-undeletable t)))
1048
1049 (defun gnus-or (&rest elems)
1050   "Return non-nil if any of the elements are non-nil."
1051   (catch 'found
1052     (while elems
1053       (when (pop elems)
1054         (throw 'found t)))))
1055
1056 (defun gnus-and (&rest elems)
1057   "Return non-nil if all of the elements are non-nil."
1058   (catch 'found
1059     (while elems
1060       (unless (pop elems)
1061         (throw 'found nil)))
1062     t))
1063
1064 (defun gnus-write-active-file (file hashtb &optional full-names)
1065   (let ((coding-system-for-write nnmail-active-file-coding-system))
1066     (with-temp-file file
1067       (mapatoms
1068        (lambda (sym)
1069          (when (and sym
1070                     (boundp sym)
1071                     (symbol-value sym))
1072            (insert (format "%S %d %d y\n"
1073                            (if full-names
1074                                sym
1075                              (intern (gnus-group-real-name (symbol-name sym))))
1076                            (or (cdr (symbol-value sym))
1077                                (car (symbol-value sym)))
1078                            (car (symbol-value sym))))))
1079        hashtb)
1080       (goto-char (point-max))
1081       (while (search-backward "\\." nil t)
1082         (delete-char 1)))))
1083
1084 (if (fboundp 'union)
1085     (defalias 'gnus-union 'union)
1086   (defun gnus-union (l1 l2)
1087     "Set union of lists L1 and L2."
1088     (cond ((null l1) l2)
1089           ((null l2) l1)
1090           ((equal l1 l2) l1)
1091           (t
1092            (or (>= (length l1) (length l2))
1093                (setq l1 (prog1 l2 (setq l2 l1))))
1094            (while l2
1095              (or (member (car l2) l1)
1096                  (push (car l2) l1))
1097              (pop l2))
1098            l1))))
1099
1100 (defun gnus-add-text-properties-when
1101   (property value start end properties &optional object)
1102   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1103   (let (point)
1104     (while (and start
1105                 (< start end) ;; XEmacs will loop for every when start=end.
1106                 (setq point (text-property-not-all start end property value)))
1107       (gnus-add-text-properties start point properties object)
1108       (setq start (text-property-any point end property value)))
1109     (if start
1110         (gnus-add-text-properties start end properties object))))
1111
1112 (defun gnus-remove-text-properties-when
1113   (property value start end properties &optional object)
1114   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1115   (let (point)
1116     (while (and start
1117                 (< start end)
1118                 (setq point (text-property-not-all start end property value)))
1119       (remove-text-properties start point properties object)
1120       (setq start (text-property-any point end property value)))
1121     (if start
1122         (remove-text-properties start end properties object))
1123     t))
1124
1125 (defun gnus-string-equal (x y)
1126   "Like `string-equal', except it compares case-insensitively."
1127   (and (= (length x) (length y))
1128        (or (string-equal x y)
1129            (string-equal (downcase x) (downcase y)))))
1130
1131 (defcustom gnus-use-byte-compile t
1132   "If non-nil, byte-compile crucial run-time codes."
1133   :type 'boolean
1134   :version "21.1"
1135   :group 'gnus-various)
1136
1137 (defun gnus-byte-compile (form)
1138   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1139   (if gnus-use-byte-compile
1140       (progn
1141         (require 'bytecomp)
1142         (defalias 'gnus-byte-compile 'byte-compile)
1143         (byte-compile form))
1144     form))
1145
1146 (defun gnus-remassoc (key alist)
1147   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1148 The modified LIST is returned.  If the first member
1149 of LIST has a car that is `equal' to KEY, there is no way to remove it
1150 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1151 sure of changing the value of `foo'."
1152   (when alist
1153     (if (equal key (caar alist))
1154         (cdr alist)
1155       (setcdr alist (gnus-remassoc key (cdr alist)))
1156       alist)))
1157
1158 (defun gnus-update-alist-soft (key value alist)
1159   (if value
1160       (cons (cons key value) (gnus-remassoc key alist))
1161     (gnus-remassoc key alist)))
1162
1163 (defun gnus-create-info-command (node)
1164   "Create a command that will go to info NODE."
1165   `(lambda ()
1166      (interactive)
1167      ,(concat "Enter the info system at node " node)
1168      (Info-goto-node ,node)
1169      (setq gnus-info-buffer (current-buffer))
1170      (gnus-configure-windows 'info)))
1171
1172 (defun gnus-not-ignore (&rest args)
1173   t)
1174
1175 (defvar gnus-directory-sep-char-regexp "/"
1176   "The regexp of directory separator character.
1177 If you find some problem with the directory separator character, try
1178 \"[/\\\\\]\" for some systems.")
1179
1180 (defun gnus-url-unhex (x)
1181   (if (> x ?9)
1182       (if (>= x ?a)
1183           (+ 10 (- x ?a))
1184         (+ 10 (- x ?A)))
1185     (- x ?0)))
1186
1187 (defun gnus-url-unhex-string (str &optional allow-newlines)
1188   "Remove %XXX embedded spaces, etc in a url.
1189 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1190 decoding of carriage returns and line feeds in the string, which is normally
1191 forbidden in URL encoding."
1192   (setq str (or (mm-subst-char-in-string ?+ ?  str) ""))
1193   (let ((tmp "")
1194         (case-fold-search t))
1195     (while (string-match "%[0-9a-f][0-9a-f]" str)
1196       (let* ((start (match-beginning 0))
1197              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1198              (code (+ (* 16 ch1)
1199                       (gnus-url-unhex (elt str (+ start 2))))))
1200         (setq tmp (concat
1201                    tmp (substring str 0 start)
1202                    (cond
1203                     (allow-newlines
1204                      (char-to-string code))
1205                     ((or (= code ?\n) (= code ?\r))
1206                      " ")
1207                     (t (char-to-string code))))
1208               str (substring str (match-end 0)))))
1209     (setq tmp (concat tmp str))
1210     tmp))
1211
1212 (defun gnus-make-predicate (spec)
1213   "Transform SPEC into a function that can be called.
1214 SPEC is a predicate specifier that contains stuff like `or', `and',
1215 `not', lists and functions.  The functions all take one parameter."
1216   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1217   
1218 (defun gnus-make-predicate-1 (spec)
1219   (cond
1220    ((symbolp spec)
1221     `(,spec elem))
1222    ((listp spec)
1223     (if (memq (car spec) '(or and not))
1224         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1225       (error "Invalid predicate specifier: %s" spec)))))
1226
1227 (defun gnus-local-map-property (map)
1228   "Return a list suitable for a text property list specifying keymap MAP."
1229   (cond
1230    ((featurep 'xemacs)
1231     (list 'keymap map))
1232    ((>= emacs-major-version 21)
1233     (list 'keymap map))
1234    (t
1235     (list 'local-map map))))
1236
1237 (provide 'gnus-util)
1238
1239 ;;; gnus-util.el ends here