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