file new.xpm was added on branch t-gnus-6_17 on 2006-04-11 22:59:16 +0000
[elisp/gnus.git-] / lisp / gnus-cache.el
1 ;;; gnus-cache.el --- cache interface for Gnus
2 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3 ;; 2004, 2005 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;;         MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; Keywords: news
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl))
32
33 (require 'gnus)
34 (eval-when-compile
35   (unless (fboundp 'gnus-agent-load-alist)
36       (defun gnus-agent-load-alist (group)))
37   (require 'gnus-sum))
38
39 (defcustom gnus-cache-active-file
40   (expand-file-name "active" gnus-cache-directory)
41   "*The cache active file."
42   :group 'gnus-cache
43   :type 'file)
44
45 (defcustom gnus-cache-enter-articles '(ticked dormant)
46   "Classes of articles to enter into the cache."
47   :group 'gnus-cache
48   :type '(set (const ticked) (const dormant) (const unread) (const read)))
49
50 (defcustom gnus-cache-remove-articles '(read)
51   "Classes of articles to remove from the cache."
52   :group 'gnus-cache
53   :type '(set (const ticked) (const dormant) (const unread) (const read)))
54
55 (defcustom gnus-cacheable-groups nil
56   "*Groups that match this regexp will be cached.
57
58 If you only want to cache your nntp groups, you could set this
59 variable to \"^nntp\".
60
61 If a group matches both gnus-cacheable-groups and gnus-uncacheable-groups
62 it's not cached."
63   :group 'gnus-cache
64   :type '(choice (const :tag "off" nil)
65                  regexp))
66
67 (defcustom gnus-uncacheable-groups nil
68   "*Groups that match this regexp will not be cached.
69
70 If you want to avoid caching your nnml groups, you could set this
71 variable to \"^nnml\".
72
73 If a group matches both gnus-cacheable-groups and gnus-uncacheable-groups
74 it's not cached."
75   :group 'gnus-cache
76   :type '(choice (const :tag "off" nil)
77                  regexp))
78
79 (defvar gnus-cache-overview-coding-system 'raw-text
80   "Coding system used on Gnus cache files.")
81
82 (defvar gnus-cache-coding-system 'raw-text
83   "Coding system used on Gnus cache files.")
84
85 \f
86
87 ;;; Internal variables.
88
89 (defvar gnus-cache-removable-articles nil)
90 (defvar gnus-cache-buffer nil)
91 (defvar gnus-cache-active-hashtb nil)
92 (defvar gnus-cache-active-altered nil)
93 (defvar gnus-cache-total-fetched-hashtb nil)
94 (defvar gnus-cache-write-file-coding-system 'raw-text)
95
96 (eval-and-compile
97   (autoload 'nnml-generate-nov-databases-1 "nnml")
98   (autoload 'nnvirtual-find-group-art "nnvirtual"))
99
100 \f
101
102 ;;; Functions called from Gnus.
103
104 (defun gnus-cache-open ()
105   "Initialize the cache."
106   (when (or (file-exists-p gnus-cache-directory)
107             (and gnus-use-cache
108                  (not (eq gnus-use-cache 'passive))))
109     (gnus-cache-read-active)))
110
111 ;; Complexities of byte-compiling make this kludge necessary.  Eeek.
112 (ignore-errors
113   (gnus-add-shutdown 'gnus-cache-close 'gnus))
114
115 (defun gnus-cache-close ()
116   "Shut down the cache."
117   (gnus-cache-write-active)
118   (gnus-cache-save-buffers)
119   (setq gnus-cache-active-hashtb nil))
120
121 (defun gnus-cache-save-buffers ()
122   ;; save the overview buffer if it exists and has been modified
123   ;; delete empty cache subdirectories
124   (when gnus-cache-buffer
125     (let ((buffer (cdr gnus-cache-buffer))
126           (overview-file (gnus-cache-file-name
127                           (car gnus-cache-buffer) ".overview")))
128       ;; write the overview only if it was modified
129       (when (and (buffer-live-p buffer) (buffer-modified-p buffer))
130         (with-current-buffer buffer
131           (if (> (buffer-size) 0)
132               ;; Non-empty overview, write it to a file.
133               (gnus-write-buffer-as-coding-system
134                gnus-cache-overview-coding-system overview-file)
135             ;; Empty overview file, remove it
136             (when (file-exists-p overview-file)
137               (delete-file overview-file))
138             ;; If possible, remove group's cache subdirectory.
139             (condition-case nil
140                 ;; FIXME: we can detect the error type and warn the user
141                 ;; of any inconsistencies (articles w/o nov entries?).
142                 ;; for now, just be conservative...delete only if safe -- sj
143                 (delete-directory (file-name-directory overview-file))
144               (error)))
145
146           (gnus-cache-update-overview-total-fetched-for
147            (car gnus-cache-buffer) overview-file)))
148       ;; Kill the buffer -- it's either unmodified or saved.
149       (gnus-kill-buffer buffer)
150       (setq gnus-cache-buffer nil))))
151
152 (defun gnus-cache-possibly-enter-article
153   (group article headers ticked dormant unread &optional force)
154   (when (and (or force (not (eq gnus-use-cache 'passive)))
155              (numberp article)
156              (> article 0)              ; This might be a dummy article.
157              (vectorp headers))
158     (let ((number article)
159           file lines-chars)
160       ;; If this is a virtual group, we find the real group.
161       (when (gnus-virtual-group-p group)
162         (let ((result (nnvirtual-find-group-art
163                        (gnus-group-real-name group) article)))
164           (setq group (car result)
165                 number (cdr result))))
166       (when (and number
167                  (> number 0)           ; Reffed article.
168                  (or force
169                      (and (gnus-cache-fully-p group)
170                           (gnus-cache-member-of-class
171                            gnus-cache-enter-articles ticked dormant unread)))
172                  (not (file-exists-p (setq file (gnus-cache-file-name
173                                                  group number)))))
174         ;; Possibly create the cache directory.
175         (gnus-make-directory (file-name-directory file))
176         ;; Save the article in the cache.
177         (if (file-exists-p file)
178             t                           ; The article already is saved.
179           (save-excursion
180             (set-buffer nntp-server-buffer)
181             (require 'gnus-art)
182             (let ((gnus-use-cache nil)
183                   (gnus-article-decode-hook nil))
184               (gnus-request-article-this-buffer number group))
185             (when (> (buffer-size) 0)
186               (gnus-write-buffer-as-coding-system
187                gnus-cache-write-file-coding-system file)
188               (gnus-cache-update-file-total-fetched-for group file)
189               (setq lines-chars (nnheader-get-lines-and-char))
190               (nnheader-remove-body)
191               (setq headers (nnheader-parse-naked-head))
192               (mail-header-set-number headers number)
193               (mail-header-set-lines headers (car lines-chars))
194               (mail-header-set-chars headers (cadr lines-chars))
195               (gnus-cache-change-buffer group)
196               (set-buffer (cdr gnus-cache-buffer))
197               (goto-char (point-max))
198               (forward-line -1)
199               (while (condition-case ()
200                          (when (not (bobp))
201                            (> (read (current-buffer)) number))
202                        (error
203                         ;; The line was malformed, so we just remove it!!
204                         (gnus-delete-line)
205                         t))
206                 (forward-line -1))
207               (if (bobp)
208                   (if (not (eobp))
209                       (progn
210                         (beginning-of-line)
211                         (when (< (read (current-buffer)) number)
212                           (forward-line 1)))
213                     (beginning-of-line))
214                 (forward-line 1))
215               (beginning-of-line)
216               (nnheader-insert-nov headers)
217               ;; Update the active info.
218               (set-buffer gnus-summary-buffer)
219               (gnus-cache-possibly-update-active group (cons number number))
220               (setq gnus-newsgroup-cached
221                     (gnus-add-to-sorted-list gnus-newsgroup-cached article))
222               (gnus-summary-update-secondary-mark article))
223             t))))))
224
225 (defun gnus-cache-enter-remove-article (article)
226   "Mark ARTICLE for later possible removal."
227   (when article
228     (push article gnus-cache-removable-articles)))
229
230 (defun gnus-cache-possibly-remove-articles ()
231   "Possibly remove some of the removable articles."
232   (if (not (gnus-virtual-group-p gnus-newsgroup-name))
233       (gnus-cache-possibly-remove-articles-1)
234     (let ((arts gnus-cache-removable-articles)
235           ga)
236       (while arts
237         (when (setq ga (nnvirtual-find-group-art
238                         (gnus-group-real-name gnus-newsgroup-name) (pop arts)))
239           (let ((gnus-cache-removable-articles (list (cdr ga)))
240                 (gnus-newsgroup-name (car ga)))
241             (gnus-cache-possibly-remove-articles-1)))))
242     (setq gnus-cache-removable-articles nil)))
243
244 (defun gnus-cache-possibly-remove-articles-1 ()
245   "Possibly remove some of the removable articles."
246   (when (gnus-cache-fully-p gnus-newsgroup-name)
247     (let ((cache-articles gnus-newsgroup-cached))
248       (gnus-cache-change-buffer gnus-newsgroup-name)
249       (dolist (article gnus-cache-removable-articles)
250         (when (memq article cache-articles)
251           ;; The article was in the cache, so we see whether we are
252           ;; supposed to remove it from the cache.
253           (gnus-cache-possibly-remove-article
254            article (memq article gnus-newsgroup-marked)
255            (memq article gnus-newsgroup-dormant)
256            (or (memq article gnus-newsgroup-unreads)
257                (memq article gnus-newsgroup-unselected))))))
258     ;; The overview file might have been modified, save it
259     ;; safe because we're only called at group exit anyway.
260     (gnus-cache-save-buffers)))
261
262 (defun gnus-cache-request-article (article group)
263   "Retrieve ARTICLE in GROUP from the cache."
264   (let ((file (gnus-cache-file-name group article))
265         (buffer-read-only nil))
266     (when (file-exists-p file)
267       (erase-buffer)
268       (gnus-kill-all-overlays)
269       (let ((nnheader-file-coding-system gnus-cache-coding-system))
270         (nnheader-insert-file-contents file))
271       t)))
272
273 (defun gnus-cache-possibly-alter-active (group active)
274   "Alter the ACTIVE info for GROUP to reflect the articles in the cache."
275   (when gnus-cache-active-hashtb
276     (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
277       (when cache-active
278         (when (< (car cache-active) (car active))
279           (setcar active (car cache-active)))
280         (when (> (cdr cache-active) (cdr active))
281           (setcdr active (cdr cache-active)))))))
282
283 (defun gnus-cache-retrieve-headers (articles group &optional fetch-old)
284   "Retrieve the headers for ARTICLES in GROUP."
285   (let ((cached
286          (setq gnus-newsgroup-cached (gnus-cache-articles-in-group group))))
287     (if (not cached)
288         ;; No cached articles here, so we just retrieve them
289         ;; the normal way.
290         (let ((gnus-use-cache nil))
291           (gnus-retrieve-headers articles group fetch-old))
292       (let ((uncached-articles (gnus-sorted-difference articles cached))
293             (cache-file (gnus-cache-file-name group ".overview"))
294             type)
295         ;; We first retrieve all the headers that we don't have in
296         ;; the cache.
297         (let ((gnus-use-cache nil))
298           (when uncached-articles
299             (setq type (and articles
300                             (gnus-retrieve-headers
301                              uncached-articles group fetch-old)))))
302         (gnus-cache-save-buffers)
303         ;; Then we insert the cached headers.
304         (save-excursion
305           (cond
306            ((not (file-exists-p cache-file))
307             ;; There are no cached headers.
308             type)
309            ((null type)
310             ;; There were no uncached headers (or retrieval was
311             ;; unsuccessful), so we use the cached headers exclusively.
312             (set-buffer nntp-server-buffer)
313             (erase-buffer)
314             (let ((nnheader-file-coding-system
315                    gnus-cache-overview-coding-system))
316               (nnheader-insert-file-contents cache-file))
317             'nov)
318            ((eq type 'nov)
319             ;; We have both cached and uncached NOV headers, so we
320             ;; braid them.
321             (gnus-cache-braid-nov group cached)
322             type)
323            (t
324             ;; We braid HEADs.
325             (gnus-cache-braid-heads group (gnus-sorted-intersection
326                                            cached articles))
327             type)))))))
328
329 (defun gnus-cache-enter-article (&optional n)
330   "Enter the next N articles into the cache.
331 If not given a prefix, use the process marked articles instead.
332 Returns the list of articles entered."
333   (interactive "P")
334   (let (out)
335     (dolist (article (gnus-summary-work-articles n))
336       (gnus-summary-remove-process-mark article)
337       (if (natnump article)
338           (when (gnus-cache-possibly-enter-article
339                  gnus-newsgroup-name article
340                  (gnus-summary-article-header article)
341                  nil nil nil t)
342             (setq gnus-newsgroup-undownloaded (delq article gnus-newsgroup-undownloaded))
343             (push article out))
344         (gnus-message 2 "Can't cache article %d" article))
345       (gnus-summary-update-download-mark article)
346       (gnus-summary-update-secondary-mark article))
347     (gnus-summary-next-subject 1)
348     (gnus-summary-position-point)
349     (nreverse out)))
350
351 (defun gnus-cache-remove-article (&optional n)
352   "Remove the next N articles from the cache.
353 If not given a prefix, use the process marked articles instead.
354 Returns the list of articles removed."
355   (interactive "P")
356   (gnus-cache-change-buffer gnus-newsgroup-name)
357   (let (out)
358     (dolist (article (gnus-summary-work-articles n))
359       (gnus-summary-remove-process-mark article)
360       (when (gnus-cache-possibly-remove-article article nil nil nil t)
361         (when gnus-newsgroup-agentized
362           (let ((alist (gnus-agent-load-alist gnus-newsgroup-name)))
363             (unless (cdr (assoc article alist))
364               (setq gnus-newsgroup-undownloaded
365                     (gnus-add-to-sorted-list 
366                      gnus-newsgroup-undownloaded article)))))
367         (push article out))
368       (gnus-summary-update-download-mark article)
369       (gnus-summary-update-secondary-mark article))
370     (gnus-summary-next-subject 1)
371     (gnus-summary-position-point)
372     (nreverse out)))
373
374 (defun gnus-cached-article-p (article)
375   "Say whether ARTICLE is cached in the current group."
376   (memq article gnus-newsgroup-cached))
377
378 (defun gnus-summary-insert-cached-articles ()
379   "Insert all the articles cached for this group into the current buffer."
380   (interactive)
381   (let ((gnus-verbose (max 6 gnus-verbose)))
382     (if (not gnus-newsgroup-cached)
383         (gnus-message 3 "No cached articles for this group")
384       (gnus-summary-goto-subjects gnus-newsgroup-cached))))
385
386 (defun gnus-summary-limit-include-cached ()
387   "Limit the summary buffer to articles that are cached."
388   (interactive)
389   (let ((gnus-verbose (max 6 gnus-verbose)))
390     (if gnus-newsgroup-cached
391         (progn
392           (gnus-summary-limit gnus-newsgroup-cached)
393           (gnus-summary-position-point))
394       (gnus-message 3 "No cached articles for this group"))))
395
396 ;;; Internal functions.
397
398 (defun gnus-cache-change-buffer (group)
399   (and gnus-cache-buffer
400        ;; See if the current group's overview cache has been loaded.
401        (or (string= group (car gnus-cache-buffer))
402            ;; Another overview cache is current, save it.
403            (gnus-cache-save-buffers)))
404   ;; if gnus-cache buffer is nil, create it
405   (unless gnus-cache-buffer
406     ;; Create cache buffer
407     (save-excursion
408       (setq gnus-cache-buffer
409             (cons group
410                   (set-buffer (gnus-get-buffer-create
411                                " *gnus-cache-overview*"))))
412       ;; Insert the contents of this group's cache overview.
413       (erase-buffer)
414       (let ((file (gnus-cache-file-name group ".overview")))
415         (when (file-exists-p file)
416           (nnheader-insert-file-contents file)))
417       ;; We have a fresh (empty/just loaded) buffer,
418       ;; mark it as unmodified to save a redundant write later.
419       (set-buffer-modified-p nil))))
420
421 ;; Return whether an article is a member of a class.
422 (defun gnus-cache-member-of-class (class ticked dormant unread)
423   (or (and ticked (memq 'ticked class))
424       (and dormant (memq 'dormant class))
425       (and unread (memq 'unread class))
426       (and (not unread) (not ticked) (not dormant) (memq 'read class))))
427
428 (defun gnus-cache-file-name (group article)
429   (setq group (gnus-group-decoded-name group))
430   (expand-file-name
431    (if (stringp article) article (int-to-string article))
432    (file-name-as-directory
433     (expand-file-name
434      (nnheader-translate-file-chars
435       (if (gnus-use-long-file-name 'not-cache)
436           group
437         (let ((group (nnheader-replace-duplicate-chars-in-string
438                       (nnheader-replace-chars-in-string group ?/ ?_)
439                       ?. ?_)))
440           ;; Translate the first colon into a slash.
441           (when (string-match ":" group)
442             (setq group (concat (substring group 0 (match-beginning 0))
443                                 "/" (substring group (match-end 0)))))
444           (nnheader-replace-chars-in-string group ?. ?/)))
445       t)
446      gnus-cache-directory))))
447
448 (defun gnus-cache-update-article (group article)
449   "If ARTICLE is in the cache, remove it and re-enter it."
450   (gnus-cache-change-buffer group)
451   (when (gnus-cache-possibly-remove-article article nil nil nil t)
452     (let ((gnus-use-cache nil))
453       (gnus-cache-possibly-enter-article
454        gnus-newsgroup-name article (gnus-summary-article-header article)
455        nil nil nil t))))
456
457 (defun gnus-cache-possibly-remove-article (article ticked dormant unread
458                                                    &optional force)
459   "Possibly remove ARTICLE from the cache."
460   (let ((group gnus-newsgroup-name)
461         (number article)
462         file)
463     ;; If this is a virtual group, we find the real group.
464     (when (gnus-virtual-group-p group)
465       (let ((result (nnvirtual-find-group-art
466                      (gnus-group-real-name group) article)))
467         (setq group (car result)
468               number (cdr result))))
469     (setq file (gnus-cache-file-name group number))
470     (when (and (file-exists-p file)
471                (or force
472                    (gnus-cache-member-of-class
473                     gnus-cache-remove-articles ticked dormant unread)))
474       (save-excursion
475         (gnus-cache-update-file-total-fetched-for group file t)
476         (delete-file file)
477
478         (set-buffer (cdr gnus-cache-buffer))
479         (goto-char (point-min))
480         (when (or (looking-at (concat (int-to-string number) "\t"))
481                   (search-forward (concat "\n" (int-to-string number) "\t")
482                                   (point-max) t))
483             (gnus-delete-line)))
484       (unless (setq gnus-newsgroup-cached
485                     (delq article gnus-newsgroup-cached))
486         (gnus-sethash gnus-newsgroup-name nil gnus-cache-active-hashtb)
487         (setq gnus-cache-active-altered t))
488       (gnus-summary-update-secondary-mark article)
489       t)))
490
491 (defun gnus-cache-articles-in-group (group)
492   "Return a sorted list of cached articles in GROUP."
493   (let ((dir (file-name-directory (gnus-cache-file-name group 1)))
494         articles)
495     (when (file-exists-p dir)
496       (setq articles
497             (sort (mapcar (lambda (name) (string-to-int name))
498                           (directory-files dir nil "^[0-9]+$" t))
499                   '<))
500       ;; Update the cache active file, just to synch more.
501       (if articles
502           (progn
503             (gnus-cache-update-active group (car articles) t)
504             (gnus-cache-update-active group (car (last articles))))
505         (when (gnus-gethash group gnus-cache-active-hashtb)
506           (gnus-sethash group nil gnus-cache-active-hashtb)
507           (setq gnus-cache-active-altered t)))
508       articles)))
509
510 (defun gnus-cache-braid-nov (group cached &optional file)
511   (let ((cache-buf (gnus-get-buffer-create " *gnus-cache*"))
512         beg end)
513     (gnus-cache-save-buffers)
514     (save-excursion
515       (set-buffer cache-buf)
516       (erase-buffer)
517       (let ((nnheader-file-coding-system gnus-cache-overview-coding-system))
518         (nnheader-insert-file-contents
519          (or file (gnus-cache-file-name group ".overview"))))
520       (goto-char (point-min))
521       (insert "\n")
522       (goto-char (point-min)))
523     (set-buffer nntp-server-buffer)
524     (goto-char (point-min))
525     (while cached
526       (while (and (not (eobp))
527                   (< (read (current-buffer)) (car cached)))
528         (forward-line 1))
529       (beginning-of-line)
530       (set-buffer cache-buf)
531       (if (search-forward (concat "\n" (int-to-string (car cached)) "\t")
532                           nil t)
533           (setq beg (point-at-bol)
534                 end (progn (end-of-line) (point)))
535         (setq beg nil))
536       (set-buffer nntp-server-buffer)
537       (when beg
538         (insert-buffer-substring cache-buf beg end)
539         (insert "\n"))
540       (setq cached (cdr cached)))
541     (kill-buffer cache-buf)))
542
543 (defun gnus-cache-braid-heads (group cached)
544   (let ((cache-buf (gnus-get-buffer-create " *gnus-cache*")))
545     (with-current-buffer cache-buf
546       (erase-buffer))
547     (set-buffer nntp-server-buffer)
548     (goto-char (point-min))
549     (dolist (entry cached)
550       (while (and (not (eobp))
551                   (looking-at "2.. +\\([0-9]+\\) ")
552                   (< (progn (goto-char (match-beginning 1))
553                             (read (current-buffer)))
554                      entry))
555         (search-forward "\n.\n" nil 'move))
556       (beginning-of-line)
557       (set-buffer cache-buf)
558       (erase-buffer)
559       (let ((nnheader-file-coding-system gnus-cache-coding-system))
560         (nnheader-insert-file-contents (gnus-cache-file-name group entry)))
561       (goto-char (point-min))
562       (insert "220 ")
563       (princ (car cached) (current-buffer))
564       (insert " Article retrieved.\n")
565       (search-forward "\n\n" nil 'move)
566       (delete-region (point) (point-max))
567       (forward-char -1)
568       (insert ".")
569       (set-buffer nntp-server-buffer)
570       (insert-buffer-substring cache-buf))
571     (kill-buffer cache-buf)))
572
573 ;;;###autoload
574 (defun gnus-jog-cache ()
575   "Go through all groups and put the articles into the cache.
576
577 Usage:
578 $ emacs -batch -l ~/.emacs -l gnus -f gnus-jog-cache"
579   (interactive)
580   (let ((gnus-mark-article-hook nil)
581         (gnus-expert-user t)
582         (nnmail-spool-file nil)
583         (mail-sources nil)
584         (gnus-use-dribble-file nil)
585         (gnus-novice-user nil)
586         (gnus-large-newsgroup nil))
587     ;; Start Gnus.
588     (gnus)
589     ;; Go through all groups...
590     (gnus-group-mark-buffer)
591     (gnus-group-iterate nil
592       (lambda (group)
593         (let (gnus-auto-select-next)
594           (gnus-summary-read-group group nil t)
595           ;; ... and enter the articles into the cache.
596           (when (eq major-mode 'gnus-summary-mode)
597             (gnus-uu-mark-buffer)
598             (gnus-cache-enter-article)
599             (kill-buffer (current-buffer))))))))
600
601 (defun gnus-cache-read-active (&optional force)
602   "Read the cache active file."
603   (gnus-make-directory gnus-cache-directory)
604   (if (or (not (file-exists-p gnus-cache-active-file))
605           (zerop (nth 7 (file-attributes gnus-cache-active-file)))
606           force)
607       ;; There is no active file, so we generate one.
608       (gnus-cache-generate-active)
609     ;; We simply read the active file.
610     (save-excursion
611       (gnus-set-work-buffer)
612       (nnheader-insert-file-contents gnus-cache-active-file)
613       (gnus-active-to-gnus-format
614        nil (setq gnus-cache-active-hashtb
615                  (gnus-make-hashtable
616                   (count-lines (point-min) (point-max)))))
617       (setq gnus-cache-active-altered nil))))
618
619 (defun gnus-cache-write-active (&optional force)
620   "Write the active hashtb to the active file."
621   (when (or force
622             (and gnus-cache-active-hashtb
623                  gnus-cache-active-altered))
624     (gnus-write-active-file gnus-cache-active-file gnus-cache-active-hashtb t)
625     ;; Mark the active hashtb as unaltered.
626     (setq gnus-cache-active-altered nil)))
627
628 (defun gnus-cache-possibly-update-active (group active)
629   "Update active info bounds of GROUP with ACTIVE if necessary.
630 The update is performed if ACTIVE contains a higher or lower bound
631 than the current."
632   (let ((lower t) (higher t))
633     (if gnus-cache-active-hashtb
634         (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
635           (when cache-active
636             (unless (< (car active) (car cache-active))
637               (setq lower nil))
638             (unless (> (cdr active) (cdr cache-active))
639               (setq higher nil))))
640       (gnus-cache-read-active))
641     (when lower
642       (gnus-cache-update-active group (car active) t))
643     (when higher
644       (gnus-cache-update-active group (cdr active)))))
645
646 (defun gnus-cache-update-active (group number &optional low)
647   "Update the upper bound of the active info of GROUP to NUMBER.
648 If LOW, update the lower bound instead."
649   (let ((active (gnus-gethash group gnus-cache-active-hashtb)))
650     (if (null active)
651         ;; We just create a new active entry for this group.
652         (gnus-sethash group (cons number number) gnus-cache-active-hashtb)
653       ;; Update the lower or upper bound.
654       (if low
655           (setcar active number)
656         (setcdr active number)))
657     ;; Mark the active hashtb as altered.
658     (setq gnus-cache-active-altered t)))
659
660 ;;;###autoload
661 (defun gnus-cache-generate-active (&optional directory)
662   "Generate the cache active file."
663   (interactive)
664   (let* ((top (null directory))
665          (directory (expand-file-name (or directory gnus-cache-directory)))
666          (files (directory-files directory 'full))
667          (group
668           (if top
669               ""
670             (string-match
671              (concat "^" (regexp-quote
672                           (file-name-as-directory
673                            (expand-file-name gnus-cache-directory))))
674              (directory-file-name directory))
675             (nnheader-replace-chars-in-string
676              (substring (directory-file-name directory) (match-end 0))
677              ?/ ?.)))
678          nums alphs)
679     (when top
680       (gnus-message 5 "Generating the cache active file...")
681       (setq gnus-cache-active-hashtb (gnus-make-hashtable 123)))
682     (when (string-match "^\\(nn[^_]+\\)_" group)
683       (setq group (replace-match "\\1:" t nil group)))
684     ;; Separate articles from all other files and directories.
685     (while files
686       (if (string-match "^[0-9]+$" (file-name-nondirectory (car files)))
687           (push (string-to-int (file-name-nondirectory (pop files))) nums)
688         (push (pop files) alphs)))
689     ;; If we have nums, then this is probably a valid group.
690     (when (setq nums (sort nums '<))
691       (gnus-sethash group (cons (car nums) (gnus-last-element nums))
692                     gnus-cache-active-hashtb))
693     ;; Go through all the other files.
694     (dolist (file alphs)
695       (when (and (file-directory-p file)
696                  (not (string-match "^\\."
697                                     (file-name-nondirectory file))))
698         ;; We descend directories.
699         (gnus-cache-generate-active file)))
700     ;; Write the new active file.
701     (when top
702       (gnus-cache-write-active t)
703       (gnus-message 5 "Generating the cache active file...done"))))
704
705 ;;;###autoload
706 (defun gnus-cache-generate-nov-databases (dir)
707   "Generate NOV files recursively starting in DIR."
708   (interactive (list gnus-cache-directory))
709   (gnus-cache-close)
710   (let ((nnml-generate-active-function 'identity))
711     (nnml-generate-nov-databases-1 dir))
712
713   (setq gnus-cache-total-fetched-hashtb nil)
714
715   (gnus-cache-open))
716
717 (defun gnus-cache-move-cache (dir)
718   "Move the cache tree to somewhere else."
719   (interactive "FMove the cache tree to: ")
720   (rename-file gnus-cache-directory dir))
721
722 (defun gnus-cache-fully-p (&optional group)
723   "Returns non-nil if the cache should be fully used.
724 If GROUP is non-nil, also cater to `gnus-cacheable-groups' and
725 `gnus-uncacheable-groups'."
726   (and gnus-use-cache
727        (not (eq gnus-use-cache 'passive))
728        (if (null group)
729            t
730          (and (or (not gnus-cacheable-groups)
731                   (string-match gnus-cacheable-groups group))
732               (or (not gnus-uncacheable-groups)
733                   (not (string-match gnus-uncacheable-groups group)))))))
734
735 ;;;###autoload
736 (defun gnus-cache-rename-group (old-group new-group)
737   "Rename OLD-GROUP as NEW-GROUP.  Always updates the cache, even when
738 disabled, as the old cache files would corrupt gnus when the cache was
739 next enabled. Depends upon the caller to determine whether group renaming is supported."
740   (let ((old-dir (gnus-cache-file-name old-group ""))
741         (new-dir (gnus-cache-file-name new-group "")))
742     (gnus-rename-file old-dir new-dir t))
743
744   (gnus-cache-rename-group-total-fetched-for old-group new-group)
745
746   (let ((no-save gnus-cache-active-hashtb))
747     (unless gnus-cache-active-hashtb
748       (gnus-cache-read-active))
749     (let* ((old-group-hash-value (gnus-gethash old-group gnus-cache-active-hashtb))
750            (new-group-hash-value (gnus-gethash new-group gnus-cache-active-hashtb))
751            (delta                (or old-group-hash-value new-group-hash-value)))
752       (gnus-sethash new-group old-group-hash-value gnus-cache-active-hashtb)
753       (gnus-sethash old-group nil gnus-cache-active-hashtb)
754
755       (if no-save
756           (setq gnus-cache-active-altered delta)
757         (gnus-cache-write-active delta)))))
758
759 ;;;###autoload
760 (defun gnus-cache-delete-group (group)
761   "Delete GROUP.  Always updates the cache, even when
762 disabled, as the old cache files would corrupt gnus when the cache was
763 next enabled. Depends upon the caller to determine whether group deletion is supported."
764   (let ((dir (gnus-cache-file-name group "")))
765     (gnus-delete-directory dir))
766
767   (gnus-cache-delete-group-total-fetched-for group)
768
769   (let ((no-save gnus-cache-active-hashtb))
770     (unless gnus-cache-active-hashtb
771       (gnus-cache-read-active))
772     (let* ((group-hash-value (gnus-gethash group gnus-cache-active-hashtb)))
773       (gnus-sethash group nil gnus-cache-active-hashtb)
774
775       (if no-save
776           (setq gnus-cache-active-altered group-hash-value)
777         (gnus-cache-write-active group-hash-value)))))
778
779 (defvar gnus-cache-inhibit-update-total-fetched-for nil)
780 (defvar gnus-cache-need-update-total-fetched-for nil)
781
782 (defmacro gnus-cache-with-refreshed-group (group &rest body)
783   `(prog1 (let ((gnus-cache-inhibit-update-total-fetched-for t))
784             ,@body)
785      (when (and gnus-cache-need-update-total-fetched-for
786                 (not gnus-cache-inhibit-update-total-fetched-for))
787         (save-excursion
788           (set-buffer gnus-group-buffer)
789           (setq gnus-cache-need-update-total-fetched-for nil)
790           (gnus-group-update-group ,group t)))))
791
792 (defun gnus-cache-update-file-total-fetched-for (group file &optional subtract)
793   (when gnus-cache-total-fetched-hashtb
794     (gnus-cache-with-refreshed-group
795      group
796      (let* ((entry (or (gnus-gethash group gnus-cache-total-fetched-hashtb)
797                        (gnus-sethash group (make-vector 2 0)
798                                      gnus-cache-total-fetched-hashtb)))
799             size)
800
801        (if file
802            (setq size (or (nth 7 (file-attributes file)) 0))
803          (let ((files (directory-files (gnus-cache-file-name group "") 
804                                        t nil t))
805                file attrs)
806            (setq size 0.0)
807            (while (setq file (pop files))
808              (setq attrs (file-attributes file))
809              (unless (nth 0 attrs)
810                (incf size (float (nth 7 attrs)))))))         
811
812        (setq gnus-cache-need-update-total-fetched-for t)
813
814        (incf (nth 1 entry) (if subtract (- size) size))))))
815
816 (defun gnus-cache-update-overview-total-fetched-for (group file)
817   (when gnus-cache-total-fetched-hashtb
818     (gnus-cache-with-refreshed-group
819      group
820      (let* ((entry (or (gnus-gethash group gnus-cache-total-fetched-hashtb)
821                        (gnus-sethash group (make-list 2 0) 
822                                      gnus-cache-total-fetched-hashtb)))
823             (size (or (nth 7 (file-attributes 
824                               (or file
825                                   (gnus-cache-file-name group ".overview"))))
826                       0)))
827        (setq gnus-cache-need-update-total-fetched-for t)
828        (setf (nth 0 entry) size)))))
829
830 (defun gnus-cache-rename-group-total-fetched-for (old-group new-group)
831   "Record of disk space used by OLD-GROUP now associated with NEW-GROUP."
832   (when gnus-cache-total-fetched-hashtb
833     (let ((entry (gnus-gethash old-group gnus-cache-total-fetched-hashtb)))
834       (gnus-sethash new-group entry gnus-cache-total-fetched-hashtb)
835       (gnus-sethash old-group nil gnus-cache-total-fetched-hashtb))))
836
837 (defun gnus-cache-delete-group-total-fetched-for (group)
838   "Delete record of disk space used by GROUP being deleted."
839   (when gnus-cache-total-fetched-hashtb
840       (gnus-sethash group nil gnus-cache-total-fetched-hashtb)))
841
842 (defun gnus-cache-total-fetched-for (group &optional no-inhibit)
843   "Get total disk space used by the cache for the specified GROUP."
844   (unless gnus-cache-total-fetched-hashtb
845     (setq gnus-cache-total-fetched-hashtb (gnus-make-hashtable 1024)))
846
847   (let* ((entry (gnus-gethash group gnus-cache-total-fetched-hashtb)))
848     (if entry
849         (apply '+ entry)
850       (let ((gnus-cache-inhibit-update-total-fetched-for (not no-inhibit)))
851         (+ 
852          (gnus-cache-update-overview-total-fetched-for group nil)
853          (gnus-cache-update-file-total-fetched-for     group nil))))))
854
855 (provide 'gnus-cache)
856
857 ;;; gnus-cache.el ends here