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