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