45c65b984aa5bb12f1a74c309061867370d63f85
[gnus] / 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 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'gnus)
32 (eval-when-compile
33   (unless (fboundp 'gnus-agent-load-alist)
34       (defun gnus-agent-load-alist (group)))
35   (require 'gnus-sum))
36
37 (defcustom gnus-cache-active-file
38   (expand-file-name "active" gnus-cache-directory)
39   "*The cache active file."
40   :group 'gnus-cache
41   :type 'file)
42
43 (defcustom gnus-cache-enter-articles '(ticked dormant)
44   "Classes of articles to enter into the cache."
45   :group 'gnus-cache
46   :type '(set (const ticked) (const dormant) (const unread) (const read)))
47
48 (defcustom gnus-cache-remove-articles '(read)
49   "Classes of articles to remove from the cache."
50   :group 'gnus-cache
51   :type '(set (const ticked) (const dormant) (const unread) (const read)))
52
53 (defcustom gnus-cacheable-groups nil
54   "*Groups that match this regexp will be cached.
55
56 If you only want to cache your nntp groups, you could set this
57 variable to \"^nntp\".
58
59 If a group matches both gnus-cacheable-groups and gnus-uncacheable-groups
60 it's not cached."
61   :group 'gnus-cache
62   :type '(choice (const :tag "off" nil)
63                  regexp))
64
65 (defcustom gnus-uncacheable-groups nil
66   "*Groups that match this regexp will not be cached.
67
68 If you want to avoid caching your nnml groups, you could set this
69 variable to \"^nnml\".
70
71 If a group matches both gnus-cacheable-groups and gnus-uncacheable-groups
72 it's not cached."
73   :group 'gnus-cache
74   :type '(choice (const :tag "off" nil)
75                  regexp))
76
77 (defvar gnus-cache-overview-coding-system 'raw-text
78   "Coding system used on Gnus cache files.")
79
80 (defvar gnus-cache-coding-system 'raw-text
81   "Coding system used on Gnus cache files.")
82
83 \f
84
85 ;;; Internal variables.
86
87 (defvar gnus-cache-removable-articles nil)
88 (defvar gnus-cache-buffer nil)
89 (defvar gnus-cache-active-hashtb nil)
90 (defvar gnus-cache-active-altered nil)
91 (defvar gnus-cache-total-fetched-hashtb nil)
92
93 (eval-and-compile
94   (autoload 'nnml-generate-nov-databases-1 "nnml")
95   (autoload 'nnvirtual-find-group-art "nnvirtual"))
96
97 \f
98
99 ;;; Functions called from Gnus.
100
101 (defun gnus-cache-open ()
102   "Initialize the cache."
103   (when (or (file-exists-p gnus-cache-directory)
104             (and gnus-use-cache
105                  (not (eq gnus-use-cache 'passive))))
106     (gnus-cache-read-active)))
107
108 ;; Complexities of byte-compiling make this kludge necessary.  Eeek.
109 (ignore-errors
110   (gnus-add-shutdown 'gnus-cache-close 'gnus))
111
112 (defun gnus-cache-close ()
113   "Shut down the cache."
114   (gnus-cache-write-active)
115   (gnus-cache-save-buffers)
116   (setq gnus-cache-active-hashtb nil))
117
118 (defun gnus-cache-save-buffers ()
119   ;; save the overview buffer if it exists and has been modified
120   ;; delete empty cache subdirectories
121   (when gnus-cache-buffer
122     (let ((buffer (cdr gnus-cache-buffer))
123           (overview-file (gnus-cache-file-name
124                           (car gnus-cache-buffer) ".overview")))
125       ;; write the overview only if it was modified
126       (when (and (buffer-live-p buffer)
127                  (buffer-modified-p buffer))
128         (with-current-buffer buffer
129           (if (> (buffer-size) 0)
130               ;; Non-empty overview, write it to a file.
131               (let ((coding-system-for-write
132                      gnus-cache-overview-coding-system))
133                 (gnus-write-buffer overview-file))
134             ;; Empty overview file, remove it
135             (when (file-exists-p overview-file)
136               (delete-file overview-file))
137             ;; If possible, remove group's cache subdirectory.
138             (condition-case nil
139                 ;; FIXME: we can detect the error type and warn the user
140                 ;; of any inconsistencies (articles w/o nov entries?).
141                 ;; for now, just be conservative...delete only if safe -- sj
142                 (delete-directory (file-name-directory overview-file))
143               (error)))
144
145           (gnus-cache-update-overview-total-fetched-for
146            (car gnus-cache-buffer) overview-file)))
147       ;; Kill the buffer -- it's either unmodified or saved.
148       (gnus-kill-buffer buffer)
149       (setq gnus-cache-buffer nil))))
150
151 (defun gnus-cache-possibly-enter-article
152   (group article ticked dormant unread &optional force)
153   (when (and (or force (not (eq gnus-use-cache 'passive)))
154              (numberp article)
155              (> article 0))             ; This might be a dummy article.
156     (let ((number article)
157           file headers lines-chars)
158       ;; If this is a virtual group, we find the real group.
159       (when (gnus-virtual-group-p group)
160         (let ((result (nnvirtual-find-group-art
161                        (gnus-group-real-name group) article)))
162           (setq group (car result)
163                 number (cdr result))))
164       (when (and number
165                  (> number 0)           ; Reffed article.
166                  (or force
167                      (and (gnus-cache-fully-p group)
168                           (gnus-cache-member-of-class
169                            gnus-cache-enter-articles ticked dormant unread)))
170                  (not (file-exists-p (setq file (gnus-cache-file-name
171                                                  group number)))))
172         ;; Possibly create the cache directory.
173         (gnus-make-directory (file-name-directory file))
174         ;; Save the article in the cache.
175         (if (file-exists-p file)
176             t                           ; The article already is saved.
177           (save-excursion
178             (set-buffer nntp-server-buffer)
179             (require 'gnus-art)
180             (let ((gnus-use-cache nil)
181                   (gnus-article-decode-hook nil))
182               (gnus-request-article-this-buffer number group))
183             (when (> (buffer-size) 0)
184               (let ((coding-system-for-write gnus-cache-coding-system))
185                 (gnus-write-buffer file)
186                 (gnus-cache-update-file-total-fetched-for group file))
187               (setq lines-chars (nnheader-get-lines-and-char))
188               (nnheader-remove-body)
189               (setq headers (nnheader-parse-naked-head))
190               (mail-header-set-number headers number)
191               (mail-header-set-lines headers (car lines-chars))
192               (mail-header-set-chars headers (cadr lines-chars))
193               (gnus-cache-change-buffer group)
194               (set-buffer (cdr gnus-cache-buffer))
195               (goto-char (point-max))
196               (forward-line -1)
197               (while (condition-case ()
198                          (when (not (bobp))
199                            (> (read (current-buffer)) number))
200                        (error
201                         ;; The line was malformed, so we just remove it!!
202                         (gnus-delete-line)
203                         t))
204                 (forward-line -1))
205               (if (bobp)
206                   (if (not (eobp))
207                       (progn
208                         (beginning-of-line)
209                         (when (< (read (current-buffer)) number)
210                           (forward-line 1)))
211                     (beginning-of-line))
212                 (forward-line 1))
213               (beginning-of-line)
214               (nnheader-insert-nov headers)
215               ;; Update the active info.
216               (set-buffer gnus-summary-buffer)
217               (gnus-cache-possibly-update-active group (cons number number))
218               (setq gnus-newsgroup-cached
219                     (gnus-add-to-sorted-list gnus-newsgroup-cached article))
220               (gnus-summary-update-secondary-mark article))
221             t))))))
222
223 (defun gnus-cache-enter-remove-article (article)
224   "Mark ARTICLE for later possible removal."
225   (when article
226     (push article gnus-cache-removable-articles)))
227
228 (defun gnus-cache-possibly-remove-articles ()
229   "Possibly remove some of the removable articles."
230   (if (not (gnus-virtual-group-p gnus-newsgroup-name))
231       (gnus-cache-possibly-remove-articles-1)
232     (let ((arts gnus-cache-removable-articles)
233           ga)
234       (while arts
235         (when (setq ga (nnvirtual-find-group-art
236                         (gnus-group-real-name gnus-newsgroup-name) (pop arts)))
237           (let ((gnus-cache-removable-articles (list (cdr ga)))
238                 (gnus-newsgroup-name (car ga)))
239             (gnus-cache-possibly-remove-articles-1)))))
240     (setq gnus-cache-removable-articles nil)))
241
242 (defun gnus-cache-possibly-remove-articles-1 ()
243   "Possibly remove some of the removable articles."
244   (when (gnus-cache-fully-p gnus-newsgroup-name)
245     (let ((articles gnus-cache-removable-articles)
246           (cache-articles gnus-newsgroup-cached)
247           article)
248       (gnus-cache-change-buffer gnus-newsgroup-name)
249       (while articles
250         (when (memq (setq article (pop articles)) 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 ((coding-system-for-read gnus-cache-coding-system))
270         (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 ((coding-system-for-read
315                    gnus-cache-overview-coding-system))
316               (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 ((articles (gnus-summary-work-articles n))
335         article out)
336     (while (setq article (pop articles))
337       (gnus-summary-remove-process-mark article)
338       (if (natnump article)
339           (when (gnus-cache-possibly-enter-article
340                  gnus-newsgroup-name 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 ((articles (gnus-summary-work-articles n))
358         article out)
359     (while articles
360       (setq article (pop articles))
361       (gnus-summary-remove-process-mark article)
362       (when (gnus-cache-possibly-remove-article article nil nil nil t)
363         (when gnus-newsgroup-agentized
364           (let ((alist (gnus-agent-load-alist gnus-newsgroup-name)))
365             (unless (cdr (assoc article alist))
366               (setq gnus-newsgroup-undownloaded
367                     (gnus-add-to-sorted-list 
368                      gnus-newsgroup-undownloaded article)))))
369         (push article out))
370       (gnus-summary-update-download-mark article)
371       (gnus-summary-update-secondary-mark article))
372     (gnus-summary-next-subject 1)
373     (gnus-summary-position-point)
374     (nreverse out)))
375
376 (defun gnus-cached-article-p (article)
377   "Say whether ARTICLE is cached in the current group."
378   (memq article gnus-newsgroup-cached))
379
380 (defun gnus-summary-insert-cached-articles ()
381   "Insert all the articles cached for this group into the current buffer."
382   (interactive)
383   (let ((gnus-verbose (max 6 gnus-verbose)))
384     (if (not gnus-newsgroup-cached)
385         (gnus-message 3 "No cached articles for this group")
386       (gnus-summary-goto-subjects gnus-newsgroup-cached))))
387
388 (defun gnus-summary-limit-include-cached ()
389   "Limit the summary buffer to articles that are cached."
390   (interactive)
391   (let ((gnus-verbose (max 6 gnus-verbose)))
392     (if gnus-newsgroup-cached
393         (progn
394           (gnus-summary-limit gnus-newsgroup-cached)
395           (gnus-summary-position-point))
396       (gnus-message 3 "No cached articles for this group"))))
397
398 ;;; Internal functions.
399
400 (defun gnus-cache-change-buffer (group)
401   (and gnus-cache-buffer
402        ;; See if the current group's overview cache has been loaded.
403        (or (string= group (car gnus-cache-buffer))
404            ;; Another overview cache is current, save it.
405            (gnus-cache-save-buffers)))
406   ;; if gnus-cache buffer is nil, create it
407   (unless gnus-cache-buffer
408     ;; Create cache buffer
409     (save-excursion
410       (setq gnus-cache-buffer
411             (cons group
412                   (set-buffer (gnus-get-buffer-create
413                                " *gnus-cache-overview*"))))
414       ;; Insert the contents of this group's cache overview.
415       (erase-buffer)
416       (let ((file (gnus-cache-file-name group ".overview")))
417         (when (file-exists-p file)
418           (nnheader-insert-file-contents file)))
419       ;; We have a fresh (empty/just loaded) buffer,
420       ;; mark it as unmodified to save a redundant write later.
421       (set-buffer-modified-p nil))))
422
423 ;; Return whether an article is a member of a class.
424 (defun gnus-cache-member-of-class (class ticked dormant unread)
425   (or (and ticked (memq 'ticked class))
426       (and dormant (memq 'dormant class))
427       (and unread (memq 'unread class))
428       (and (not unread) (not ticked) (not dormant) (memq 'read class))))
429
430 (defun gnus-cache-file-name (group article)
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
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-int 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 ((coding-system-for-read
519              gnus-cache-overview-coding-system))
520         (insert-file-contents
521          (or file (gnus-cache-file-name group ".overview"))))
522       (goto-char (point-min))
523       (insert "\n")
524       (goto-char (point-min)))
525     (set-buffer nntp-server-buffer)
526     (goto-char (point-min))
527     (while cached
528       (while (and (not (eobp))
529                   (< (read (current-buffer)) (car cached)))
530         (forward-line 1))
531       (beginning-of-line)
532       (set-buffer cache-buf)
533       (if (search-forward (concat "\n" (int-to-string (car cached)) "\t")
534                           nil t)
535           (setq beg (point-at-bol)
536                 end (progn (end-of-line) (point)))
537         (setq beg nil))
538       (set-buffer nntp-server-buffer)
539       (when beg
540         (insert-buffer-substring cache-buf beg end)
541         (insert "\n"))
542       (setq cached (cdr cached)))
543     (kill-buffer cache-buf)))
544
545 (defun gnus-cache-braid-heads (group cached)
546   (let ((cache-buf (gnus-get-buffer-create " *gnus-cache*")))
547     (save-excursion
548       (set-buffer cache-buf)
549       (erase-buffer))
550     (set-buffer nntp-server-buffer)
551     (goto-char (point-min))
552     (while cached
553       (while (and (not (eobp))
554                   (looking-at "2.. +\\([0-9]+\\) ")
555                   (< (progn (goto-char (match-beginning 1))
556                             (read (current-buffer)))
557                      (car cached)))
558         (search-forward "\n.\n" nil 'move))
559       (beginning-of-line)
560       (set-buffer cache-buf)
561       (erase-buffer)
562       (let ((coding-system-for-read
563              gnus-cache-coding-system))
564         (insert-file-contents (gnus-cache-file-name group (car cached))))
565       (goto-char (point-min))
566       (insert "220 ")
567       (princ (car cached) (current-buffer))
568       (insert " Article retrieved.\n")
569       (search-forward "\n\n" nil 'move)
570       (delete-region (point) (point-max))
571       (forward-char -1)
572       (insert ".")
573       (set-buffer nntp-server-buffer)
574       (insert-buffer-substring cache-buf)
575       (setq cached (cdr cached)))
576     (kill-buffer cache-buf)))
577
578 ;;;###autoload
579 (defun gnus-jog-cache ()
580   "Go through all groups and put the articles into the cache.
581
582 Usage:
583 $ emacs -batch -l ~/.emacs -l gnus -f gnus-jog-cache"
584   (interactive)
585   (let ((gnus-mark-article-hook nil)
586         (gnus-expert-user t)
587         (nnmail-spool-file nil)
588         (mail-sources nil)
589         (gnus-use-dribble-file nil)
590         (gnus-novice-user nil)
591         (gnus-large-newsgroup nil))
592     ;; Start Gnus.
593     (gnus)
594     ;; Go through all groups...
595     (gnus-group-mark-buffer)
596     (gnus-group-iterate nil
597       (lambda (group)
598         (let (gnus-auto-select-next)
599           (gnus-summary-read-group group nil t)
600           ;; ... and enter the articles into the cache.
601           (when (eq major-mode 'gnus-summary-mode)
602             (gnus-uu-mark-buffer)
603             (gnus-cache-enter-article)
604             (kill-buffer (current-buffer))))))))
605
606 (defun gnus-cache-read-active (&optional force)
607   "Read the cache active file."
608   (gnus-make-directory gnus-cache-directory)
609   (if (or (not (file-exists-p gnus-cache-active-file))
610           (zerop (nth 7 (file-attributes gnus-cache-active-file)))
611           force)
612       ;; There is no active file, so we generate one.
613       (gnus-cache-generate-active)
614     ;; We simply read the active file.
615     (save-excursion
616       (gnus-set-work-buffer)
617       (nnheader-insert-file-contents gnus-cache-active-file)
618       (gnus-active-to-gnus-format
619        nil (setq gnus-cache-active-hashtb
620                  (gnus-make-hashtable
621                   (count-lines (point-min) (point-max)))))
622       (setq gnus-cache-active-altered nil))))
623
624 (defun gnus-cache-write-active (&optional force)
625   "Write the active hashtb to the active file."
626   (when (or force
627             (and gnus-cache-active-hashtb
628                  gnus-cache-active-altered))
629     (gnus-write-active-file gnus-cache-active-file gnus-cache-active-hashtb t)
630     ;; Mark the active hashtb as unaltered.
631     (setq gnus-cache-active-altered nil)))
632
633 (defun gnus-cache-possibly-update-active (group active)
634   "Update active info bounds of GROUP with ACTIVE if necessary.
635 The update is performed if ACTIVE contains a higher or lower bound
636 than the current."
637   (let ((lower t) (higher t))
638     (if gnus-cache-active-hashtb
639         (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
640           (when cache-active
641             (unless (< (car active) (car cache-active))
642               (setq lower nil))
643             (unless (> (cdr active) (cdr cache-active))
644               (setq higher nil))))
645       (gnus-cache-read-active))
646     (when lower
647       (gnus-cache-update-active group (car active) t))
648     (when higher
649       (gnus-cache-update-active group (cdr active)))))
650
651 (defun gnus-cache-update-active (group number &optional low)
652   "Update the upper bound of the active info of GROUP to NUMBER.
653 If LOW, update the lower bound instead."
654   (let ((active (gnus-gethash group gnus-cache-active-hashtb)))
655     (if (null active)
656         ;; We just create a new active entry for this group.
657         (gnus-sethash group (cons number number) gnus-cache-active-hashtb)
658       ;; Update the lower or upper bound.
659       (if low
660           (setcar active number)
661         (setcdr active number)))
662     ;; Mark the active hashtb as altered.
663     (setq gnus-cache-active-altered t)))
664
665 ;;;###autoload
666 (defun gnus-cache-generate-active (&optional directory)
667   "Generate the cache active file."
668   (interactive)
669   (let* ((top (null directory))
670          (directory (expand-file-name (or directory gnus-cache-directory)))
671          (files (directory-files directory 'full))
672          (group
673           (if top
674               ""
675             (string-match
676              (concat "^" (regexp-quote
677                           (file-name-as-directory
678                            (expand-file-name gnus-cache-directory))))
679              (directory-file-name directory))
680             (nnheader-replace-chars-in-string
681              (substring (directory-file-name directory) (match-end 0))
682              ?/ ?.)))
683          nums alphs)
684     (when top
685       (gnus-message 5 "Generating the cache active file...")
686       (setq gnus-cache-active-hashtb (gnus-make-hashtable 123)))
687     (when (string-match "^\\(nn[^_]+\\)_" group)
688       (setq group (replace-match "\\1:" t nil group)))
689     ;; Separate articles from all other files and directories.
690     (while files
691       (if (string-match "^[0-9]+$" (file-name-nondirectory (car files)))
692           (push (string-to-int (file-name-nondirectory (pop files))) nums)
693         (push (pop files) alphs)))
694     ;; If we have nums, then this is probably a valid group.
695     (when (setq nums (sort nums '<))
696       (gnus-sethash group (cons (car nums) (gnus-last-element nums))
697                     gnus-cache-active-hashtb))
698     ;; Go through all the other files.
699     (while alphs
700       (when (and (file-directory-p (car alphs))
701                  (not (string-match "^\\."
702                                     (file-name-nondirectory (car alphs)))))
703         ;; We descend directories.
704         (gnus-cache-generate-active (car alphs)))
705       (setq alphs (cdr alphs)))
706     ;; Write the new active file.
707     (when top
708       (gnus-cache-write-active t)
709       (gnus-message 5 "Generating the cache active file...done"))))
710
711 ;;;###autoload
712 (defun gnus-cache-generate-nov-databases (dir)
713   "Generate NOV files recursively starting in DIR."
714   (interactive (list gnus-cache-directory))
715   (gnus-cache-close)
716   (let ((nnml-generate-active-function 'identity))
717     (nnml-generate-nov-databases-1 dir))
718
719   (setq gnus-cache-total-fetched-hashtb nil)
720
721   (gnus-cache-open))
722
723 (defun gnus-cache-move-cache (dir)
724   "Move the cache tree to somewhere else."
725   (interactive "FMove the cache tree to: ")
726   (rename-file gnus-cache-directory dir))
727
728 (defun gnus-cache-fully-p (&optional group)
729   "Returns non-nil if the cache should be fully used.
730 If GROUP is non-nil, also cater to `gnus-cacheable-groups' and
731 `gnus-uncacheable-groups'."
732   (and gnus-use-cache
733        (not (eq gnus-use-cache 'passive))
734        (if (null group)
735            t
736          (and (or (not gnus-cacheable-groups)
737                   (string-match gnus-cacheable-groups group))
738               (or (not gnus-uncacheable-groups)
739                   (not (string-match gnus-uncacheable-groups group)))))))
740
741 ;;;###autoload
742 (defun gnus-cache-rename-group (old-group new-group)
743   "Rename OLD-GROUP as NEW-GROUP.  Always updates the cache, even when
744 disabled, as the old cache files would corrupt gnus when the cache was
745 next enabled. Depends upon the caller to determine whether group renaming is supported."
746   (let ((old-dir (gnus-cache-file-name old-group ""))
747         (new-dir (gnus-cache-file-name new-group "")))
748     (gnus-rename-file old-dir new-dir t))
749
750   (gnus-cache-rename-group-total-fetched-for old-group new-group)
751
752   (let ((no-save gnus-cache-active-hashtb))
753     (unless gnus-cache-active-hashtb
754       (gnus-cache-read-active))
755     (let* ((old-group-hash-value (gnus-gethash old-group gnus-cache-active-hashtb))
756            (new-group-hash-value (gnus-gethash new-group gnus-cache-active-hashtb))
757            (delta                (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.  Always updates the cache, even when
768 disabled, as the old cache files would corrupt gnus when the cache was
769 next enabled. Depends upon the caller to determine whether group deletion is supported."
770   (let ((dir (gnus-cache-file-name group "")))
771     (gnus-delete-file dir))
772
773   (gnus-cache-delete-group-total-fetched-for group)
774
775   (let ((no-save gnus-cache-active-hashtb))
776     (unless gnus-cache-active-hashtb
777       (gnus-cache-read-active))
778     (let* ((group-hash-value (gnus-gethash group gnus-cache-active-hashtb)))
779       (gnus-sethash group nil gnus-cache-active-hashtb)
780
781       (if no-save
782           (setq gnus-cache-active-altered group-hash-value)
783         (gnus-cache-write-active group-hash-value)))))
784
785 (defvar gnus-cache-inhibit-update-total-fetched-for nil)
786 (defvar gnus-cache-need-update-total-fetched-for nil)
787
788 (defmacro gnus-cache-with-refreshed-group (group &rest body)
789   `(prog1 (let ((gnus-cache-inhibit-update-total-fetched-for t))
790             ,@body)
791      (when (and gnus-cache-need-update-total-fetched-for
792                 (not gnus-cache-inhibit-update-total-fetched-for))
793         (save-excursion
794           (set-buffer gnus-group-buffer)
795           (setq gnus-cache-need-update-total-fetched-for nil)
796           (gnus-group-update-group ,group t)))))
797
798 (defun gnus-cache-update-file-total-fetched-for (group file &optional subtract)
799   (when gnus-cache-total-fetched-hashtb
800     (gnus-cache-with-refreshed-group
801      group
802      (let* ((entry (or (gnus-gethash group gnus-cache-total-fetched-hashtb)
803                        (gnus-sethash group (make-vector 2 0)
804                                      gnus-cache-total-fetched-hashtb)))
805             size)
806
807        (if file
808            (setq size (or (nth 7 (file-attributes file)) 0))
809          (let ((files (directory-files (gnus-cache-file-name group "") 
810                                        t nil t))
811                file attrs)
812            (setq size 0.0)
813            (while (setq file (pop files))
814              (setq attrs (file-attributes file))
815              (unless (nth 0 attrs)
816                (incf size (float (nth 7 attrs)))))))         
817
818        (setq gnus-cache-need-update-total-fetched-for t)
819
820        (incf (nth 1 entry) (if subtract (- size) size))))))
821
822 (defun gnus-cache-update-overview-total-fetched-for (group file)
823   (when gnus-cache-total-fetched-hashtb
824     (gnus-cache-with-refreshed-group
825      group
826      (let* ((entry (or (gnus-gethash group gnus-cache-total-fetched-hashtb)
827                        (gnus-sethash group (make-list 2 0) 
828                                      gnus-cache-total-fetched-hashtb)))
829             (size (or (nth 7 (file-attributes 
830                               (or file
831                                   (gnus-cache-file-name group ".overview"))))
832                       0)))
833        (setq gnus-cache-need-update-total-fetched-for t)
834        (setf (nth 0 entry) size)))))
835
836 (defun gnus-cache-rename-group-total-fetched-for (old-group new-group)
837   "Record of disk space used by OLD-GROUP now associated with NEW-GROUP."
838   (when gnus-cache-total-fetched-hashtb
839     (let ((entry (gnus-gethash old-group gnus-cache-total-fetched-hashtb)))
840       (gnus-sethash new-group entry gnus-cache-total-fetched-hashtb)
841       (gnus-sethash old-group nil gnus-cache-total-fetched-hashtb))))
842
843 (defun gnus-cache-delete-group-total-fetched-for (group)
844   "Delete record of disk space used by GROUP being deleted."
845   (when gnus-cache-total-fetched-hashtb
846       (gnus-sethash group nil gnus-cache-total-fetched-hashtb)))
847
848 (defun gnus-cache-total-fetched-for (group &optional no-inhibit)
849   "Get total disk space used by the cache for the specified GROUP."
850   (unless gnus-cache-total-fetched-hashtb
851     (setq gnus-cache-total-fetched-hashtb (gnus-make-hashtable 1024)))
852
853   (let* ((entry (gnus-gethash group gnus-cache-total-fetched-hashtb)))
854     (if entry
855         (apply '+ entry)
856       (let ((gnus-cache-inhibit-update-total-fetched-for (not no-inhibit)))
857         (+ 
858          (gnus-cache-update-overview-total-fetched-for group nil)
859          (gnus-cache-update-file-total-fetched-for     group nil))))))
860
861 (provide 'gnus-cache)
862
863 ;;; gnus-cache.el ends here