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