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