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