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