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