f5a957a58996c17e38996a71007b3da5f6d284a9
[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 ;;        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   (expand-file-name
430    (if (stringp article) article (int-to-string article))
431    (file-name-as-directory
432     (expand-file-name
433      (nnheader-translate-file-chars
434       (if (gnus-use-long-file-name 'not-cache)
435           group
436         (let ((group (nnheader-replace-duplicate-chars-in-string
437                       (nnheader-replace-chars-in-string group ?/ ?_)
438                       ?. ?_)))
439           ;; Translate the first colon into a slash.
440           (when (string-match ":" group)
441             (setq group (concat (substring group 0 (match-beginning 0))
442                                 "/" (substring group (match-end 0)))))
443           (nnheader-replace-chars-in-string group ?. ?/)))
444       t)
445      gnus-cache-directory))))
446
447 (defun gnus-cache-update-article (group article)
448   "If ARTICLE is in the cache, remove it and re-enter it."
449   (gnus-cache-change-buffer group)
450   (when (gnus-cache-possibly-remove-article article nil nil nil t)
451     (let ((gnus-use-cache nil))
452       (gnus-cache-possibly-enter-article
453        gnus-newsgroup-name article (gnus-summary-article-header article)
454        nil nil nil t))))
455
456 (defun gnus-cache-possibly-remove-article (article ticked dormant unread
457                                                    &optional force)
458   "Possibly remove ARTICLE from the cache."
459   (let ((group gnus-newsgroup-name)
460         (number article)
461         file)
462     ;; If this is a virtual group, we find the real group.
463     (when (gnus-virtual-group-p group)
464       (let ((result (nnvirtual-find-group-art
465                      (gnus-group-real-name group) article)))
466         (setq group (car result)
467               number (cdr result))))
468     (setq file (gnus-cache-file-name group number))
469     (when (and (file-exists-p file)
470                (or force
471                    (gnus-cache-member-of-class
472                     gnus-cache-remove-articles ticked dormant unread)))
473       (save-excursion
474         (gnus-cache-update-file-total-fetched-for group file t)
475         (delete-file file)
476
477         (set-buffer (cdr gnus-cache-buffer))
478         (goto-char (point-min))
479         (when (or (looking-at (concat (int-to-string number) "\t"))
480                   (search-forward (concat "\n" (int-to-string number) "\t")
481                                   (point-max) t))
482             (gnus-delete-line)))
483       (unless (setq gnus-newsgroup-cached
484                     (delq article gnus-newsgroup-cached))
485         (gnus-sethash gnus-newsgroup-name nil gnus-cache-active-hashtb)
486         (setq gnus-cache-active-altered t))
487       (gnus-summary-update-secondary-mark article)
488       t)))
489
490 (defun gnus-cache-articles-in-group (group)
491   "Return a sorted list of cached articles in GROUP."
492   (let ((dir (file-name-directory (gnus-cache-file-name group 1)))
493         articles)
494     (when (file-exists-p dir)
495       (setq articles
496             (sort (mapcar (lambda (name) (string-to-int name))
497                           (directory-files dir nil "^[0-9]+$" t))
498                   '<))
499       ;; Update the cache active file, just to synch more.
500       (if articles
501           (progn
502             (gnus-cache-update-active group (car articles) t)
503             (gnus-cache-update-active group (car (last articles))))
504         (when (gnus-gethash group gnus-cache-active-hashtb)
505           (gnus-sethash group nil gnus-cache-active-hashtb)
506           (setq gnus-cache-active-altered t)))
507       articles)))
508
509 (defun gnus-cache-braid-nov (group cached &optional file)
510   (let ((cache-buf (gnus-get-buffer-create " *gnus-cache*"))
511         beg end)
512     (gnus-cache-save-buffers)
513     (save-excursion
514       (set-buffer cache-buf)
515       (erase-buffer)
516       (let ((nnheader-file-coding-system gnus-cache-overview-coding-system))
517         (nnheader-insert-file-contents
518          (or file (gnus-cache-file-name group ".overview"))))
519       (goto-char (point-min))
520       (insert "\n")
521       (goto-char (point-min)))
522     (set-buffer nntp-server-buffer)
523     (goto-char (point-min))
524     (while cached
525       (while (and (not (eobp))
526                   (< (read (current-buffer)) (car cached)))
527         (forward-line 1))
528       (beginning-of-line)
529       (set-buffer cache-buf)
530       (if (search-forward (concat "\n" (int-to-string (car cached)) "\t")
531                           nil t)
532           (setq beg (point-at-bol)
533                 end (progn (end-of-line) (point)))
534         (setq beg nil))
535       (set-buffer nntp-server-buffer)
536       (when beg
537         (insert-buffer-substring cache-buf beg end)
538         (insert "\n"))
539       (setq cached (cdr cached)))
540     (kill-buffer cache-buf)))
541
542 (defun gnus-cache-braid-heads (group cached)
543   (let ((cache-buf (gnus-get-buffer-create " *gnus-cache*")))
544     (with-current-buffer cache-buf
545       (erase-buffer))
546     (set-buffer nntp-server-buffer)
547     (goto-char (point-min))
548     (dolist (entry cached)
549       (while (and (not (eobp))
550                   (looking-at "2.. +\\([0-9]+\\) ")
551                   (< (progn (goto-char (match-beginning 1))
552                             (read (current-buffer)))
553                      entry))
554         (search-forward "\n.\n" nil 'move))
555       (beginning-of-line)
556       (set-buffer cache-buf)
557       (erase-buffer)
558       (let ((nnheader-file-coding-system gnus-cache-coding-system))
559         (nnheader-insert-file-contents (gnus-cache-file-name group entry)))
560       (goto-char (point-min))
561       (insert "220 ")
562       (princ (car cached) (current-buffer))
563       (insert " Article retrieved.\n")
564       (search-forward "\n\n" nil 'move)
565       (delete-region (point) (point-max))
566       (forward-char -1)
567       (insert ".")
568       (set-buffer nntp-server-buffer)
569       (insert-buffer-substring cache-buf))
570     (kill-buffer cache-buf)))
571
572 ;;;###autoload
573 (defun gnus-jog-cache ()
574   "Go through all groups and put the articles into the cache.
575
576 Usage:
577 $ emacs -batch -l ~/.emacs -l gnus -f gnus-jog-cache"
578   (interactive)
579   (let ((gnus-mark-article-hook nil)
580         (gnus-expert-user t)
581         (nnmail-spool-file nil)
582         (mail-sources nil)
583         (gnus-use-dribble-file nil)
584         (gnus-novice-user nil)
585         (gnus-large-newsgroup nil))
586     ;; Start Gnus.
587     (gnus)
588     ;; Go through all groups...
589     (gnus-group-mark-buffer)
590     (gnus-group-iterate nil
591       (lambda (group)
592         (let (gnus-auto-select-next)
593           (gnus-summary-read-group group nil t)
594           ;; ... and enter the articles into the cache.
595           (when (eq major-mode 'gnus-summary-mode)
596             (gnus-uu-mark-buffer)
597             (gnus-cache-enter-article)
598             (kill-buffer (current-buffer))))))))
599
600 (defun gnus-cache-read-active (&optional force)
601   "Read the cache active file."
602   (gnus-make-directory gnus-cache-directory)
603   (if (or (not (file-exists-p gnus-cache-active-file))
604           (zerop (nth 7 (file-attributes gnus-cache-active-file)))
605           force)
606       ;; There is no active file, so we generate one.
607       (gnus-cache-generate-active)
608     ;; We simply read the active file.
609     (save-excursion
610       (gnus-set-work-buffer)
611       (nnheader-insert-file-contents gnus-cache-active-file)
612       (gnus-active-to-gnus-format
613        nil (setq gnus-cache-active-hashtb
614                  (gnus-make-hashtable
615                   (count-lines (point-min) (point-max)))))
616       (setq gnus-cache-active-altered nil))))
617
618 (defun gnus-cache-write-active (&optional force)
619   "Write the active hashtb to the active file."
620   (when (or force
621             (and gnus-cache-active-hashtb
622                  gnus-cache-active-altered))
623     (gnus-write-active-file gnus-cache-active-file gnus-cache-active-hashtb t)
624     ;; Mark the active hashtb as unaltered.
625     (setq gnus-cache-active-altered nil)))
626
627 (defun gnus-cache-possibly-update-active (group active)
628   "Update active info bounds of GROUP with ACTIVE if necessary.
629 The update is performed if ACTIVE contains a higher or lower bound
630 than the current."
631   (let ((lower t) (higher t))
632     (if gnus-cache-active-hashtb
633         (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
634           (when cache-active
635             (unless (< (car active) (car cache-active))
636               (setq lower nil))
637             (unless (> (cdr active) (cdr cache-active))
638               (setq higher nil))))
639       (gnus-cache-read-active))
640     (when lower
641       (gnus-cache-update-active group (car active) t))
642     (when higher
643       (gnus-cache-update-active group (cdr active)))))
644
645 (defun gnus-cache-update-active (group number &optional low)
646   "Update the upper bound of the active info of GROUP to NUMBER.
647 If LOW, update the lower bound instead."
648   (let ((active (gnus-gethash group gnus-cache-active-hashtb)))
649     (if (null active)
650         ;; We just create a new active entry for this group.
651         (gnus-sethash group (cons number number) gnus-cache-active-hashtb)
652       ;; Update the lower or upper bound.
653       (if low
654           (setcar active number)
655         (setcdr active number)))
656     ;; Mark the active hashtb as altered.
657     (setq gnus-cache-active-altered t)))
658
659 ;;;###autoload
660 (defun gnus-cache-generate-active (&optional directory)
661   "Generate the cache active file."
662   (interactive)
663   (let* ((top (null directory))
664          (directory (expand-file-name (or directory gnus-cache-directory)))
665          (files (directory-files directory 'full))
666          (group
667           (if top
668               ""
669             (string-match
670              (concat "^" (regexp-quote
671                           (file-name-as-directory
672                            (expand-file-name gnus-cache-directory))))
673              (directory-file-name directory))
674             (nnheader-replace-chars-in-string
675              (substring (directory-file-name directory) (match-end 0))
676              ?/ ?.)))
677          nums alphs)
678     (when top
679       (gnus-message 5 "Generating the cache active file...")
680       (setq gnus-cache-active-hashtb (gnus-make-hashtable 123)))
681     (when (string-match "^\\(nn[^_]+\\)_" group)
682       (setq group (replace-match "\\1:" t nil group)))
683     ;; Separate articles from all other files and directories.
684     (while files
685       (if (string-match "^[0-9]+$" (file-name-nondirectory (car files)))
686           (push (string-to-int (file-name-nondirectory (pop files))) nums)
687         (push (pop files) alphs)))
688     ;; If we have nums, then this is probably a valid group.
689     (when (setq nums (sort nums '<))
690       (gnus-sethash group (cons (car nums) (gnus-last-element nums))
691                     gnus-cache-active-hashtb))
692     ;; Go through all the other files.
693     (dolist (file alphs)
694       (when (and (file-directory-p file)
695                  (not (string-match "^\\."
696                                     (file-name-nondirectory file))))
697         ;; We descend directories.
698         (gnus-cache-generate-active file)))
699     ;; Write the new active file.
700     (when top
701       (gnus-cache-write-active t)
702       (gnus-message 5 "Generating the cache active file...done"))))
703
704 ;;;###autoload
705 (defun gnus-cache-generate-nov-databases (dir)
706   "Generate NOV files recursively starting in DIR."
707   (interactive (list gnus-cache-directory))
708   (gnus-cache-close)
709   (let ((nnml-generate-active-function 'identity))
710     (nnml-generate-nov-databases-1 dir))
711
712   (setq gnus-cache-total-fetched-hashtb nil)
713
714   (gnus-cache-open))
715
716 (defun gnus-cache-move-cache (dir)
717   "Move the cache tree to somewhere else."
718   (interactive "FMove the cache tree to: ")
719   (rename-file gnus-cache-directory dir))
720
721 (defun gnus-cache-fully-p (&optional group)
722   "Returns non-nil if the cache should be fully used.
723 If GROUP is non-nil, also cater to `gnus-cacheable-groups' and
724 `gnus-uncacheable-groups'."
725   (and gnus-use-cache
726        (not (eq gnus-use-cache 'passive))
727        (if (null group)
728            t
729          (and (or (not gnus-cacheable-groups)
730                   (string-match gnus-cacheable-groups group))
731               (or (not gnus-uncacheable-groups)
732                   (not (string-match gnus-uncacheable-groups group)))))))
733
734 ;;;###autoload
735 (defun gnus-cache-rename-group (old-group new-group)
736   "Rename OLD-GROUP as NEW-GROUP.  Always updates the cache, even when
737 disabled, as the old cache files would corrupt gnus when the cache was
738 next enabled. Depends upon the caller to determine whether group renaming is supported."
739   (let ((old-dir (gnus-cache-file-name old-group ""))
740         (new-dir (gnus-cache-file-name new-group "")))
741     (gnus-rename-file old-dir new-dir t))
742
743   (gnus-cache-rename-group-total-fetched-for old-group new-group)
744
745   (let ((no-save gnus-cache-active-hashtb))
746     (unless gnus-cache-active-hashtb
747       (gnus-cache-read-active))
748     (let* ((old-group-hash-value (gnus-gethash old-group gnus-cache-active-hashtb))
749            (new-group-hash-value (gnus-gethash new-group gnus-cache-active-hashtb))
750            (delta                (or old-group-hash-value new-group-hash-value)))
751       (gnus-sethash new-group old-group-hash-value gnus-cache-active-hashtb)
752       (gnus-sethash old-group nil gnus-cache-active-hashtb)
753
754       (if no-save
755           (setq gnus-cache-active-altered delta)
756         (gnus-cache-write-active delta)))))
757
758 ;;;###autoload
759 (defun gnus-cache-delete-group (group)
760   "Delete GROUP.  Always updates the cache, even when
761 disabled, as the old cache files would corrupt gnus when the cache was
762 next enabled. Depends upon the caller to determine whether group deletion is supported."
763   (let ((dir (gnus-cache-file-name group "")))
764     (gnus-delete-directory dir))
765
766   (gnus-cache-delete-group-total-fetched-for group)
767
768   (let ((no-save gnus-cache-active-hashtb))
769     (unless gnus-cache-active-hashtb
770       (gnus-cache-read-active))
771     (let* ((group-hash-value (gnus-gethash group gnus-cache-active-hashtb)))
772       (gnus-sethash group nil gnus-cache-active-hashtb)
773
774       (if no-save
775           (setq gnus-cache-active-altered group-hash-value)
776         (gnus-cache-write-active group-hash-value)))))
777
778 (defvar gnus-cache-inhibit-update-total-fetched-for nil)
779 (defvar gnus-cache-need-update-total-fetched-for nil)
780
781 (defmacro gnus-cache-with-refreshed-group (group &rest body)
782   `(prog1 (let ((gnus-cache-inhibit-update-total-fetched-for t))
783             ,@body)
784      (when (and gnus-cache-need-update-total-fetched-for
785                 (not gnus-cache-inhibit-update-total-fetched-for))
786         (save-excursion
787           (set-buffer gnus-group-buffer)
788           (setq gnus-cache-need-update-total-fetched-for nil)
789           (gnus-group-update-group ,group t)))))
790
791 (defun gnus-cache-update-file-total-fetched-for (group file &optional subtract)
792   (when gnus-cache-total-fetched-hashtb
793     (gnus-cache-with-refreshed-group
794      group
795      (let* ((entry (or (gnus-gethash group gnus-cache-total-fetched-hashtb)
796                        (gnus-sethash group (make-vector 2 0)
797                                      gnus-cache-total-fetched-hashtb)))
798             size)
799
800        (if file
801            (setq size (or (nth 7 (file-attributes file)) 0))
802          (let ((files (directory-files (gnus-cache-file-name group "") 
803                                        t nil t))
804                file attrs)
805            (setq size 0.0)
806            (while (setq file (pop files))
807              (setq attrs (file-attributes file))
808              (unless (nth 0 attrs)
809                (incf size (float (nth 7 attrs)))))))         
810
811        (setq gnus-cache-need-update-total-fetched-for t)
812
813        (incf (nth 1 entry) (if subtract (- size) size))))))
814
815 (defun gnus-cache-update-overview-total-fetched-for (group file)
816   (when gnus-cache-total-fetched-hashtb
817     (gnus-cache-with-refreshed-group
818      group
819      (let* ((entry (or (gnus-gethash group gnus-cache-total-fetched-hashtb)
820                        (gnus-sethash group (make-list 2 0) 
821                                      gnus-cache-total-fetched-hashtb)))
822             (size (or (nth 7 (file-attributes 
823                               (or file
824                                   (gnus-cache-file-name group ".overview"))))
825                       0)))
826        (setq gnus-cache-need-update-total-fetched-for t)
827        (setf (nth 0 entry) size)))))
828
829 (defun gnus-cache-rename-group-total-fetched-for (old-group new-group)
830   "Record of disk space used by OLD-GROUP now associated with NEW-GROUP."
831   (when gnus-cache-total-fetched-hashtb
832     (let ((entry (gnus-gethash old-group gnus-cache-total-fetched-hashtb)))
833       (gnus-sethash new-group entry gnus-cache-total-fetched-hashtb)
834       (gnus-sethash old-group nil gnus-cache-total-fetched-hashtb))))
835
836 (defun gnus-cache-delete-group-total-fetched-for (group)
837   "Delete record of disk space used by GROUP being deleted."
838   (when gnus-cache-total-fetched-hashtb
839       (gnus-sethash group nil gnus-cache-total-fetched-hashtb)))
840
841 (defun gnus-cache-total-fetched-for (group &optional no-inhibit)
842   "Get total disk space used by the cache for the specified GROUP."
843   (unless gnus-cache-total-fetched-hashtb
844     (setq gnus-cache-total-fetched-hashtb (gnus-make-hashtable 1024)))
845
846   (let* ((entry (gnus-gethash group gnus-cache-total-fetched-hashtb)))
847     (if entry
848         (apply '+ entry)
849       (let ((gnus-cache-inhibit-update-total-fetched-for (not no-inhibit)))
850         (+ 
851          (gnus-cache-update-overview-total-fetched-for group nil)
852          (gnus-cache-update-file-total-fetched-for     group nil))))))
853
854 (provide 'gnus-cache)
855
856 ;;; gnus-cache.el ends here