*** 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             (when (> (buffer-size) 0)
132               (write-region (point-min) (point-max) file nil 'quiet)
133               (gnus-cache-change-buffer group)
134               (set-buffer (cdr gnus-cache-buffer))
135               (goto-char (point-max))
136               (forward-line -1)
137               (while (condition-case ()
138                          (and (not (bobp))
139                               (> (read (current-buffer)) number))
140                        (error
141                         ;; The line was malformed, so we just remove it!!
142                         (gnus-delete-line)
143                         t))
144                 (forward-line -1))
145               (if (bobp) 
146                   (if (not (eobp))
147                       (progn
148                         (beginning-of-line)
149                         (if (< (read (current-buffer)) number)
150                             (forward-line 1)))
151                     (beginning-of-line))
152                 (forward-line 1))
153               (beginning-of-line)
154               ;; [number subject from date id references chars lines xref]
155               (insert (format "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n"
156                               (mail-header-number headers)
157                               (mail-header-subject headers)
158                               (mail-header-from headers)
159                               (mail-header-date headers)
160                               (mail-header-id headers)
161                               (or (mail-header-references headers) "")
162                               (or (mail-header-chars headers) "")
163                               (or (mail-header-lines headers) "")
164                               (or (mail-header-xref headers) "")))
165               ;; Update the active info.
166               (gnus-cache-update-active group number)
167               (push number gnus-newsgroup-cached))
168             t))))))
169
170 (defun gnus-cache-enter-remove-article (article)
171   "Mark ARTICLE for later possible removal."
172   (setq gnus-cache-removeable-articles
173         (cons article gnus-cache-removeable-articles)))
174
175 (defun gnus-cache-possibly-remove-articles ()
176   "Possibly remove some of the removable articles."
177   (unless (eq gnus-use-cache 'passive)
178     (let ((articles gnus-cache-removeable-articles)
179           (cache-articles gnus-newsgroup-cached)
180           article)
181       (gnus-cache-change-buffer gnus-newsgroup-name)
182       (while articles
183         (if (memq (setq article (pop articles)) cache-articles)
184             ;; The article was in the cache, so we see whether we are
185             ;; supposed to remove it from the cache.
186             (gnus-cache-possibly-remove-article
187              article (memq article gnus-newsgroup-marked)
188              (memq article gnus-newsgroup-dormant)
189              (or (memq article gnus-newsgroup-unreads)
190                  (memq article gnus-newsgroup-unselected))))))
191     ;; The overview file might have been modified, save it
192     ;; safe because we're only called at group exit anyway.
193     (gnus-cache-save-buffers)))
194
195 (defun gnus-cache-request-article (article group)
196   "Retrieve ARTICLE in GROUP from the cache."
197   (let ((file (gnus-cache-file-name group article))
198         (buffer-read-only nil))
199     (when (file-exists-p file)
200       (erase-buffer)
201       (gnus-kill-all-overlays)
202       (insert-file-contents file)
203       t)))
204
205 (defun gnus-cache-possibly-alter-active (group active)
206   "Alter the ACTIVE info for GROUP to reflect the articles in the cache."
207   (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
208     (and cache-active 
209          (< (car cache-active) (car active))
210          (setcar active (car cache-active)))
211     (and cache-active
212          (> (cdr cache-active) (cdr active))
213          (setcdr active (cdr cache-active)))))
214
215 (defun gnus-cache-retrieve-headers (articles group &optional fetch-old)
216   "Retrieve the headers for ARTICLES in GROUP."
217   (let* ((cached 
218           (setq gnus-newsgroup-cached (gnus-cache-articles-in-group group)))
219          (articles (gnus-sorted-complement articles cached))
220          (cache-file (gnus-cache-file-name group ".overview"))
221          type)
222     ;; We first retrieve all the headers that we don't have in 
223     ;; the cache.
224     (let ((gnus-use-cache nil))
225       (setq type (and articles 
226                       (gnus-retrieve-headers articles group fetch-old))))
227     (gnus-cache-save-buffers)
228     ;; Then we insert the cached headers.
229     (save-excursion
230       (cond
231        ((not (file-exists-p cache-file))
232         ;; There are no cached headers.
233         type)
234        ((null type)
235         ;; There were no uncached headers (or retrieval was 
236         ;; unsuccessful), so we use the cached headers exclusively.
237         (set-buffer nntp-server-buffer)
238         (erase-buffer)
239         (insert-file-contents cache-file)
240         'nov)
241        ((eq type 'nov)
242         ;; We have both cached and uncached NOV headers, so we
243         ;; braid them.
244         (gnus-cache-braid-nov group cached)
245         type)
246        (t
247         ;; We braid HEADs.
248         (gnus-cache-braid-heads group cached)
249         type)))))
250
251 (defun gnus-cache-enter-article (n)
252   "Enter the next N articles into the cache.
253 If not given a prefix, use the process marked articles instead.
254 Returns the list of articles entered."
255   (interactive "P")
256   (gnus-set-global-variables)
257   (let ((articles (gnus-summary-work-articles n))
258         article out)
259     (while articles
260       (setq article (pop articles))
261       (when (gnus-cache-possibly-enter-article 
262              gnus-newsgroup-name article (gnus-summary-article-header article)
263              nil nil nil t)
264         (push article out))
265       (gnus-summary-remove-process-mark article)
266       (gnus-summary-update-secondary-mark article))
267     (gnus-summary-position-point)
268     (nreverse out)))
269
270 (defun gnus-cache-remove-article (n)
271   "Remove the next N articles from the cache.
272 If not given a prefix, use the process marked articles instead.
273 Returns the list of articles removed."
274   (interactive "P")
275   (gnus-set-global-variables)
276   (let ((articles (gnus-summary-work-articles n))
277         article out)
278     (while articles
279       (setq article (pop articles))
280       (when (gnus-cache-possibly-remove-article article nil nil nil t)
281         (push article out))
282       (gnus-summary-remove-process-mark article)
283       (gnus-summary-update-secondary-mark article))
284     (gnus-summary-position-point)
285     (nreverse out)))
286
287 (defun gnus-cached-article-p (article)
288   "Say whether ARTICLE is cached in the current group."
289   (memq article gnus-newsgroup-cached))
290
291 ;;; Internal functions.
292
293 (defun gnus-cache-change-buffer (group)
294   (and gnus-cache-buffer
295        ;; See if the current group's overview cache has been loaded.
296        (or (string= group (car gnus-cache-buffer))
297            ;; Another overview cache is current, save it.
298            (gnus-cache-save-buffers)))
299   ;; if gnus-cache buffer is nil, create it
300   (or gnus-cache-buffer
301       ;; Create cache buffer
302       (save-excursion
303         (setq gnus-cache-buffer
304               (cons group
305                     (set-buffer (get-buffer-create " *gnus-cache-overview*"))))
306         (buffer-disable-undo (current-buffer))
307         ;; Insert the contents of this group's cache overview.
308         (erase-buffer)
309         (let ((file (gnus-cache-file-name group ".overview")))
310           (and (file-exists-p file)
311                (insert-file-contents file)))
312         ;; We have a fresh (empty/just loaded) buffer, 
313         ;; mark it as unmodified to save a redundant write later.
314         (set-buffer-modified-p nil))))
315
316 ;; Return whether an article is a member of a class.
317 (defun gnus-cache-member-of-class (class ticked dormant unread)
318   (or (and ticked (memq 'ticked class))
319       (and dormant (memq 'dormant class))
320       (and unread (memq 'unread class))
321       (and (not unread) (memq 'read class))))
322
323 (defun gnus-cache-file-name (group article)
324   (concat (file-name-as-directory gnus-cache-directory)
325           (file-name-as-directory
326            (if (gnus-use-long-file-name 'not-cache)
327                group 
328              (let ((group (concat group "")))
329                (if (string-match ":" group)
330                    (aset group (match-beginning 0) ?/))
331                (gnus-replace-chars-in-string group ?. ?/))))
332           (if (stringp article) article (int-to-string article))))
333
334 (defun gnus-cache-possibly-remove-article 
335   (article ticked dormant unread &optional force)
336   "Possibly remove ARTICLE from the cache."
337   (let ((file (gnus-cache-file-name gnus-newsgroup-name article)))
338     (when (and (file-exists-p file)
339                (or force
340                    (gnus-cache-member-of-class
341                     gnus-cache-remove-articles ticked dormant unread)))
342       (save-excursion
343         (delete-file file)
344         (set-buffer (cdr gnus-cache-buffer))
345         (goto-char (point-min))
346         (if (or (looking-at (concat (int-to-string article) "\t"))
347                 (search-forward (concat "\n" (int-to-string article) "\t")
348                                 (point-max) t))
349             (delete-region (progn (beginning-of-line) (point))
350                            (progn (forward-line 1) (point)))))
351       (setq gnus-newsgroup-cached
352             (delq article gnus-newsgroup-cached))
353       t)))
354
355 (defun gnus-cache-articles-in-group (group)
356   "Return a sorted list of cached articles in GROUP."
357   (let ((dir (file-name-directory (gnus-cache-file-name group 1)))
358         articles)
359     (when (file-exists-p dir)
360       (sort (mapcar (lambda (name) (string-to-int name)) 
361                     (directory-files dir nil "^[0-9]+$" t))
362             '<))))
363
364 (defun gnus-cache-braid-nov (group cached)
365   (let ((cache-buf (get-buffer-create " *gnus-cache*"))
366         beg end)
367     (gnus-cache-save-buffers)
368     (save-excursion
369       (set-buffer cache-buf)
370       (buffer-disable-undo (current-buffer))
371       (erase-buffer)
372       (insert-file-contents (gnus-cache-file-name group ".overview"))
373       (goto-char (point-min))
374       (insert "\n")
375       (goto-char (point-min)))
376     (set-buffer nntp-server-buffer)
377     (goto-char (point-min))
378     (while cached
379       (while (and (not (eobp))
380                   (< (read (current-buffer)) (car cached)))
381         (forward-line 1))
382       (beginning-of-line)
383       (save-excursion
384         (set-buffer cache-buf)
385         (if (search-forward (concat "\n" (int-to-string (car cached)) "\t")
386                             nil t)
387             (setq beg (progn (beginning-of-line) (point))
388                   end (progn (end-of-line) (point)))
389           (setq beg nil)))
390       (if beg (progn (insert-buffer-substring cache-buf beg end)
391                      (insert "\n")))
392       (setq cached (cdr cached)))
393     (kill-buffer cache-buf)))
394
395 (defun gnus-cache-braid-heads (group cached)
396   (let ((cache-buf (get-buffer-create " *gnus-cache*")))
397     (save-excursion
398       (set-buffer cache-buf)
399       (buffer-disable-undo (current-buffer))
400       (erase-buffer))
401     (set-buffer nntp-server-buffer)
402     (goto-char (point-min))
403     (while cached
404       (while (and (not (eobp))
405                   (looking-at "2.. +\\([0-9]+\\) ")
406                   (< (progn (goto-char (match-beginning 1))
407                             (read (current-buffer)))
408                      (car cached)))
409         (search-forward "\n.\n" nil 'move))
410       (beginning-of-line)
411       (save-excursion
412         (set-buffer cache-buf)
413         (erase-buffer)
414         (insert-file-contents (gnus-cache-file-name group (car cached)))
415         (goto-char (point-min))
416         (insert "220 " (int-to-string (car cached)) " Article retrieved.\n")
417         (search-forward "\n\n" nil 'move)
418         (delete-region (point) (point-max))
419         (forward-char -1)
420         (insert "."))
421       (insert-buffer-substring cache-buf)
422       (setq cached (cdr cached)))
423     (kill-buffer cache-buf)))
424
425 ;;;###autoload
426 (defun gnus-jog-cache ()
427   "Go through all groups and put the articles into the cache."
428   (interactive)
429   (let ((newsrc (cdr gnus-newsrc-alist))
430         (gnus-cache-enter-articles '(unread))
431         (gnus-mark-article-hook nil)
432         (gnus-expert-user t)
433         (gnus-large-newsgroup nil))
434     (while newsrc
435       (gnus-summary-read-group (car (car newsrc)))
436       (if (not (eq major-mode 'gnus-summary-mode))
437           ()
438         (while gnus-newsgroup-unreads
439           (gnus-summary-select-article t t nil (car gnus-newsgroup-unreads))
440           (setq gnus-newsgroup-unreads (cdr gnus-newsgroup-unreads)))
441         (kill-buffer (current-buffer)))
442       (setq newsrc (cdr newsrc)))))
443
444 (defun gnus-cache-read-active (&optional force)
445   "Read the cache active file."
446   (if (not (and (file-exists-p gnus-cache-active-file)
447                 (or force (not gnus-cache-active-hashtb))))
448       ;; There is no active file, so we generate one.
449       (gnus-cache-generate-active)
450     ;; We simply read the active file.
451     (save-excursion
452       (gnus-set-work-buffer)
453       (insert-file-contents gnus-cache-active-file)
454       (gnus-active-to-gnus-format
455        nil (setq gnus-cache-active-hashtb 
456                  (gnus-make-hashtable 
457                   (count-lines (point-min) (point-max)))))
458       (setq gnus-cache-active-altered nil))))
459        
460 (defun gnus-cache-write-active (&optional force)
461   "Write the active hashtb to the active file."
462   (when (or force
463             (and gnus-cache-active-hashtb
464                  gnus-cache-active-altered))
465     (save-excursion
466       (gnus-set-work-buffer)
467       (mapatoms
468        (lambda (sym)
469          (when (and sym (boundp sym))
470            (insert (format "%s %d %d y\n"
471                            (symbol-name sym) (cdr (symbol-value sym))
472                            (car (symbol-value sym))))))
473        gnus-cache-active-hashtb)
474       (write-region 
475        (point-min) (point-max) gnus-cache-active-file nil 'silent))
476     ;; Mark the active hashtb as unaltered.
477     (setq gnus-cache-active-altered nil)))
478
479 (defun gnus-cache-update-active (group number &optional low)
480   "Update the upper bound of the active info of GROUP to NUMBER.
481 If LOW, update the lower bound instead."
482   (let ((active (gnus-gethash group gnus-cache-active-hashtb)))
483     (if (null active)
484         ;; We just create a new active entry for this group.
485         (gnus-sethash group (cons number number) gnus-cache-active-hashtb)
486       ;; Update the lower or upper bound.
487       (if low
488           (setcar active number)
489         (setcdr active number))
490       ;; Mark the active hashtb as altered.
491       (setq gnus-cache-active-altered t))))
492
493 ;;;###autoload
494 (defun gnus-cache-generate-active (&optional directory)
495   "Generate the cache active file."
496   (interactive)
497   (let* ((top (null directory))
498          (directory (expand-file-name (or directory gnus-cache-directory)))
499          (files (directory-files directory 'full))
500          (group 
501           (progn
502             (string-match 
503              (concat "^" (file-name-as-directory
504                           (expand-file-name gnus-cache-directory)))
505              (file-name-as-directory directory))
506             (gnus-replace-chars-in-string 
507              (substring (file-name-as-directory directory) (match-end 0))
508              ?/ ?.)))
509          nums alphs)
510     (when top
511       (gnus-message 5 "Generating the cache active file...")
512       (setq gnus-cache-active-hashtb (gnus-make-hashtable 123)))
513     ;; Separate articles from all other files and directories.
514     (while files
515       (if (string-match "^[0-9]+$" (file-name-nondirectory (car files)))
516           (push (string-to-int (file-name-nondirectory (pop files))) nums)
517         (push (pop files) alphs)))
518     ;; If we have nums, then this is probably a valid group.
519     (setq nums (sort nums '<))
520     (if nums
521         (gnus-sethash group (cons (car nums) (gnus-last-element nums))
522                       gnus-cache-active-hashtb))
523     ;; Go through all the other files.
524     (while alphs
525       (when (and (file-directory-p (car alphs))
526                  (not (string-match "^\\.\\.?$"
527                                     (file-name-nondirectory (car alphs)))))
528         ;; We descend directories.
529         (gnus-cache-generate-active (car alphs)))
530       (setq alphs (cdr alphs)))
531     ;; Write the new active file.
532     (when top
533       (gnus-cache-write-active t)
534       (gnus-message 5 "Generating the cache active file...done"))))
535
536 ;;;###autoload
537 (defun gnus-cache-generate-nov-databases (dir)
538   "Generate NOV files recursively starting in DIR."
539   (interactive (list gnus-cache-directory))
540   (gnus-cache-close)
541   (let ((nnml-generate-active-function 'identity))
542     (nnml-generate-nov-databases-1 dir)))
543
544 (provide 'gnus-cache)
545               
546 ;;; gnus-cache.el ends here