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