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