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