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