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