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