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