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