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