*** empty log message ***
[gnus] / lisp / gnus-cache.el
1 ;;; gnus-cache.el --- cache interface for Gnus
2 ;; Copyright (C) 1995 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'gnus)
28 (eval-when-compile (require 'cl))
29
30 (defvar gnus-cache-directory
31   (concat (file-name-as-directory gnus-article-save-directory) "cache/")
32   "*The directory where cached articles will be stored.")
33
34 (defvar gnus-cache-active-file 
35   (concat (file-name-as-directory gnus-cache-directory) "active")
36   "*The cache active file.")
37
38 (defvar gnus-cache-enter-articles '(ticked dormant)
39   "*Classes of articles to enter into the cache.")
40
41 (defvar gnus-cache-remove-articles '(read)
42   "*Classes of articles to remove from the cache.")
43
44 (defvar gnus-uncacheable-groups "^nnvirtual"
45   "*Groups that match this regexp will not be cached.
46
47 If you want to avoid caching your nnml groups, you could set this
48 variable to \"^nnml\".")
49
50 \f
51
52 ;;; Internal variables.
53
54 (defvar gnus-cache-buffer nil)
55 (defvar gnus-cache-active-hashtb nil)
56 (defvar gnus-cache-active-altered nil)
57
58 (eval-and-compile
59   (autoload 'nnml-generate-nov-databases-1 "nnml"))
60
61 \f
62
63 ;;; Functions called from Gnus.
64
65 (defun gnus-cache-open ()
66   "Initialize the cache."
67   (gnus-cache-read-active))
68
69 (defun gnus-cache-close ()
70   "Shut down the cache."
71   (gnus-cache-write-active)
72   (gnus-cache-save-buffers)
73   (setq gnus-cache-active-hashtb nil))
74
75 (defun gnus-cache-save-buffers ()
76   ;; save the overview buffer if it exists and has been modified
77   ;; delete empty cache subdirectories
78   (if (null gnus-cache-buffer)
79       ()
80     (let ((buffer (cdr gnus-cache-buffer))
81           (overview-file (gnus-cache-file-name
82                           (car gnus-cache-buffer) ".overview")))
83       ;; write the overview only if it was modified
84       (if (buffer-modified-p buffer)
85           (save-excursion
86             (set-buffer buffer)
87             (if (> (buffer-size) 0)
88                 ;; non-empty overview, write it out
89                 (progn
90                   (gnus-make-directory (file-name-directory overview-file))
91                   (write-region (point-min) (point-max)
92                                 overview-file nil 'quietly))
93               ;; empty overview file, remove it
94               (and (file-exists-p overview-file)
95                    (delete-file overview-file))
96               ;; if possible, remove group's cache subdirectory
97               (condition-case nil
98                   ;; FIXME: we can detect the error type and warn the user
99                   ;; of any inconsistencies (articles w/o nov entries?).
100                   ;; for now, just be conservative...delete only if safe -- sj
101                   (delete-directory (file-name-directory overview-file))
102                 (error nil)))))
103       ;; kill the buffer, it's either unmodified or saved
104       (gnus-kill-buffer buffer)
105       (setq gnus-cache-buffer nil))))
106
107 (defun gnus-cache-possibly-enter-article 
108   (group article headers ticked dormant unread &optional force)
109   (when (or force (not (eq gnus-use-cache 'passive)))
110     (let ((number (mail-header-number headers))
111           file dir)
112       (when (and (vectorp headers)      ; This might be a dummy article.
113                  (> number 0)           ; Reffed article.
114                  (or (not gnus-uncacheable-groups)
115                      (not (string-match gnus-uncacheable-groups group)))
116                  (or force
117                      (gnus-cache-member-of-class
118                       gnus-cache-enter-articles ticked dormant unread))
119                  (not (file-exists-p (setq file (gnus-cache-file-name
120                                                  group article)))))
121         ;; Possibly create the cache directory.
122         (or (file-exists-p (setq dir (file-name-directory file)))
123             (gnus-make-directory dir))
124         ;; Save the article in the cache.
125         (if (file-exists-p file)
126             t                           ; The article already is saved.
127           (let ((gnus-use-cache nil))
128             (gnus-summary-select-article))
129           (save-excursion
130             (set-buffer gnus-original-article-buffer)
131             (save-restriction
132               (widen)
133               (write-region (point-min) (point-max) file nil 'quiet))
134             (gnus-cache-change-buffer group)
135             (set-buffer (cdr gnus-cache-buffer))
136             (goto-char (point-max))
137             (forward-line -1)
138             (while (condition-case ()
139                        (and (not (bobp))
140                             (> (read (current-buffer)) number))
141                      (error
142                       ;; The line was malformed, so we just remove it!!
143                       (gnus-delete-line)
144                       t))
145               (forward-line -1))
146             (if (bobp) 
147                 (if (not (eobp))
148                     (progn
149                       (beginning-of-line)
150                       (if (< (read (current-buffer)) number)
151                           (forward-line 1)))
152                   (beginning-of-line))
153               (forward-line 1))
154             (beginning-of-line)
155             ;; [number subject from date id references chars lines xref]
156             (insert (format "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n"
157                             (mail-header-number headers)
158                             (mail-header-subject headers)
159                             (mail-header-from headers)
160                             (mail-header-date headers)
161                             (mail-header-id headers)
162                             (or (mail-header-references headers) "")
163                             (or (mail-header-chars headers) "")
164                             (or (mail-header-lines headers) "")
165                             (or (mail-header-xref headers) ""))))
166           ;; Update the active info.
167           (gnus-cache-update-active group number)
168           (push number gnus-newsgroup-cached)
169           t)))))
170
171 (defun gnus-cache-enter-remove-article (article)
172   "Mark ARTICLE for later possible removal."
173   (setq gnus-cache-removeable-articles
174         (cons article gnus-cache-removeable-articles)))
175
176 (defun gnus-cache-possibly-remove-articles ()
177   "Possibly remove some of the removable articles."
178   (unless (eq gnus-use-cache 'passive)
179     (let ((articles gnus-cache-removeable-articles)
180           (cache-articles gnus-newsgroup-cached)
181           article)
182       (gnus-cache-change-buffer gnus-newsgroup-name)
183       (while articles
184         (if (memq (setq article (pop articles)) cache-articles)
185             ;; The article was in the cache, so we see whether we are
186             ;; supposed to remove it from the cache.
187             (gnus-cache-possibly-remove-article
188              article (memq article gnus-newsgroup-marked)
189              (memq article gnus-newsgroup-dormant)
190              (or (memq article gnus-newsgroup-unreads)
191                  (memq article gnus-newsgroup-unselected))))))
192     ;; The overview file might have been modified, save it
193     ;; safe because we're only called at group exit anyway.
194     (gnus-cache-save-buffers)))
195
196 (defun gnus-cache-request-article (article group)
197   "Retrieve ARTICLE in GROUP from the cache."
198   (let ((file (gnus-cache-file-name group article))
199         (buffer-read-only nil))
200     (when (file-exists-p file)
201       (erase-buffer)
202       (gnus-kill-all-overlays)
203       (insert-file-contents file)
204       t)))
205
206 (defun gnus-cache-possibly-alter-active (group active)
207   "Alter the ACTIVE info for GROUP to reflect the articles in the cache."
208   (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
209     (and cache-active 
210          (< (car cache-active) (car active))
211          (setcar active (car cache-active)))
212     (and cache-active
213          (> (cdr cache-active) (cdr active))
214          (setcdr active (cdr cache-active)))))
215
216 (defun gnus-cache-retrieve-headers (articles group &optional fetch-old)
217   "Retrieve the headers for ARTICLES in GROUP."
218   (let* ((cached 
219           (setq gnus-newsgroup-cached (gnus-cache-articles-in-group group)))
220          (articles (gnus-sorted-complement articles cached))
221          (cache-file (gnus-cache-file-name group ".overview"))
222          type)
223     ;; We first retrieve all the headers that we don't have in 
224     ;; the cache.
225     (let ((gnus-use-cache nil))
226       (setq type (and articles 
227                       (gnus-retrieve-headers articles group fetch-old))))
228     (gnus-cache-save-buffers)
229     ;; Then we insert the cached headers.
230     (save-excursion
231       (cond
232        ((not (file-exists-p cache-file))
233         ;; There are no cached headers.
234         type)
235        ((null type)
236         ;; There were no uncached headers (or retrieval was 
237         ;; unsuccessful), so we use the cached headers exclusively.
238         (set-buffer nntp-server-buffer)
239         (erase-buffer)
240         (insert-file-contents cache-file)
241         'nov)
242        ((eq type 'nov)
243         ;; We have both cached and uncached NOV headers, so we
244         ;; braid them.
245         (gnus-cache-braid-nov group cached)
246         type)
247        (t
248         ;; We braid HEADs.
249         (gnus-cache-braid-heads group cached)
250         type)))))
251
252 (defun gnus-cache-enter-article (n)
253   "Enter the next N articles into the cache.
254 If not given a prefix, use the process marked articles instead.
255 Returns the list of articles entered."
256   (interactive "P")
257   (gnus-set-global-variables)
258   (let ((articles (gnus-summary-work-articles n))
259         article out)
260     (while articles
261       (setq article (pop articles))
262       (when (gnus-cache-possibly-enter-article 
263              gnus-newsgroup-name article (gnus-summary-article-header article)
264              nil nil nil t)
265         (push article out))
266       (gnus-summary-remove-process-mark article)
267       (gnus-summary-update-secondary-mark article))
268     (gnus-summary-position-point)
269     (nreverse out)))
270
271 (defun gnus-cache-remove-article (n)
272   "Remove the next N articles from the cache.
273 If not given a prefix, use the process marked articles instead.
274 Returns the list of articles removed."
275   (interactive "P")
276   (gnus-set-global-variables)
277   (let ((articles (gnus-summary-work-articles n))
278         article out)
279     (while articles
280       (setq article (pop articles))
281       (when (gnus-cache-possibly-remove-article article nil nil nil t)
282         (push article out))
283       (gnus-summary-remove-process-mark article)
284       (gnus-summary-update-secondary-mark article))
285     (gnus-summary-position-point)
286     (nreverse out)))
287
288 (defun gnus-cached-article-p (article)
289   "Say whether ARTICLE is cached in the current group."
290   (memq article gnus-newsgroup-cached))
291
292 ;;; Internal functions.
293
294 (defun gnus-cache-change-buffer (group)
295   (and gnus-cache-buffer
296        ;; See if the current group's overview cache has been loaded.
297        (or (string= group (car gnus-cache-buffer))
298            ;; Another overview cache is current, save it.
299            (gnus-cache-save-buffers)))
300   ;; if gnus-cache buffer is nil, create it
301   (or gnus-cache-buffer
302       ;; Create cache buffer
303       (save-excursion
304         (setq gnus-cache-buffer
305               (cons group
306                     (set-buffer (get-buffer-create " *gnus-cache-overview*"))))
307         (buffer-disable-undo (current-buffer))
308         ;; Insert the contents of this group's cache overview.
309         (erase-buffer)
310         (let ((file (gnus-cache-file-name group ".overview")))
311           (and (file-exists-p file)
312                (insert-file-contents file)))
313         ;; We have a fresh (empty/just loaded) buffer, 
314         ;; mark it as unmodified to save a redundant write later.
315         (set-buffer-modified-p nil))))
316
317 ;; Return whether an article is a member of a class.
318 (defun gnus-cache-member-of-class (class ticked dormant unread)
319   (or (and ticked (memq 'ticked class))
320       (and dormant (memq 'dormant class))
321       (and unread (memq 'unread class))
322       (and (not unread) (memq 'read class))))
323
324 (defun gnus-cache-file-name (group article)
325   (concat (file-name-as-directory gnus-cache-directory)
326           (file-name-as-directory
327            (if (gnus-use-long-file-name 'not-cache)
328                group 
329              (let ((group (concat group "")))
330                (if (string-match ":" group)
331                    (aset group (match-beginning 0) ?/))
332                (gnus-replace-chars-in-string group ?. ?/))))
333           (if (stringp article) article (int-to-string article))))
334
335 (defun gnus-cache-possibly-remove-article 
336   (article ticked dormant unread &optional force)
337   "Possibly remove ARTICLE from the cache."
338   (let ((file (gnus-cache-file-name gnus-newsgroup-name article)))
339     (when (and (file-exists-p file)
340                (or force
341                    (gnus-cache-member-of-class
342                     gnus-cache-remove-articles ticked dormant unread)))
343       (save-excursion
344         (delete-file file)
345         (set-buffer (cdr gnus-cache-buffer))
346         (goto-char (point-min))
347         (if (or (looking-at (concat (int-to-string article) "\t"))
348                 (search-forward (concat "\n" (int-to-string article) "\t")
349                                 (point-max) t))
350             (delete-region (progn (beginning-of-line) (point))
351                            (progn (forward-line 1) (point)))))
352       (setq gnus-newsgroup-cached
353             (delq article gnus-newsgroup-cached))
354       t)))
355
356 (defun gnus-cache-articles-in-group (group)
357   "Return a sorted list of cached articles in GROUP."
358   (let ((dir (file-name-directory (gnus-cache-file-name group 1)))
359         articles)
360     (when (file-exists-p dir)
361       (sort (mapcar (lambda (name) (string-to-int name)) 
362                     (directory-files dir nil "^[0-9]+$" t))
363             '<))))
364
365 (defun gnus-cache-braid-nov (group cached)
366   (let ((cache-buf (get-buffer-create " *gnus-cache*"))
367         beg end)
368     (gnus-cache-save-buffers)
369     (save-excursion
370       (set-buffer cache-buf)
371       (buffer-disable-undo (current-buffer))
372       (erase-buffer)
373       (insert-file-contents (gnus-cache-file-name group ".overview"))
374       (goto-char (point-min))
375       (insert "\n")
376       (goto-char (point-min)))
377     (set-buffer nntp-server-buffer)
378     (goto-char (point-min))
379     (while cached
380       (while (and (not (eobp))
381                   (< (read (current-buffer)) (car cached)))
382         (forward-line 1))
383       (beginning-of-line)
384       (save-excursion
385         (set-buffer cache-buf)
386         (if (search-forward (concat "\n" (int-to-string (car cached)) "\t")
387                             nil t)
388             (setq beg (progn (beginning-of-line) (point))
389                   end (progn (end-of-line) (point)))
390           (setq beg nil)))
391       (if beg (progn (insert-buffer-substring cache-buf beg end)
392                      (insert "\n")))
393       (setq cached (cdr cached)))
394     (kill-buffer cache-buf)))
395
396 (defun gnus-cache-braid-heads (group cached)
397   (let ((cache-buf (get-buffer-create " *gnus-cache*")))
398     (save-excursion
399       (set-buffer cache-buf)
400       (buffer-disable-undo (current-buffer))
401       (erase-buffer))
402     (set-buffer nntp-server-buffer)
403     (goto-char (point-min))
404     (while cached
405       (while (and (not (eobp))
406                   (looking-at "2.. +\\([0-9]+\\) ")
407                   (< (progn (goto-char (match-beginning 1))
408                             (read (current-buffer)))
409                      (car cached)))
410         (search-forward "\n.\n" nil 'move))
411       (beginning-of-line)
412       (save-excursion
413         (set-buffer cache-buf)
414         (erase-buffer)
415         (insert-file-contents (gnus-cache-file-name group (car cached)))
416         (goto-char (point-min))
417         (insert "220 " (int-to-string (car cached)) " Article retrieved.\n")
418         (search-forward "\n\n" nil 'move)
419         (delete-region (point) (point-max))
420         (forward-char -1)
421         (insert "."))
422       (insert-buffer-substring cache-buf)
423       (setq cached (cdr cached)))
424     (kill-buffer cache-buf)))
425
426 ;;;###autoload
427 (defun gnus-jog-cache ()
428   "Go through all groups and put the articles into the cache."
429   (interactive)
430   (let ((newsrc (cdr gnus-newsrc-alist))
431         (gnus-cache-enter-articles '(unread))
432         (gnus-mark-article-hook nil)
433         (gnus-expert-user t)
434         (gnus-large-newsgroup nil))
435     (while newsrc
436       (gnus-summary-read-group (car (car newsrc)))
437       (if (not (eq major-mode 'gnus-summary-mode))
438           ()
439         (while gnus-newsgroup-unreads
440           (gnus-summary-select-article t t nil (car gnus-newsgroup-unreads))
441           (setq gnus-newsgroup-unreads (cdr gnus-newsgroup-unreads)))
442         (kill-buffer (current-buffer)))
443       (setq newsrc (cdr newsrc)))))
444
445 (defun gnus-cache-read-active (&optional force)
446   "Read the cache active file."
447   (if (not (and (file-exists-p gnus-cache-active-file)
448                 (or force (not gnus-cache-active-hashtb))))
449       ;; There is no active file, so we generate one.
450       (gnus-cache-generate-active)
451     ;; We simply read the active file.
452     (save-excursion
453       (gnus-set-work-buffer)
454       (insert-file-contents gnus-cache-active-file)
455       (gnus-active-to-gnus-format
456        nil (setq gnus-cache-active-hashtb 
457                  (gnus-make-hashtable 
458                   (count-lines (point-min) (point-max)))))
459       (setq gnus-cache-active-altered nil))))
460        
461 (defun gnus-cache-write-active (&optional force)
462   "Write the active hashtb to the active file."
463   (when (or force
464             (and gnus-cache-active-hashtb
465                  gnus-cache-active-altered))
466     (save-excursion
467       (gnus-set-work-buffer)
468       (mapatoms
469        (lambda (sym)
470          (when (and sym (boundp sym))
471            (insert (format "%s %d %d y\n"
472                            (symbol-name sym) (cdr (symbol-value sym))
473                            (car (symbol-value sym))))))
474        gnus-cache-active-hashtb)
475       (write-region 
476        (point-min) (point-max) gnus-cache-active-file nil 'silent))
477     ;; Mark the active hashtb as unaltered.
478     (setq gnus-cache-active-altered nil)))
479
480 (defun gnus-cache-update-active (group number &optional low)
481   "Update the upper bound of the active info of GROUP to NUMBER.
482 If LOW, update the lower bound instead."
483   (let ((active (gnus-gethash group gnus-cache-active-hashtb)))
484     (if (null active)
485         ;; We just create a new active entry for this group.
486         (gnus-sethash group (cons number number) gnus-cache-active-hashtb)
487       ;; Update the lower or upper bound.
488       (if low
489           (setcar active number)
490         (setcdr active number))
491       ;; Mark the active hashtb as altered.
492       (setq gnus-cache-active-altered t))))
493
494 ;;;###autoload
495 (defun gnus-cache-generate-active (&optional directory)
496   "Generate the cache active file."
497   (interactive)
498   (let* ((top (null directory))
499          (directory (expand-file-name (or directory gnus-cache-directory)))
500          (files (directory-files directory 'full))
501          (group 
502           (progn
503             (string-match 
504              (concat "^" (file-name-as-directory
505                           (expand-file-name gnus-cache-directory)))
506              directory)
507             (gnus-replace-chars-in-string 
508              (substring directory (match-end 0))
509              ?/ ?.)))
510          nums alphs)
511     (when top
512       (gnus-message 5 "Generating the cache active file...")
513       (setq gnus-cache-active-hashtb (gnus-make-hashtable 123)))
514     ;; Separate articles from all other files and directories.
515     (while files
516       (if (string-match "^[0-9]+$" (file-name-nondirectory (car files)))
517           (push (string-to-int (file-name-nondirectory (pop files))) nums)
518         (push (pop files) alphs)))
519     ;; If we have nums, then this is probably a valid group.
520     (setq nums (sort nums '<))
521     (if nums
522         (gnus-sethash group (cons (car nums) (gnus-last-element nums))
523                       gnus-cache-active-hashtb))
524     ;; Go through all the other files.
525     (while alphs
526       (when (and (file-directory-p (car alphs))
527                  (not (string-match "^\\.\\.?$"
528                                     (file-name-nondirectory (car alphs)))))
529         ;; We descend directories.
530         (gnus-cache-generate-active (car alphs)))
531       (setq alphs (cdr alphs)))
532     ;; Write the new active file.
533     (when top
534       (gnus-cache-write-active t)
535       (gnus-message 5 "Generating the cache active file...done"))))
536
537 ;;;###autoload
538 (defun gnus-cache-generate-nov-databases (dir)
539   "Generate NOV files recursively starting in DIR."
540   (interactive (list gnus-cache-directory))
541   (gnus-cache-close)
542   (let ((nnml-generate-active-function 'identity))
543     (nnml-generate-nov-databases-1 dir)))
544
545 (provide 'gnus-cache)
546               
547 ;;; gnus-cache.el ends here