*** empty log message ***
[gnus] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Gnus
2 ;; Copyright (C) 1997 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 the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'gnus)
29 (require 'gnus-cache)
30 (require 'nnvirtual)
31 (require 'gnus-sum)
32 (eval-when-compile (require 'cl))
33
34 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
35   "Where the Gnus agent will store its files."
36   :group 'gnus-agent
37   :type 'directory)
38
39 (defcustom gnus-agent-plugged-hook nil
40   "Hook run when plugging into the network."
41   :group 'gnus-agent
42   :type 'hook)
43
44 (defcustom gnus-agent-unplugged-hook nil
45   "Hook run when unplugging from the network."
46   :group 'gnus-agent
47   :type 'hook)
48
49 ;;; Internal variables
50
51 (defvar gnus-agent-history-buffers nil)
52 (defvar gnus-agent-buffer-alist nil)
53 (defvar gnus-agent-article-alist nil)
54 (defvar gnus-agent-group-alist nil)
55 (defvar gnus-agent-covered-methods nil)
56 (defvar gnus-category-alist nil)
57 (defvar gnus-agent-current-history nil)
58 (defvar gnus-agent-overview-buffer nil)
59 (defvar gnus-category-predicate-cache nil)
60 (defvar gnus-category-group-cache nil)
61 (defvar gnus-agent-spam-hashtb nil)
62 (defvar gnus-agent-file-name nil)
63 (defvar gnus-agent-send-mail-function nil)
64
65 (defvar gnus-plugged t
66   "Whether Gnus is plugged or not.")
67
68 ;; Dynamic variables
69 (defvar gnus-headers)
70 (defvar gnus-score)
71
72 ;;;
73 ;;; Setup
74 ;;;
75
76 (defun gnus-open-agent ()
77   (setq gnus-agent t)
78   (gnus-agent-read-servers)
79   (gnus-category-read)
80   (setq gnus-agent-overview-buffer
81         (get-buffer-create " *Gnus agent overview*"))
82   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
83   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
84   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
85
86 (gnus-add-shutdown 'gnus-close-agent 'gnus)
87
88 (defun gnus-close-agent ()
89   (setq gnus-agent-covered-methods nil
90         gnus-category-predicate-cache nil
91         gnus-category-group-cache nil
92         gnus-agent-spam-hashtb nil)
93   (gnus-kill-buffer gnus-agent-overview-buffer))
94
95 ;;;
96 ;;; Utility functions
97 ;;;
98
99 (defun gnus-agent-read-file (file)
100   "Load FILE and do a `read' there."
101   (nnheader-temp-write nil
102     (ignore-errors
103       (insert-file-contents file)
104       (goto-char (point-min))
105       (read (current-buffer)))))
106
107 (defsubst gnus-agent-method ()
108   (concat (symbol-name (car gnus-command-method)) "/"
109           (if (equal (cadr gnus-command-method) "")
110               "unnamed"
111             (cadr gnus-command-method))))
112
113 (defsubst gnus-agent-directory ()
114   "Path of the Gnus agent directory."
115   (nnheader-concat gnus-agent-directory (gnus-agent-method) "/"))
116
117 (defun gnus-agent-lib-file (file)
118   "The full path of the Gnus agent library FILE."
119   (concat (gnus-agent-directory) "lib/" file))
120
121 ;;;
122 ;;; Mode infestation
123 ;;;
124
125 (defvar gnus-agent-mode-hook nil
126   "Hook run when installing agent mode.")
127
128 (defvar gnus-agent-mode nil)
129 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
130
131 (defun gnus-agent-mode ()
132   "Minor mode for providing a agent support in Gnus buffers."
133   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
134                                       (symbol-name major-mode))
135                         (match-string 1 (symbol-name major-mode))))
136          (mode (intern (format "gnus-agent-%s-mode" buffer))))
137     (set (make-local-variable 'gnus-agent-mode) t)
138     (set mode nil)
139     (set (make-local-variable mode) t)
140     ;; Set up the menu.
141     (when (gnus-visual-p 'agent-menu 'menu)
142       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
143     (unless (assq 'gnus-agent-mode minor-mode-alist)
144       (push gnus-agent-mode-status minor-mode-alist))
145     (unless (assq mode minor-mode-map-alist)
146       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
147                                                      buffer))))
148             minor-mode-map-alist))
149     (gnus-agent-toggle-plugged gnus-plugged)
150     (run-hooks 'gnus-agent-mode-hook)))
151
152 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
153 (gnus-define-keys gnus-agent-group-mode-map
154   "Ju" gnus-agent-fetch-group
155   "Jc" gnus-enter-category-buffer
156   "Jj" gnus-agent-toggle-plugged
157   "Js" gnus-agent-fetch-session
158   "Ja" gnus-agent-add-group)
159
160 (defun gnus-agent-group-make-menu-bar ()
161   (unless (boundp 'gnus-agent-group-menu)
162     (easy-menu-define
163      gnus-agent-group-menu gnus-agent-group-mode-map ""
164      '("Agent"
165        ["Toggle plugged" gnus-agent-toggle-plugged t]
166        ["List categories" gnus-enter-category-buffer t]
167        ("Fetch"
168         ["Group" gnus-agent-fetch-group t])))))
169
170 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
171 (gnus-define-keys gnus-agent-summary-mode-map
172   "Jj" gnus-agent-toggle-plugged
173   "J#" gnus-agent-mark-article
174   "J\M-#" gnus-agent-unmark-article
175   "@" gnus-agent-toggle-mark
176   "Jc" gnus-agent-catchup)
177
178 (defun gnus-agent-summary-make-menu-bar ()
179   (unless (boundp 'gnus-agent-summary-menu)
180     (easy-menu-define
181      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
182      '("Agent"
183        ["Toggle plugged" gnus-agent-toggle-plugged t]
184        ["Mark as downloadable" gnus-agent-mark-article t]
185        ["Unmark as downloadable" gnus-agent-unmark-article t]
186        ["Toggle mark" gnus-agent-toggle-mark t]
187        ["Catchup undownloaded" gnus-agent-catchup t]))))
188
189 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
190 (gnus-define-keys gnus-agent-server-mode-map
191   "Jj" gnus-agent-toggle-plugged
192   "Ja" gnus-agent-add-server
193   "Jr" gnus-agent-remove-server)
194
195 (defun gnus-agent-server-make-menu-bar ()
196   (unless (boundp 'gnus-agent-server-menu)
197     (easy-menu-define
198      gnus-agent-server-menu gnus-agent-server-mode-map ""
199      '("Agent"
200        ["Toggle plugged" gnus-agent-toggle-plugged t]
201        ["Add" gnus-agent-add-server t]
202        ["Remove" gnus-agent-remove-server t]))))
203
204 (defun gnus-agent-toggle-plugged (plugged)
205   "Toggle whether Gnus is unplugged or not."
206   (interactive (list (not gnus-plugged)))
207   (if plugged
208       (progn
209         (run-hooks 'gnus-agent-plugged-hook)
210         (setcar (cdr gnus-agent-mode-status) " Plugged"))
211     (gnus-agent-close-connections)
212     (run-hooks 'gnus-agent-unplugged-hook)
213     (setcar (cdr gnus-agent-mode-status) " Unplugged"))
214   (setq gnus-plugged plugged)
215   (set-buffer-modified-p t))
216
217 (defun gnus-agent-close-connections ()
218   "Close all methods covered by the Gnus agent."
219   (let ((methods gnus-agent-covered-methods))
220     (while methods
221       (gnus-close-server (pop methods)))))
222
223 ;;;###autoload
224 (defun gnus-unplugged ()
225   "Start Gnus unplugged."
226   (interactive)
227   (setq gnus-plugged nil)
228   (gnus))
229
230 ;;;###autoload
231 (defun gnus-agentize ()
232   "Allow Gnus to be an offline newsreader.
233 The normal usage of this command is to put the following as the
234 last form in your `.gnus.el' file:
235
236 \(gnus-agentize)
237
238 This will modify the `gnus-before-startup-hook', `gnus-post-method',
239 and `message-send-mail-function' variables, and install the Gnus
240 agent minor mode in all Gnus buffers."
241   (interactive)
242   (add-hook 'gnus-before-startup-hook 'gnus-open-agent)
243   (setq gnus-agent-send-mail-function message-send-mail-function
244         message-send-mail-function 'gnus-agent-send-mail))
245
246 (defun gnus-agent-send-mail ()
247   (if gnus-plugged
248       (funcall gnus-agent-send-mail-function)
249     (goto-char (point-min))
250     (re-search-forward
251      (concat "^" (regexp-quote mail-header-separator) "\n"))
252     (replace-match "\n")
253     (gnus-request-accept-article "nndraft:drafts")))
254
255 ;;;
256 ;;; Group mode commands
257 ;;;
258
259 (defun gnus-agent-fetch-group (group)
260   "Put all new articles in GROUP into the agent."
261   (interactive (list (gnus-group-group-name)))
262   (unless group
263     (error "No group on the current line"))
264   (let ((articles (gnus-list-of-unread-articles group))
265         (gnus-command-method (gnus-find-method-for-group group)))
266     (gnus-agent-with-fetch
267       (gnus-agent-fetch-articles group articles))))
268
269 (defun gnus-agent-add-group (category arg)
270   "Add the current group to an agent category."
271   (interactive
272    (list
273     (intern
274      (completing-read
275       "Add to category: "
276       (mapcar (lambda (cat) (list (symbol-name (car cat))))
277               gnus-category-alist)
278       nil t))
279     current-prefix-arg))
280   (let ((cat (assq category gnus-category-alist))
281         c groups)
282     (gnus-group-iterate arg
283       (lambda (group)
284         (when (cadddr (setq c (gnus-group-category group)))
285           (setf (cadddr c) (delete group (cadddr c))))
286         (push group groups)))
287     (setf (cadddr cat) (nconc (cadddr cat) groups))
288     (gnus-category-write)))
289
290 ;;;
291 ;;; Server mode commands
292 ;;;
293
294 (defun gnus-agent-add-server (server)
295   "Enroll SERVER in the agent program."
296   (interactive (list (gnus-server-server-name)))
297   (unless server
298     (error "No server on the current line"))
299   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
300     (when (member method gnus-agent-covered-methods)
301       (error "Server already in the agent program"))
302     (push method gnus-agent-covered-methods)
303     (gnus-agent-write-servers)
304     (message "Entered %s into the agent" server)))
305
306 (defun gnus-agent-remove-server (server)
307   "Remove SERVER from the agent program."
308   (interactive (list (gnus-server-server-name)))
309   (unless server
310     (error "No server on the current line"))
311   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
312     (unless (member method gnus-agent-covered-methods)
313       (error "Server not in the agent program"))
314     (setq gnus-agent-covered-methods
315           (delete method gnus-agent-covered-methods))
316     (gnus-agent-write-servers)
317     (message "Removed %s from the agent" server)))
318
319 (defun gnus-agent-read-servers ()
320   "Read the alist of covered servers."
321   (setq gnus-agent-covered-methods
322         (gnus-agent-read-file
323          (nnheader-concat gnus-agent-directory "lib/servers"))))
324
325 (defun gnus-agent-write-servers ()
326   "Write the alist of covered servers."
327   (nnheader-temp-write (nnheader-concat gnus-agent-directory "lib/servers")
328     (prin1 gnus-agent-covered-methods (current-buffer))))
329
330 ;;;
331 ;;; Summary commands
332 ;;;
333
334 (defun gnus-agent-mark-article (n &optional unmark)
335   "Mark the next N articles as downloadable.
336 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
337 the mark instead.  The difference between N and the actual number of
338 articles marked is returned."
339   (interactive "p")
340   (gnus-set-global-variables)
341   (let ((backward (< n 0))
342         (n (abs n)))
343     (while (and
344             (> n 0)
345             (progn
346               (gnus-summary-set-agent-mark
347                (gnus-summary-article-number) unmark)
348               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
349       (setq n (1- n)))
350     (when (/= 0 n)
351       (gnus-message 7 "No more articles"))
352     (gnus-summary-recenter)
353     (gnus-summary-position-point)
354     n))
355
356 (defun gnus-agent-unmark-article (n)
357   "Remove the downloadable mark from the next N articles.
358 If N is negative, unmark backward instead.  The difference between N and
359 the actual number of articles unmarked is returned."
360   (interactive "p")
361   (gnus-set-global-variables)
362   (gnus-agent-mark-article n t))
363
364 (defun gnus-agent-toggle-mark (n)
365   "Toggle the downloadable mark from the next N articles.
366 If N is negative, toggle backward instead.  The difference between N and
367 the actual number of articles toggled is returned."
368   (interactive "p")
369   (gnus-set-global-variables)
370   (gnus-agent-mark-article n 'toggle))
371
372 (defun gnus-summary-set-agent-mark (article &optional unmark)
373   "Mark ARTICLE as downloadable."
374   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
375                     (memq article gnus-newsgroup-downloadable)
376                   unmark)))
377     (setq gnus-newsgroup-downloadable
378           (delq article gnus-newsgroup-downloadable))
379     (unless unmark
380       (push article gnus-newsgroup-downloadable))
381     (gnus-summary-update-mark
382      (if unmark gnus-undownloaded-mark gnus-downloadable-mark)
383      'unread)))
384
385 (defun gnus-agent-get-undownloaded-list ()
386   "Mark all unfetched articles as read."
387   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
388     (when (and (not gnus-plugged)
389                (gnus-agent-method-p gnus-command-method))
390       (gnus-agent-load-alist gnus-newsgroup-name)
391       (let ((articles gnus-newsgroup-unreads)
392             article)
393         (while (setq article (pop articles))
394           (unless (or (cdr (assq article gnus-agent-article-alist))
395                   (memq article gnus-newsgroup-downloadable))
396             (push article gnus-newsgroup-undownloaded)))))))
397
398 (defun gnus-agent-catchup ()
399   "Mark all undownloaded articles as read."
400   (interactive)
401   (save-excursion
402     (while gnus-newsgroup-undownloaded
403       (gnus-summary-mark-article
404        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
405   (gnus-summary-position-point))
406
407 ;;;
408 ;;; Internal functions
409 ;;;
410
411 (defun gnus-agent-save-active (method)
412   (when (gnus-agent-method-p method)
413     (let* ((gnus-command-method method)
414            (file (gnus-agent-lib-file "active")))
415       (gnus-make-directory (file-name-directory file))
416       (write-region (point-min) (point-max) file nil 'silent)
417       (when (file-exists-p (gnus-agent-lib-file "groups"))
418         (delete-file (gnus-agent-lib-file "groups"))))))
419
420 (defun gnus-agent-save-groups (method)
421   (let* ((gnus-command-method method)
422          (file (gnus-agent-lib-file "groups")))
423     (gnus-make-directory (file-name-directory file))
424     (write-region (point-min) (point-max) file nil 'silent))
425     (when (file-exists-p (gnus-agent-lib-file "active"))
426       (delete-file (gnus-agent-lib-file "active"))))
427
428 (defun gnus-agent-group-path (group)
429   "Translate GROUP into a path."
430   (nnheader-replace-chars-in-string group ?. ?/))
431
432 \f
433
434 (defun gnus-agent-method-p (method)
435   "Say whether METHOD is covered by the agent."
436   (member method gnus-agent-covered-methods))
437
438 (defun gnus-agent-get-function (method)
439   (if (and (not gnus-plugged)
440            (gnus-agent-method-p method))
441       (progn
442         (require 'nnagent)
443         'nnagent)
444     (car method)))
445
446 ;;; History functions
447
448 (defun gnus-agent-history-buffer ()
449   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
450
451 (defun gnus-agent-open-history ()
452   (save-excursion
453     (push (cons (gnus-agent-method)
454                 (set-buffer (get-buffer-create
455                              (format " *Gnus agent %s history*"
456                                      (gnus-agent-method)))))
457           gnus-agent-history-buffers)
458     (erase-buffer)
459     (insert "\n")
460     (let ((file (gnus-agent-lib-file "history")))
461       (when (file-exists-p file)
462         (insert-file file))
463       (set (make-local-variable 'gnus-agent-file-name) file))))
464
465 (defun gnus-agent-save-history ()
466   (save-excursion
467     (set-buffer gnus-agent-current-history)
468     (gnus-make-directory (file-name-directory gnus-agent-file-name))
469     (write-region (1+ (point-min)) (point-max)
470                   gnus-agent-file-name nil 'silent)))
471
472 (defun gnus-agent-close-history ()
473   (when (gnus-buffer-live-p gnus-agent-current-history)
474     (kill-buffer gnus-agent-current-history)
475     (setq gnus-agent-history-buffers
476           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
477                 gnus-agent-history-buffers))))
478
479 (defun gnus-agent-enter-history (id group-arts date)
480   (save-excursion
481     (set-buffer gnus-agent-current-history)
482     (goto-char (point-max))
483     (insert id "\t" (number-to-string date) "\t")
484     (while group-arts
485       (insert (caar group-arts) "/" (number-to-string (cdr (pop group-arts)))
486               " "))
487     (insert "\n")))
488
489 (defun gnus-agent-article-in-history-p (id)
490   (save-excursion
491     (set-buffer (gnus-agent-history-buffer))
492     (goto-char (point-min))
493     (search-forward (concat "\n" id "\t") nil t)))
494
495 (defun gnus-agent-history-path (id)
496   (save-excursion
497     (set-buffer (gnus-agent-history-buffer))
498     (goto-char (point-min))
499     (when (search-forward (concat "\n" id "\t") nil t)
500       (let ((method (gnus-agent-method)))
501         (let (paths group)
502           (while (not (numberp (setq group (read (current-buffer)))))
503             (push (concat method "/" group) paths))
504           (nreverse paths))))))
505
506 ;;;
507 ;;; Fetching
508 ;;;
509
510 (defun gnus-agent-start-fetch ()
511   "Initialize data structures for efficient fetching."
512   (gnus-agent-open-history)
513   (setq gnus-agent-current-history (gnus-agent-history-buffer)))
514
515 (defun gnus-agent-stop-fetch ()
516   "Save all data structures and clean up."
517   (gnus-agent-save-history)
518   (gnus-agent-close-history)
519   (setq gnus-agent-spam-hashtb nil)
520   (save-excursion
521     (set-buffer nntp-server-buffer)
522     (widen)))
523
524 (defmacro gnus-agent-with-fetch (&rest forms)
525   "Do FORMS safely."
526   `(unwind-protect
527        (progn
528          (gnus-agent-start-fetch)
529          ,@forms)
530      (gnus-agent-stop-fetch)))
531
532 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
533 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
534
535 (defun gnus-agent-fetch-articles (group articles)
536   "Fetch ARTICLES from GROUP and put them into the agent."
537   (when articles
538     ;; Prune off articles that we have already fetched.
539     (while (and articles
540                 (cdr (assq (car articles) gnus-agent-article-alist)))
541       (pop articles))
542     (let ((arts articles))
543       (while (cdr arts)
544         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
545             (setcdr arts (cddr arts))
546           (setq arts (cdr arts)))))
547     (when articles
548       (let ((dir (concat
549                   (gnus-agent-directory)
550                   (gnus-agent-group-path group) "/"))
551             (date (gnus-time-to-day (current-time)))
552             (case-fold-search t)
553             pos alists crosses id elem)
554         (gnus-make-directory dir)
555         (gnus-message 7 "Fetching articles for %s..." group)
556         ;; Fetch the articles from the backend.
557         (if (gnus-check-backend-function 'retrieve-articles group)
558             (setq pos (gnus-retrieve-articles articles group))
559           (nnheader-temp-write nil
560             (let ((buf (current-buffer))
561                   article)
562               (while (setq article (pop articles))
563                 (when (gnus-request-article article group)
564                   (goto-char (point-max))
565                   (push (cons article (point)) pos)
566                   (insert-buffer-substring nntp-server-buffer)))
567               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
568               (setq pos (nreverse pos)))))
569         ;; Then save these articles into the agent.
570         (save-excursion
571           (set-buffer nntp-server-buffer)
572           (while pos
573             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
574             (goto-char (point-min))
575             (when (search-forward "\n\n" nil t)
576               (when (search-backward "\nXrefs: " nil t)
577                 ;; Handle crossposting.
578                 (skip-chars-forward "^ ")
579                 (skip-chars-forward " ")
580                 (setq crosses nil)
581                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
582                   (push (cons (buffer-substring (match-beginning 1)
583                                                 (match-end 1))
584                               (buffer-substring (match-beginning 2)
585                                                 (match-end 2)))
586                         crosses)
587                   (goto-char (match-end 0)))
588                 (gnus-agent-crosspost crosses (caar pos))))
589             (goto-char (point-min))
590             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
591                 (setq id "No-Message-ID-in-article")
592               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
593             (write-region (point-min) (point-max)
594                           (concat dir (number-to-string (caar pos)))
595                           nil 'silent)
596             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
597               (setcdr elem t))
598             (gnus-agent-enter-history
599              id (or crosses (list (cons group (caar pos)))) date)
600             (widen)
601             (pop pos)))
602         (gnus-agent-save-alist group)))))
603
604 (defun gnus-agent-crosspost (crosses article)
605   (let (gnus-agent-article-alist group alist beg end)
606     (save-excursion
607       (set-buffer gnus-agent-overview-buffer)
608       (when (nnheader-find-nov-line article)
609         (forward-word 1)
610         (setq beg (point))
611         (setq end (progn (forward-line 1) (point)))))
612     (while crosses
613       (setq group (caar crosses))
614       (unless (setq alist (assoc group gnus-agent-group-alist))
615         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
616               gnus-agent-group-alist))
617       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
618       (save-excursion
619         (set-buffer (get-buffer-create (format " *Gnus agent overview %s*"
620                                                group)))
621         (when (= (point-max) (point-min))
622           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
623           (ignore-errors
624             (insert-file-contents
625              (gnus-agent-article-name ".overview" group))))
626         (nnheader-find-nov-line (string-to-number (cdar crosses)))
627         (insert (string-to-number (cdar crosses)))
628         (insert-buffer-substring gnus-agent-overview-buffer beg end))
629       (pop crosses))))
630
631 (defun gnus-agent-flush-cache ()
632   (save-excursion
633     (while gnus-agent-buffer-alist
634       (set-buffer (cdar gnus-agent-buffer-alist))
635       (write-region (point-min) (point-max)
636                     (gnus-agent-article-name ".overview"
637                                              (caar gnus-agent-buffer-alist))
638                      nil 'silent)
639       (pop gnus-agent-buffer-alist))
640     (while gnus-agent-group-alist
641       (nnheader-temp-write (caar gnus-agent-group-alist)
642         (princ (cdar gnus-agent-group-alist))
643         (insert "\n"))
644       (pop gnus-agent-group-alist))))
645
646 (defun gnus-agent-fetch-headers (group articles &optional force)
647   (gnus-agent-load-alist group)
648   ;; Find out what headers we need to retrieve.
649   (when articles
650     (while (and articles
651                 (assq (car articles) gnus-agent-article-alist))
652       (pop articles))
653     (let ((arts articles))
654       (while (cdr arts)
655         (if (assq (cadr arts) gnus-agent-article-alist)
656             (setcdr arts (cddr arts))
657           (setq arts (cdr arts)))))
658     ;; Fetch them.
659     (when articles
660       (gnus-message 7 "Fetching headers for %s..." group)
661       (save-excursion
662         (set-buffer nntp-server-buffer)
663         (unless (eq 'nov (gnus-retrieve-headers articles group))
664           (nnvirtual-convert-headers))
665         ;; Save these headers for later processing.
666         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
667         (let (file)
668           (when (file-exists-p
669                  (setq file (gnus-agent-article-name ".overview" group)))
670             (gnus-agent-braid-nov group articles file))
671           (gnus-make-directory (file-name-directory file))
672           (write-region (point-min) (point-max) file nil 'silent)
673           (gnus-agent-save-alist group articles nil))
674         t))))
675
676 (defsubst gnus-agent-copy-nov-line (article)
677   (let (b e)
678     (set-buffer gnus-agent-overview-buffer)
679     (setq b (point))
680     (if (eq article (read (current-buffer)))
681         (setq e (progn (forward-line 1) (point)))
682       (setq e b))
683     (set-buffer nntp-server-buffer)
684     (insert-buffer-substring gnus-agent-overview-buffer b e)))
685
686 (defun gnus-agent-braid-nov (group articles file)
687   (let (beg end)
688     (set-buffer gnus-agent-overview-buffer)
689     (goto-char (point-min))
690     (set-buffer nntp-server-buffer)
691     (erase-buffer)
692     (insert-file-contents file)
693     (goto-char (point-min))
694     (if (or (= (point-min) (point-max))
695             (progn
696               (forward-line -1)
697               (< (read (current-buffer)) (car articles))))
698         ;; We have only headers that are after the older headers,
699         ;; so we just append them.
700         (progn
701           (goto-char (point-max))
702           (insert-buffer-substring gnus-agent-overview-buffer))
703       ;; We do it the hard way.
704       (nnheader-find-nov-line (car articles))
705       (gnus-agent-copy-nov-line (car articles))
706       (pop articles)
707       (while (and articles
708                   (not (eobp)))
709         (while (and (not (eobp))
710                     (< (read (current-buffer)) (car articles)))
711           (forward-line 1))
712         (beginning-of-line)
713         (unless (eobp)
714           (gnus-agent-copy-nov-line (car articles))
715           (setq articles (cdr articles))))
716       (when articles
717         (let (b e)
718           (set-buffer gnus-agent-overview-buffer)
719           (setq b (point)
720                 e (point-max))
721           (set-buffer nntp-server-buffer)
722           (insert-buffer-substring gnus-agent-overview-buffer b e))))))
723
724 (defun gnus-agent-load-alist (group &optional dir)
725   "Load the article-state alist for GROUP."
726   (setq gnus-agent-article-alist
727         (gnus-agent-read-file
728          (if dir
729              (concat dir ".agentview")
730            (gnus-agent-article-name ".agentview" group)))))
731
732 (defun gnus-agent-save-alist (group &optional articles state dir)
733   "Load the article-state alist for GROUP."
734   (nnheader-temp-write (if dir
735                            (concat dir ".agentview")
736                          (gnus-agent-article-name ".agentview" group))
737     (princ (setq gnus-agent-article-alist
738                  (nconc gnus-agent-article-alist
739                         (mapcar (lambda (article) (cons article state))
740                                 articles)))
741            (current-buffer))
742     (insert "\n")))
743
744 (defun gnus-agent-article-name (article group)
745   (concat (gnus-agent-directory) (gnus-agent-group-path group) "/"
746           (if (stringp article) article (string-to-number article))))
747
748 (defun gnus-agent-fetch-session ()
749   "Fetch all articles and headers that are eligible for fetching."
750   (interactive)
751   (unless gnus-agent-covered-methods
752     (error "No servers are covered by the Gnus agent"))
753   (unless gnus-plugged
754     (error "Can't fetch articles while Gnus is unplugged"))
755   (let ((methods gnus-agent-covered-methods)
756         gnus-newsgroup-dependencies gnus-newsgroup-headers
757         gnus-newsgroup-scored
758         gnus-headers gnus-score
759         gnus-use-cache
760         gnus-command-method groups group articles score arts
761         category predicate info marks score-param)
762     (save-excursion
763       (while methods
764         (setq gnus-command-method (car methods)
765               groups (gnus-groups-from-server (pop methods)))
766         (gnus-agent-with-fetch
767           (while (setq group (pop groups))
768             ;; Fetch headers.
769             (when (and (setq articles (gnus-list-of-unread-articles group))
770                        (gnus-agent-fetch-headers group articles))
771               ;; Parse them and see which articles we want to fetch.
772               (setq gnus-newsgroup-dependencies
773                     (make-vector (length articles) 0))
774               (setq gnus-newsgroup-headers
775                     (gnus-get-newsgroup-headers-xover articles nil nil group))
776               (setq category (gnus-group-category group))
777               (setq predicate
778                     (gnus-get-predicate 
779                      (or (gnus-group-get-parameter group 'agent-predicate)
780                          (cadr category))))
781               (setq score-param
782                     (or (gnus-group-get-parameter group 'agent-score)
783                         (caddr category)))
784               (when score-param
785                 (gnus-score-headers (list (list score-param))))
786               (setq arts nil)
787               (while (setq gnus-headers (pop gnus-newsgroup-headers))
788                 (setq gnus-score
789                       (or (cdr (assq (mail-header-number gnus-headers)
790                                      gnus-newsgroup-scored))
791                           gnus-summary-default-score))
792                 (when (funcall predicate)
793                   (push (mail-header-number gnus-headers)
794                         arts)))
795               ;; Fetch the articles.
796               (when arts
797                 (gnus-agent-fetch-articles group arts)))
798             ;; Perhaps we have some additional articles to fetch.
799             (setq arts (assq 'download (gnus-info-marks
800                                         (setq info (gnus-get-info group)))))
801             (when (cdr arts)
802               (gnus-agent-fetch-articles
803                group (gnus-uncompress-range (cdr arts)))
804               (setq marks (delq arts (gnus-info-marks info)))
805               (gnus-info-set-marks info marks)))))
806       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
807
808 ;;;
809 ;;; Agent Category Mode
810 ;;;
811
812 (defvar gnus-category-mode-hook nil
813   "Hook run in `gnus-category-mode' buffers.")
814
815 (defvar gnus-category-line-format "     %(%20c%): %g\n"
816   "Format of category lines.")
817
818 (defvar gnus-category-mode-line-format "Gnus: %%b"
819   "The format specification for the category mode line.")
820
821 (defvar gnus-agent-short-article 100
822   "Articles that have fewer lines than this are short.")
823
824 (defvar gnus-agent-long-article 200
825   "Articles that have more lines than this are long.")
826
827 (defvar gnus-agent-low-score 0
828   "Articles that have a score lower than this have a low score.")
829
830 (defvar gnus-agent-high-score 0
831   "Articles that have a score higher than this have a high score.")
832
833
834 ;;; Internal variables.
835
836 (defvar gnus-category-buffer "*Agent Category*")
837
838 (defvar gnus-category-line-format-alist
839   `((?c name ?s)
840     (?g groups ?d)))
841
842 (defvar gnus-category-mode-line-format-alist
843   `((?u user-defined ?s)))
844
845 (defvar gnus-category-line-format-spec nil)
846 (defvar gnus-category-mode-line-format-spec nil)
847
848 (defvar gnus-category-mode-map nil)
849 (put 'gnus-category-mode 'mode-class 'special)
850
851 (unless gnus-category-mode-map
852   (setq gnus-category-mode-map (make-sparse-keymap))
853   (suppress-keymap gnus-category-mode-map)
854
855   (gnus-define-keys gnus-category-mode-map
856     "q" gnus-category-exit
857     "k" gnus-category-kill
858     "c" gnus-category-copy
859     "a" gnus-category-add
860     "p" gnus-category-edit-predicate
861     "g" gnus-category-edit-groups
862     "s" gnus-category-edit-score
863     "l" gnus-category-list
864
865     "\C-c\C-i" gnus-info-find-node
866     "\C-c\C-b" gnus-bug))
867
868 (defvar gnus-category-menu-hook nil
869   "*Hook run after the creation of the menu.")
870
871 (defun gnus-category-make-menu-bar ()
872   (gnus-turn-off-edit-menu 'category)
873   (unless (boundp 'gnus-category-menu)
874     (easy-menu-define
875      gnus-category-menu gnus-category-mode-map ""
876      '("Categories"
877        ["Add" gnus-category-add t]
878        ["Kill" gnus-category-kill t]
879        ["Copy" gnus-category-copy t]
880        ["Edit predicate" gnus-category-edit-predicate t]
881        ["Edit score" gnus-category-edit-score t]
882        ["Edit groups" gnus-category-edit-groups t]
883        ["Exit" gnus-category-exit t]))
884
885     (run-hooks 'gnus-category-menu-hook)))
886
887 (defun gnus-category-mode ()
888   "Major mode for listing and editing agent categories.
889
890 All normal editing commands are switched off.
891 \\<gnus-category-mode-map>
892 For more in-depth information on this mode, read the manual
893 (`\\[gnus-info-find-node]').
894
895 The following commands are available:
896
897 \\{gnus-category-mode-map}"
898   (interactive)
899   (when (gnus-visual-p 'category-menu 'menu)
900     (gnus-category-make-menu-bar))
901   (kill-all-local-variables)
902   (gnus-simplify-mode-line)
903   (setq major-mode 'gnus-category-mode)
904   (setq mode-name "Category")
905   (gnus-set-default-directory)
906   (setq mode-line-process nil)
907   (use-local-map gnus-category-mode-map)
908   (buffer-disable-undo (current-buffer))
909   (setq truncate-lines t)
910   (setq buffer-read-only t)
911   (run-hooks 'gnus-category-mode-hook))
912
913 (defalias 'gnus-category-position-point 'gnus-goto-colon)
914
915 (defun gnus-category-insert-line (category)
916   (let* ((name (car category))
917          (groups (length (cadddr category))))
918     (beginning-of-line)
919     (gnus-add-text-properties
920      (point)
921      (prog1 (1+ (point))
922        ;; Insert the text.
923        (eval gnus-category-line-format-spec))
924      (list 'gnus-category name))))
925
926 (defun gnus-enter-category-buffer ()
927   "Go to the Category buffer."
928   (interactive)
929   (gnus-category-setup-buffer)
930   (gnus-configure-windows 'category)
931   (gnus-category-prepare))
932
933 (defun gnus-category-setup-buffer ()
934   (unless (get-buffer gnus-category-buffer)
935     (save-excursion
936       (set-buffer (get-buffer-create gnus-category-buffer))
937       (gnus-add-current-to-buffer-list)
938       (gnus-category-mode))))
939
940 (defun gnus-category-prepare ()
941   (gnus-set-format 'category-mode)
942   (gnus-set-format 'category t)
943   (let ((alist gnus-category-alist)
944         (buffer-read-only nil))
945     (erase-buffer)
946     (while alist
947       (gnus-category-insert-line (pop alist)))
948     (goto-char (point-min))
949     (gnus-category-position-point)))
950
951 (defun gnus-category-name ()
952   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
953       (error "No category on the current line")))
954
955 (defun gnus-category-read ()
956   "Read the category alist."
957   (setq gnus-category-alist
958         (or (gnus-agent-read-file
959              (nnheader-concat gnus-agent-directory "lib/categories"))
960             (list (list 'default 'true nil nil)))))
961     
962 (defun gnus-category-write ()
963   "Write the category alist."
964   (setq gnus-category-predicate-cache nil
965         gnus-category-group-cache nil)
966   (nnheader-temp-write (nnheader-concat gnus-agent-directory "lib/categories")
967     (prin1 gnus-category-alist (current-buffer))))
968
969 (defun gnus-category-edit-predicate (category)
970   "Edit the predicate for CATEGORY."
971   (interactive (list (gnus-category-name)))
972   (let ((info (assq category gnus-category-alist)))
973     (gnus-edit-form
974      (cadr info) (format "Editing the predicate for category %s" category)
975      `(lambda (predicate)
976         (setf (cadr (assq ',category gnus-category-alist)) predicate)
977         (gnus-category-write)
978         (gnus-category-list)))))
979   
980 (defun gnus-category-edit-score (category)
981   "Edit the score expression for CATEGORY."
982   (interactive (list (gnus-category-name)))
983   (let ((info (assq category gnus-category-alist)))
984     (gnus-edit-form
985      (caddr info)
986      (format "Editing the score expression for category %s" category)
987      `(lambda (groups)
988         (setf (caddr (assq ',category gnus-category-alist)) groups)
989         (gnus-category-write)
990         (gnus-category-list)))))
991
992 (defun gnus-category-edit-groups (category)
993   "Edit the group list for CATEGORY."
994   (interactive (list (gnus-category-name)))
995   (let ((info (assq category gnus-category-alist)))
996     (gnus-edit-form
997      (cadddr info) (format "Editing the group list for category %s" category)
998      `(lambda (groups)
999         (setf (cadddr (assq ',category gnus-category-alist)) groups)
1000         (gnus-category-write)
1001         (gnus-category-list)))))
1002
1003 (defun gnus-category-kill (category)
1004   "Kill the current category."
1005   (interactive (list (gnus-category-name)))
1006   (let ((info (assq category gnus-category-alist))
1007         (buffer-read-only nil))
1008     (gnus-delete-line)
1009     (gnus-category-write)
1010     (setq gnus-category-alist (delq info gnus-category-alist))))
1011
1012 (defun gnus-category-copy (category to)
1013   "Copy the current category."
1014   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1015   (let ((info (assq category gnus-category-alist)))
1016     (push (list to (gnus-copy-sequence (cadr info))
1017                 (gnus-copy-sequence (caddr info)) nil)
1018           gnus-category-alist)
1019     (gnus-category-write)
1020     (gnus-category-list)))
1021
1022 (defun gnus-category-add (category)
1023   "Create a new category."
1024   (interactive "SCategory name: ")
1025   (when (assq category gnus-category-alist)
1026     (error "Category %s already exists" category))
1027   (push (list category 'true nil nil)
1028         gnus-category-alist)
1029   (gnus-category-write)
1030   (gnus-category-list))
1031
1032 (defun gnus-category-list ()
1033   "List all categories."
1034   (interactive)
1035   (gnus-category-prepare))
1036
1037 (defun gnus-category-exit ()
1038   "Return to the group buffer."
1039   (interactive)
1040   (kill-buffer (current-buffer))
1041   (gnus-configure-windows 'group t))
1042
1043 ;; To avoid having 8-bit characters in the source file.
1044 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1045
1046 (defvar gnus-category-predicate-alist
1047   '((spam . gnus-agent-spam-p)
1048     (short . gnus-agent-short-p)
1049     (long . gnus-agent-long-p)
1050     (low . gnus-agent-low-scored-p)
1051     (high . gnus-agent-high-scored-p)
1052     (true . gnus-agent-true)
1053     (false . gnus-agent-false))
1054   "Mapping from short score predicate symbols to predicate functions.")
1055
1056 (defun gnus-agent-spam-p ()
1057   "Say whether an article is spam or not."
1058   (unless gnus-agent-spam-hashtb
1059     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1060   (if (not (equal (mail-header-references gnus-headers) ""))
1061       nil
1062     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1063       (prog1
1064           (gnus-gethash string gnus-agent-spam-hashtb)
1065         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1066
1067 (defun gnus-agent-short-p ()
1068   "Say whether an article is short or not."
1069   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1070
1071 (defun gnus-agent-long-p ()
1072   "Say whether an article is long or not."
1073   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1074
1075 (defun gnus-agent-low-scored-p ()
1076   "Say whether an article has a low score or not."
1077   (< gnus-score gnus-agent-low-score))
1078
1079 (defun gnus-agent-high-scored-p ()
1080   "Say whether an article has a high score or not."
1081   (> gnus-score gnus-agent-low-score))
1082
1083 (defun gnus-category-make-function (cat)
1084   "Make a function from category CAT."
1085   `(lambda () ,(gnus-category-make-function-1 cat)))
1086
1087 (defun gnus-agent-true ()
1088   "Return t."
1089   t)
1090
1091 (defun gnus-agent-false ()
1092   "Return nil."
1093   nil)
1094   
1095 (defun gnus-category-make-function-1 (cat)
1096   "Make a function from category CAT."
1097   (cond
1098    ;; Functions are just returned as is.
1099    ((or (symbolp cat)
1100         (gnus-functionp cat))
1101     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1102            cat)))
1103    ;; More complex category.
1104    ((consp cat)
1105     `(,(cond
1106         ((memq (car cat) '(& and))
1107          'and)
1108         ((memq (car cat) '(| or))
1109          'or)
1110         ((memq (car cat) gnus-category-not)
1111          'not))
1112       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1113    (t
1114     (error "Unknown category type: %s" cat))))
1115
1116 (defun gnus-get-predicate (predicate)
1117   "Return the predicate for CATEGORY."
1118   (or (cdr (assoc predicate gnus-category-predicate-cache))
1119       (cdar (push (cons predicate
1120                         (gnus-category-make-function predicate))
1121                   gnus-category-predicate-cache))))
1122
1123 (defun gnus-group-category (group)
1124   "Return the category GROUP belongs to."
1125   (unless gnus-category-group-cache
1126     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1127     (let ((cs gnus-category-alist)
1128           groups cat)
1129       (while (setq cat (pop cs))
1130         (setq groups (cadddr cat))
1131         (while groups
1132           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1133   (or (gnus-gethash group gnus-category-group-cache)
1134       (assq 'default gnus-category-alist)))
1135
1136 (defun gnus-agent-expire ()
1137   "Expire all old articles."
1138   (interactive)
1139   (let ((methods gnus-agent-covered-methods)
1140         (alist (cdr gnus-newsrc-alist))
1141         gnus-command-method ofiles info method file group)
1142     (while (setq gnus-command-method (pop methods))
1143       (setq ofiles (nconc ofiles (gnus-agent-expire-directory
1144                                   (gnus-agent-directory)))))
1145     (while (setq info (pop alist))
1146       (when (and (gnus-agent-method-p
1147                   (setq gnus-command-method
1148                         (gnus-find-method-for-group
1149                          (setq group (gnus-info-group info)))))
1150                  (member
1151                   (setq file
1152                         (concat
1153                          (gnus-agent-directory)
1154                          (gnus-agent-group-path group) "/.overview"))
1155                   ofiles))
1156         (setq ofiles (delete file ofiles))
1157         (gnus-agent-expire-group file group)))
1158     (while ofiles
1159       (gnus-agent-expire-group (pop ofiles)))))
1160
1161 (defun gnus-agent-expire-directory (dir)
1162   "Expire all groups in DIR recursively."
1163   (when (file-directory-p dir)
1164     (let ((files (directory-files dir t))
1165           file ofiles)
1166       (while (setq file (pop files))
1167         (cond
1168          ((member (file-name-nondirectory file) '("." ".."))
1169           ;; Do nothing.
1170           )
1171          ((file-directory-p file)
1172           ;; Recurse.
1173           (setq ofiles (nconc ofiles (gnus-agent-expire-directory file))))
1174          ((string-match "\\.overview$" file)
1175           ;; Expire group.
1176           (push file ofiles))))
1177       ofiles)))
1178
1179 (defun gnus-agent-expire-group (overview &optional group)
1180   "Expire articles in OVERVIEW."
1181   (gnus-message 5 "Expiring %s..." overview)
1182   (let ((odate (- (gnus-time-to-day (current-time)) 4))
1183         (dir (file-name-directory overview))
1184         (info (when group (gnus-get-info group)))
1185         headers article file point unreads)
1186     (gnus-agent-load-alist nil dir)
1187     (when info
1188       (setq unreads
1189             (nconc
1190              (gnus-list-of-unread-articles group)
1191              (gnus-uncompress-range
1192               (cdr (assq 'tick (gnus-info-marks info))))
1193              (gnus-uncompress-range
1194               (cdr (assq 'dormant (gnus-info-marks info)))))))
1195     (nnheader-temp-write overview
1196       (insert-file-contents overview)
1197       (goto-char (point-min))
1198       (while (not (eobp))
1199         (setq point (point))
1200         (condition-case ()
1201             (setq headers (inline (nnheader-parse-nov)))
1202           (error
1203            (goto-char point)
1204            (gnus-delete-line)
1205            (setq headers nil)))
1206         (when headers
1207           (unless (memq (setq article (mail-header-number headers)) unreads)
1208             (if (not (< (inline
1209                           (gnus-time-to-day
1210                            (inline (nnmail-date-to-time
1211                                     (mail-header-date headers)))))
1212                         odate))
1213                 (forward-line 1)              
1214               (gnus-delete-line)
1215               (setq gnus-agent-article-alist
1216                     (delq (assq article gnus-agent-article-alist)
1217                           gnus-agent-article-alist))
1218               (when (file-exists-p
1219                      (setq file (concat dir (number-to-string article))))
1220                 (delete-file file))))))
1221       (gnus-agent-save-alist nil nil nil dir))))
1222    
1223 (provide 'gnus-agent)
1224
1225 ;;; gnus-agent.el ends here