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