4a7ca17140f7095c95ec76157ecd9aa49767d489
[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
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
537            gnus-agent-file-coding-system))
538       (write-region (point-min) (point-max) file nil 'silent))
539
540     );;<-- correct?
541
542     (when (file-exists-p (gnus-agent-lib-file "active"))
543       (delete-file (gnus-agent-lib-file "active"))))
544 ;  )
545
546 (defun gnus-agent-save-group-info (method group active)
547   (when (gnus-agent-method-p method)
548     (let* ((gnus-command-method method)
549            (file (if nntp-server-list-active-group
550                      (gnus-agent-lib-file "active")
551                    (gnus-agent-lib-file "groups"))))
552       (gnus-make-directory (file-name-directory file))
553       (with-temp-file file
554         (when (file-exists-p file)
555           (nnheader-insert-file-contents file))
556         (goto-char (point-min))
557         (if nntp-server-list-active-group
558             (progn
559               (when (re-search-forward
560                      (concat "^" (regexp-quote group) " ") nil t)
561                 (gnus-delete-line))
562               (insert group " " (number-to-string (cdr active)) " "
563                       (number-to-string (car active)) "\n"))
564           (when (re-search-forward (concat (regexp-quote group) " ") nil t)
565             (gnus-delete-line))
566           (insert-buffer-substring nntp-server-buffer))))))
567
568 (defun gnus-agent-group-path (group)
569   "Translate GROUP into a path."
570   (if nnmail-use-long-file-names
571       (gnus-group-real-name group)
572     (nnheader-replace-chars-in-string
573      (nnheader-translate-file-chars (gnus-group-real-name group))
574      ?. ?/)))
575
576 \f
577
578 (defun gnus-agent-method-p (method)
579   "Say whether METHOD is covered by the agent."
580   (member method gnus-agent-covered-methods))
581
582 (defun gnus-agent-get-function (method)
583   (if (and (not gnus-plugged)
584            (gnus-agent-method-p method))
585       (progn
586         (require 'nnagent)
587         'nnagent)
588     (car method)))
589
590 ;;; History functions
591
592 (defun gnus-agent-history-buffer ()
593   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
594
595 (defun gnus-agent-open-history ()
596   (save-excursion
597     (push (cons (gnus-agent-method)
598                 (set-buffer (gnus-get-buffer-create
599                              (format " *Gnus agent %s history*"
600                                      (gnus-agent-method)))))
601           gnus-agent-history-buffers)
602     (erase-buffer)
603     (insert "\n")
604     (let ((file (gnus-agent-lib-file "history")))
605       (when (file-exists-p file)
606         (insert-file file))
607       (set (make-local-variable 'gnus-agent-file-name) file))))
608
609 (defun gnus-agent-save-history ()
610   (save-excursion
611     (set-buffer gnus-agent-current-history)
612     (gnus-make-directory (file-name-directory gnus-agent-file-name))
613     (let ((coding-system-for-write
614            gnus-agent-file-coding-system))
615       (write-region (1+ (point-min)) (point-max)
616                     gnus-agent-file-name nil 'silent))))
617
618 (defun gnus-agent-close-history ()
619   (when (gnus-buffer-live-p gnus-agent-current-history)
620     (kill-buffer gnus-agent-current-history)
621     (setq gnus-agent-history-buffers
622           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
623                 gnus-agent-history-buffers))))
624
625 (defun gnus-agent-enter-history (id group-arts date)
626   (save-excursion
627     (set-buffer gnus-agent-current-history)
628     (goto-char (point-max))
629     (insert id "\t" (number-to-string date) "\t")
630     (while group-arts
631       (insert (caar group-arts) " " (number-to-string (cdr (pop group-arts)))
632               " "))
633     (insert "\n")))
634
635 (defun gnus-agent-article-in-history-p (id)
636   (save-excursion
637     (set-buffer (gnus-agent-history-buffer))
638     (goto-char (point-min))
639     (search-forward (concat "\n" id "\t") nil t)))
640
641 (defun gnus-agent-history-path (id)
642   (save-excursion
643     (set-buffer (gnus-agent-history-buffer))
644     (goto-char (point-min))
645     (when (search-forward (concat "\n" id "\t") nil t)
646       (let ((method (gnus-agent-method)))
647         (let (paths group)
648           (while (not (numberp (setq group (read (current-buffer)))))
649             (push (concat method "/" group) paths))
650           (nreverse paths))))))
651
652 ;;;
653 ;;; Fetching
654 ;;;
655
656 (defun gnus-agent-fetch-articles (group articles)
657   "Fetch ARTICLES from GROUP and put them into the Agent."
658   (when articles
659     ;; Prune off articles that we have already fetched.
660     (while (and articles
661                 (cdr (assq (car articles) gnus-agent-article-alist)))
662      (pop articles))
663     (let ((arts articles))
664       (while (cdr arts)
665         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
666             (setcdr arts (cddr arts))
667           (setq arts (cdr arts)))))
668     (when articles
669       (let ((dir (concat
670                   (gnus-agent-directory)
671                   (gnus-agent-group-path group) "/"))
672             (date (time-to-days (current-time)))
673             (case-fold-search t)
674             pos crosses id elem)
675         (gnus-make-directory dir)
676         (gnus-message 7 "Fetching articles for %s..." group)
677         ;; Fetch the articles from the backend.
678         (if (gnus-check-backend-function 'retrieve-articles group)
679             (setq pos (gnus-retrieve-articles articles group))
680           (with-temp-file nil
681             (let (article)
682               (while (setq article (pop articles))
683                 (when (gnus-request-article article group)
684                   (goto-char (point-max))
685                   (push (cons article (point)) pos)
686                   (insert-buffer-substring nntp-server-buffer)))
687               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
688               (setq pos (nreverse pos)))))
689         ;; Then save these articles into the Agent.
690         (save-excursion
691           (set-buffer nntp-server-buffer)
692           (while pos
693             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
694             (goto-char (point-min))
695             (when (search-forward "\n\n" nil t)
696               (when (search-backward "\nXrefs: " nil t)
697                 ;; Handle crossposting.
698                 (skip-chars-forward "^ ")
699                 (skip-chars-forward " ")
700                 (setq crosses nil)
701                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
702                   (push (cons (buffer-substring (match-beginning 1)
703                                                 (match-end 1))
704                               (buffer-substring (match-beginning 2)
705                                                 (match-end 2)))
706                         crosses)
707                   (goto-char (match-end 0)))
708                 (gnus-agent-crosspost crosses (caar pos))))
709             (goto-char (point-min))
710             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
711                 (setq id "No-Message-ID-in-article")
712               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
713             (let ((coding-system-for-write
714                    gnus-agent-file-coding-system))
715               (write-region (point-min) (point-max)
716                             (concat dir (number-to-string (caar pos)))
717                             nil 'silent))
718             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
719               (setcdr elem t))
720             (gnus-agent-enter-history
721              id (or crosses (list (cons group (caar pos)))) date)
722             (widen)
723             (pop pos)))
724         (gnus-agent-save-alist group)))))
725
726 (defun gnus-agent-crosspost (crosses article)
727   (let (gnus-agent-article-alist group alist beg end)
728     (save-excursion
729       (set-buffer gnus-agent-overview-buffer)
730       (when (nnheader-find-nov-line article)
731         (forward-word 1)
732         (setq beg (point))
733         (setq end (progn (forward-line 1) (point)))))
734     (while crosses
735       (setq group (caar crosses))
736       (unless (setq alist (assoc group gnus-agent-group-alist))
737         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
738               gnus-agent-group-alist))
739       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
740       (save-excursion
741         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
742                                                group)))
743         (when (= (point-max) (point-min))
744           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
745           (ignore-errors
746             (nnheader-insert-file-contents
747              (gnus-agent-article-name ".overview" group))))
748         (nnheader-find-nov-line (string-to-number (cdar crosses)))
749         (insert (string-to-number (cdar crosses)))
750         (insert-buffer-substring gnus-agent-overview-buffer beg end))
751       (pop crosses))))
752
753 (defun gnus-agent-flush-cache ()
754   (save-excursion
755     (while gnus-agent-buffer-alist
756       (set-buffer (cdar gnus-agent-buffer-alist))
757       (let ((coding-system-for-write
758              gnus-agent-file-coding-system))
759         (write-region (point-min) (point-max)
760                       (gnus-agent-article-name ".overview"
761                                                (caar gnus-agent-buffer-alist))
762                       nil 'silent))
763       (pop gnus-agent-buffer-alist))
764     (while gnus-agent-group-alist
765       (with-temp-file (caar gnus-agent-group-alist)
766         (princ (cdar gnus-agent-group-alist))
767         (insert "\n"))
768       (pop gnus-agent-group-alist))))
769
770 (defun gnus-agent-fetch-headers (group &optional force)
771   (let ((articles (if (gnus-agent-load-alist group)
772                       (gnus-sorted-intersection
773                        (gnus-list-of-unread-articles group)
774                        (gnus-uncompress-range
775                         (cons (1+ (caar (last gnus-agent-article-alist)))
776                               (cdr (gnus-active group)))))
777                     (gnus-list-of-unread-articles group))))
778     ;; Fetch them.
779     (when articles
780       (gnus-message 7 "Fetching headers for %s..." group)
781       (save-excursion
782         (set-buffer nntp-server-buffer)
783         (unless (eq 'nov (gnus-retrieve-headers articles group))
784           (nnvirtual-convert-headers))
785         ;; Save these headers for later processing.
786         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
787         (let (file)
788           (when (file-exists-p
789                  (setq file (gnus-agent-article-name ".overview" group)))
790             (gnus-agent-braid-nov group articles file))
791           (gnus-make-directory (nnheader-translate-file-chars
792                                 (file-name-directory file)))
793           (let ((coding-system-for-write
794                  gnus-agent-file-coding-system))
795             (write-region (point-min) (point-max) file nil 'silent))
796           (gnus-agent-save-alist group articles nil)
797           (gnus-agent-enter-history
798            "last-header-fetched-for-session"
799            (list (cons group (nth (- (length  articles) 1) articles)))
800            (time-to-days (current-time)))
801           articles)))))
802
803 (defsubst gnus-agent-copy-nov-line (article)
804   (let (b e)
805     (set-buffer gnus-agent-overview-buffer)
806     (setq b (point))
807     (if (eq article (read (current-buffer)))
808         (setq e (progn (forward-line 1) (point)))
809       (progn
810         (beginning-of-line)
811         (setq e b)))
812     (set-buffer nntp-server-buffer)
813     (insert-buffer-substring gnus-agent-overview-buffer b e)))
814
815 (defun gnus-agent-braid-nov (group articles file)
816   (set-buffer gnus-agent-overview-buffer)
817   (goto-char (point-min))
818   (set-buffer nntp-server-buffer)
819   (erase-buffer)
820   (nnheader-insert-file-contents file)
821   (goto-char (point-max))
822   (if (or (= (point-min) (point-max))
823           (progn
824             (forward-line -1)
825             (< (read (current-buffer)) (car articles))))
826       ;; We have only headers that are after the older headers,
827       ;; so we just append them.
828       (progn
829         (goto-char (point-max))
830         (insert-buffer-substring gnus-agent-overview-buffer))
831     ;; We do it the hard way.
832     (nnheader-find-nov-line (car articles))
833     (gnus-agent-copy-nov-line (car articles))
834     (pop articles)
835     (while (and articles
836                 (not (eobp)))
837       (while (and (not (eobp))
838                   (< (read (current-buffer)) (car articles)))
839         (forward-line 1))
840       (beginning-of-line)
841       (unless (eobp)
842         (gnus-agent-copy-nov-line (car articles))
843         (setq articles (cdr articles))))
844     (when articles
845       (let (b e)
846         (set-buffer gnus-agent-overview-buffer)
847         (setq b (point)
848               e (point-max))
849         (set-buffer nntp-server-buffer)
850         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
851
852 (defun gnus-agent-load-alist (group &optional dir)
853   "Load the article-state alist for GROUP."
854   (setq gnus-agent-article-alist
855         (gnus-agent-read-file
856          (if dir
857              (concat dir ".agentview")
858            (gnus-agent-article-name ".agentview" group)))))
859
860 (defun gnus-agent-save-alist (group &optional articles state dir)
861   "Save the article-state alist for GROUP."
862   (with-temp-file (if dir
863                       (concat dir ".agentview")
864                     (gnus-agent-article-name ".agentview" group))
865     (princ (setq gnus-agent-article-alist
866                  (nconc gnus-agent-article-alist
867                         (mapcar (lambda (article) (cons article state))
868                                 articles)))
869            (current-buffer))
870     (insert "\n")))
871
872 (defun gnus-agent-article-name (article group)
873   (concat (gnus-agent-directory) (gnus-agent-group-path group) "/"
874           (if (stringp article) article (string-to-number article))))
875
876 ;;;###autoload
877 (defun gnus-agent-batch-fetch ()
878   "Start Gnus and fetch session."
879   (interactive)
880   (gnus)
881   (gnus-agent-fetch-session)
882   (gnus-group-exit))
883
884 (defun gnus-agent-fetch-session ()
885   "Fetch all articles and headers that are eligible for fetching."
886   (interactive)
887   (unless gnus-agent-covered-methods
888     (error "No servers are covered by the Gnus agent"))
889   (unless gnus-plugged
890     (error "Can't fetch articles while Gnus is unplugged"))
891   (let ((methods gnus-agent-covered-methods)
892         groups group gnus-command-method)
893     (save-excursion
894       (while methods
895         (setq gnus-command-method (car methods))
896         (when (or (gnus-server-opened gnus-command-method)
897                   (gnus-open-server gnus-command-method))
898           (setq groups (gnus-groups-from-server (car methods)))
899           (gnus-agent-with-fetch
900             (while (setq group (pop groups))
901               (when (<= (gnus-group-level group) gnus-agent-handle-level)
902                 (gnus-agent-fetch-group-1 group gnus-command-method)))))
903         (pop methods))
904       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
905
906 (defun gnus-agent-fetch-group-1 (group method)
907   "Fetch GROUP."
908   (let ((gnus-command-method method)
909         gnus-newsgroup-dependencies gnus-newsgroup-headers
910         gnus-newsgroup-scored gnus-headers gnus-score
911         gnus-use-cache articles arts
912         category predicate info marks score-param)
913     ;; Fetch headers.
914     (when (and (or (gnus-active group) (gnus-activate-group group))
915                (setq articles (gnus-agent-fetch-headers group)))
916       ;; Parse them and see which articles we want to fetch.
917       (setq gnus-newsgroup-dependencies
918             (make-vector (length articles) 0))
919       ;; No need to call `gnus-get-newsgroup-headers-xover' with 
920       ;; the entire .overview for group as we still have the just
921       ;; downloaded headers in `gnus-agent-overview-buffer'.
922       (let ((nntp-server-buffer gnus-agent-overview-buffer))
923         (setq gnus-newsgroup-headers
924               (gnus-get-newsgroup-headers-xover articles nil nil group)))
925       (setq category (gnus-group-category group))
926       (setq predicate
927             (gnus-get-predicate 
928              (or (gnus-group-get-parameter group 'agent-predicate t)
929                  (cadr category))))
930       ;; Do we want to download everything, or nothing?
931       (if (or (eq (caaddr predicate) 'gnus-agent-true)
932               (eq (caaddr predicate) 'gnus-agent-false))
933           ;; Yes.
934           (setq arts (symbol-value 
935                       (cadr (assoc (caaddr predicate) 
936                                    '((gnus-agent-true articles)
937                                      (gnus-agent-false nil))))))
938         ;; No, we need to decide what we want.
939         (setq score-param
940               (let ((score-method (or 
941                                    (gnus-group-get-parameter group 'agent-score t)
942                                    (caddr category))))
943                 (when score-method
944                   (require 'gnus-score)
945                   (if (eq score-method 'file)
946                       (let ((entries
947                              (gnus-score-load-files
948                               (gnus-all-score-files group)))
949                             list score-file)
950                         (while (setq list (car entries))
951                           (push (car list) score-file)
952                           (setq list (cdr list))
953                           (while list
954                             (when (member (caar list)
955                                           gnus-agent-scoreable-headers)
956                               (push (car list) score-file))
957                             (setq list (cdr list)))
958                           (setq score-param 
959                                 (append score-param (list (nreverse score-file)))
960                                 score-file nil entries (cdr entries)))
961                         (list score-param))
962                     (if (stringp (car score-method))
963                         score-method
964                       (list (list score-method)))))))
965         (when score-param
966           (gnus-score-headers score-param))
967         (setq arts nil)
968         (while (setq gnus-headers (pop gnus-newsgroup-headers))
969           (setq gnus-score
970                 (or (cdr (assq (mail-header-number gnus-headers)
971                                gnus-newsgroup-scored))
972                     gnus-summary-default-score))
973           (when (funcall predicate)
974             (push (mail-header-number gnus-headers)
975                   arts))))
976       ;; Fetch the articles.
977       (when arts
978         (gnus-agent-fetch-articles group arts)))
979     ;; Perhaps we have some additional articles to fetch.
980     (setq arts (assq 'download (gnus-info-marks
981                                 (setq info (gnus-get-info group)))))
982     (when (cdr arts)
983       (gnus-agent-fetch-articles
984        group (gnus-uncompress-range (cdr arts)))
985       (setq marks (delq arts (gnus-info-marks info)))
986       (gnus-info-set-marks info marks))))
987
988 ;;;
989 ;;; Agent Category Mode
990 ;;;
991
992 (defvar gnus-category-mode-hook nil
993   "Hook run in `gnus-category-mode' buffers.")
994
995 (defvar gnus-category-line-format "     %(%20c%): %g\n"
996   "Format of category lines.")
997
998 (defvar gnus-category-mode-line-format "Gnus: %%b"
999   "The format specification for the category mode line.")
1000
1001 (defvar gnus-agent-short-article 100
1002   "Articles that have fewer lines than this are short.")
1003
1004 (defvar gnus-agent-long-article 200
1005   "Articles that have more lines than this are long.")
1006
1007 (defvar gnus-agent-low-score 0
1008   "Articles that have a score lower than this have a low score.")
1009
1010 (defvar gnus-agent-high-score 0
1011   "Articles that have a score higher than this have a high score.")
1012
1013
1014 ;;; Internal variables.
1015
1016 (defvar gnus-category-buffer "*Agent Category*")
1017
1018 (defvar gnus-category-line-format-alist
1019   `((?c gnus-tmp-name ?s)
1020     (?g gnus-tmp-groups ?d)))
1021
1022 (defvar gnus-category-mode-line-format-alist
1023   `((?u user-defined ?s)))
1024
1025 (defvar gnus-category-line-format-spec nil)
1026 (defvar gnus-category-mode-line-format-spec nil)
1027
1028 (defvar gnus-category-mode-map nil)
1029 (put 'gnus-category-mode 'mode-class 'special)
1030
1031 (unless gnus-category-mode-map
1032   (setq gnus-category-mode-map (make-sparse-keymap))
1033   (suppress-keymap gnus-category-mode-map)
1034
1035   (gnus-define-keys gnus-category-mode-map
1036     "q" gnus-category-exit
1037     "k" gnus-category-kill
1038     "c" gnus-category-copy
1039     "a" gnus-category-add
1040     "p" gnus-category-edit-predicate
1041     "g" gnus-category-edit-groups
1042     "s" gnus-category-edit-score
1043     "l" gnus-category-list
1044
1045     "\C-c\C-i" gnus-info-find-node
1046     "\C-c\C-b" gnus-bug))
1047
1048 (defvar gnus-category-menu-hook nil
1049   "*Hook run after the creation of the menu.")
1050
1051 (defun gnus-category-make-menu-bar ()
1052   (gnus-turn-off-edit-menu 'category)
1053   (unless (boundp 'gnus-category-menu)
1054     (easy-menu-define
1055      gnus-category-menu gnus-category-mode-map ""
1056      '("Categories"
1057        ["Add" gnus-category-add t]
1058        ["Kill" gnus-category-kill t]
1059        ["Copy" gnus-category-copy t]
1060        ["Edit predicate" gnus-category-edit-predicate t]
1061        ["Edit score" gnus-category-edit-score t]
1062        ["Edit groups" gnus-category-edit-groups t]
1063        ["Exit" gnus-category-exit t]))
1064
1065     (gnus-run-hooks 'gnus-category-menu-hook)))
1066
1067 (defun gnus-category-mode ()
1068   "Major mode for listing and editing agent categories.
1069
1070 All normal editing commands are switched off.
1071 \\<gnus-category-mode-map>
1072 For more in-depth information on this mode, read the manual
1073 (`\\[gnus-info-find-node]').
1074
1075 The following commands are available:
1076
1077 \\{gnus-category-mode-map}"
1078   (interactive)
1079   (when (gnus-visual-p 'category-menu 'menu)
1080     (gnus-category-make-menu-bar))
1081   (kill-all-local-variables)
1082   (gnus-simplify-mode-line)
1083   (setq major-mode 'gnus-category-mode)
1084   (setq mode-name "Category")
1085   (gnus-set-default-directory)
1086   (setq mode-line-process nil)
1087   (use-local-map gnus-category-mode-map)
1088   (buffer-disable-undo (current-buffer))
1089   (setq truncate-lines t)
1090   (setq buffer-read-only t)
1091   (gnus-run-hooks 'gnus-category-mode-hook))
1092
1093 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1094
1095 (defun gnus-category-insert-line (category)
1096   (let* ((gnus-tmp-name (car category))
1097          (gnus-tmp-groups (length (cadddr category))))
1098     (beginning-of-line)
1099     (gnus-add-text-properties
1100      (point)
1101      (prog1 (1+ (point))
1102        ;; Insert the text.
1103        (eval gnus-category-line-format-spec))
1104      (list 'gnus-category gnus-tmp-name))))
1105
1106 (defun gnus-enter-category-buffer ()
1107   "Go to the Category buffer."
1108   (interactive)
1109   (gnus-category-setup-buffer)
1110   (gnus-configure-windows 'category)
1111   (gnus-category-prepare))
1112
1113 (defun gnus-category-setup-buffer ()
1114   (unless (get-buffer gnus-category-buffer)
1115     (save-excursion
1116       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1117       (gnus-category-mode))))
1118
1119 (defun gnus-category-prepare ()
1120   (gnus-set-format 'category-mode)
1121   (gnus-set-format 'category t)
1122   (let ((alist gnus-category-alist)
1123         (buffer-read-only nil))
1124     (erase-buffer)
1125     (while alist
1126       (gnus-category-insert-line (pop alist)))
1127     (goto-char (point-min))
1128     (gnus-category-position-point)))
1129
1130 (defun gnus-category-name ()
1131   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1132       (error "No category on the current line")))
1133
1134 (defun gnus-category-read ()
1135   "Read the category alist."
1136   (setq gnus-category-alist
1137         (or (gnus-agent-read-file
1138              (nnheader-concat gnus-agent-directory "lib/categories"))
1139             (list (list 'default 'short nil nil)))))
1140     
1141 (defun gnus-category-write ()
1142   "Write the category alist."
1143   (setq gnus-category-predicate-cache nil
1144         gnus-category-group-cache nil)
1145   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1146     (prin1 gnus-category-alist (current-buffer))))
1147
1148 (defun gnus-category-edit-predicate (category)
1149   "Edit the predicate for CATEGORY."
1150   (interactive (list (gnus-category-name)))
1151   (let ((info (assq category gnus-category-alist)))
1152     (gnus-edit-form
1153      (cadr info) (format "Editing the predicate for category %s" category)
1154      `(lambda (predicate)
1155         (setf (cadr (assq ',category gnus-category-alist)) predicate)
1156         (gnus-category-write)
1157         (gnus-category-list)))))
1158   
1159 (defun gnus-category-edit-score (category)
1160   "Edit the score expression for CATEGORY."
1161   (interactive (list (gnus-category-name)))
1162   (let ((info (assq category gnus-category-alist)))
1163     (gnus-edit-form
1164      (caddr info)
1165      (format "Editing the score expression for category %s" category)
1166      `(lambda (groups)
1167         (setf (caddr (assq ',category gnus-category-alist)) groups)
1168         (gnus-category-write)
1169         (gnus-category-list)))))
1170
1171 (defun gnus-category-edit-groups (category)
1172   "Edit the group list for CATEGORY."
1173   (interactive (list (gnus-category-name)))
1174   (let ((info (assq category gnus-category-alist)))
1175     (gnus-edit-form
1176      (cadddr info) (format "Editing the group list for category %s" category)
1177      `(lambda (groups)
1178         (setf (cadddr (assq ',category gnus-category-alist)) groups)
1179         (gnus-category-write)
1180         (gnus-category-list)))))
1181
1182 (defun gnus-category-kill (category)
1183   "Kill the current category."
1184   (interactive (list (gnus-category-name)))
1185   (let ((info (assq category gnus-category-alist))
1186         (buffer-read-only nil))
1187     (gnus-delete-line)
1188     (gnus-category-write)
1189     (setq gnus-category-alist (delq info gnus-category-alist))))
1190
1191 (defun gnus-category-copy (category to)
1192   "Copy the current category."
1193   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1194   (let ((info (assq category gnus-category-alist)))
1195     (push (list to (gnus-copy-sequence (cadr info))
1196                 (gnus-copy-sequence (caddr info)) nil)
1197           gnus-category-alist)
1198     (gnus-category-write)
1199     (gnus-category-list)))
1200
1201 (defun gnus-category-add (category)
1202   "Create a new category."
1203   (interactive "SCategory name: ")
1204   (when (assq category gnus-category-alist)
1205     (error "Category %s already exists" category))
1206   (push (list category 'true nil nil)
1207         gnus-category-alist)
1208   (gnus-category-write)
1209   (gnus-category-list))
1210
1211 (defun gnus-category-list ()
1212   "List all categories."
1213   (interactive)
1214   (gnus-category-prepare))
1215
1216 (defun gnus-category-exit ()
1217   "Return to the group buffer."
1218   (interactive)
1219   (kill-buffer (current-buffer))
1220   (gnus-configure-windows 'group t))
1221
1222 ;; To avoid having 8-bit characters in the source file.
1223 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1224
1225 (defvar gnus-category-predicate-alist
1226   '((spam . gnus-agent-spam-p)
1227     (short . gnus-agent-short-p)
1228     (long . gnus-agent-long-p)
1229     (low . gnus-agent-low-scored-p)
1230     (high . gnus-agent-high-scored-p)
1231     (true . gnus-agent-true)
1232     (false . gnus-agent-false))
1233   "Mapping from short score predicate symbols to predicate functions.")
1234
1235 (defun gnus-agent-spam-p ()
1236   "Say whether an article is spam or not."
1237   (unless gnus-agent-spam-hashtb
1238     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1239   (if (not (equal (mail-header-references gnus-headers) ""))
1240       nil
1241     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1242       (prog1
1243           (gnus-gethash string gnus-agent-spam-hashtb)
1244         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1245
1246 (defun gnus-agent-short-p ()
1247   "Say whether an article is short or not."
1248   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1249
1250 (defun gnus-agent-long-p ()
1251   "Say whether an article is long or not."
1252   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1253
1254 (defun gnus-agent-low-scored-p ()
1255   "Say whether an article has a low score or not."
1256   (< gnus-score gnus-agent-low-score))
1257
1258 (defun gnus-agent-high-scored-p ()
1259   "Say whether an article has a high score or not."
1260   (> gnus-score gnus-agent-high-score))
1261
1262 (defun gnus-category-make-function (cat)
1263   "Make a function from category CAT."
1264   `(lambda () ,(gnus-category-make-function-1 cat)))
1265
1266 (defun gnus-agent-true ()
1267   "Return t."
1268   t)
1269
1270 (defun gnus-agent-false ()
1271   "Return nil."
1272   nil)
1273   
1274 (defun gnus-category-make-function-1 (cat)
1275   "Make a function from category CAT."
1276   (cond
1277    ;; Functions are just returned as is.
1278    ((or (symbolp cat)
1279         (gnus-functionp cat))
1280     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1281            cat)))
1282    ;; More complex category.
1283    ((consp cat)
1284     `(,(cond
1285         ((memq (car cat) '(& and))
1286          'and)
1287         ((memq (car cat) '(| or))
1288          'or)
1289         ((memq (car cat) gnus-category-not)
1290          'not))
1291       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1292    (t
1293     (error "Unknown category type: %s" cat))))
1294
1295 (defun gnus-get-predicate (predicate)
1296   "Return the predicate for CATEGORY."
1297   (or (cdr (assoc predicate gnus-category-predicate-cache))
1298       (cdar (push (cons predicate
1299                         (gnus-category-make-function predicate))
1300                   gnus-category-predicate-cache))))
1301
1302 (defun gnus-group-category (group)
1303   "Return the category GROUP belongs to."
1304   (unless gnus-category-group-cache
1305     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1306     (let ((cs gnus-category-alist)
1307           groups cat)
1308       (while (setq cat (pop cs))
1309         (setq groups (cadddr cat))
1310         (while groups
1311           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1312   (or (gnus-gethash group gnus-category-group-cache)
1313       (assq 'default gnus-category-alist)))
1314
1315 (defun gnus-agent-expire ()
1316   "Expire all old articles."
1317   (interactive)
1318   (let ((methods gnus-agent-covered-methods)
1319         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1320         gnus-command-method sym group articles
1321         history overview file histories elem art nov-file low info
1322         unreads marked article)
1323     (save-excursion
1324       (setq overview (gnus-get-buffer-create " *expire overview*"))
1325       (while (setq gnus-command-method (pop methods))
1326         (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1327         (gnus-agent-open-history)
1328         (set-buffer
1329          (setq gnus-agent-current-history
1330                (setq history (gnus-agent-history-buffer))))
1331         (goto-char (point-min))
1332         (when (> (buffer-size) 1)
1333           (goto-char (point-min))
1334           (while (not (eobp))
1335             (skip-chars-forward "^\t")
1336             (if (> (read (current-buffer)) day)
1337                 ;; New article; we don't expire it.
1338                 (forward-line 1)
1339               ;; Old article.  Schedule it for possible nuking.
1340               (while (not (eolp))
1341                 (setq sym (let ((obarray expiry-hashtb))
1342                             (read (current-buffer))))
1343                 (if (boundp sym)
1344                     (set sym (cons (cons (read (current-buffer)) (point))
1345                                    (symbol-value sym)))
1346                   (set sym (list (cons (read (current-buffer)) (point)))))
1347                 (skip-chars-forward " "))
1348               (forward-line 1)))
1349           ;; We now have all articles that can possibly be expired.
1350           (mapatoms
1351            (lambda (sym)
1352              (setq group (symbol-name sym)
1353                    articles (sort (symbol-value sym) 'car-less-than-car)
1354                    low (car (gnus-active group))
1355                    info (gnus-get-info group)
1356                    unreads (ignore-errors (gnus-list-of-unread-articles group))
1357                    marked (nconc (gnus-uncompress-range
1358                                   (cdr (assq 'tick (gnus-info-marks info))))
1359                                  (gnus-uncompress-range
1360                                   (cdr (assq 'dormant
1361                                              (gnus-info-marks info)))))
1362                    nov-file (gnus-agent-article-name ".overview" group))
1363              (gnus-agent-load-alist group)
1364              (gnus-message 5 "Expiring articles in %s" group)
1365              (set-buffer overview)
1366              (erase-buffer)
1367              (when (file-exists-p nov-file)
1368                (nnheader-insert-file-contents nov-file))
1369              (goto-char (point-min))
1370              (setq article 0)
1371              (while (setq elem (pop articles))
1372                (setq article (car elem))
1373                (when (or (null low)
1374                          (< article low)
1375                          gnus-agent-expire-all
1376                          (and (not (memq article unreads))
1377                               (not (memq article marked))))
1378                  ;; Find and nuke the NOV line.
1379                  (while (and (not (eobp))
1380                              (or (not (numberp
1381                                        (setq art (read (current-buffer)))))
1382                                  (< art article)))
1383                    (if (file-exists-p
1384                         (gnus-agent-article-name
1385                          (number-to-string art) group))
1386                        (forward-line 1)
1387                      ;; Remove old NOV lines that have no articles.
1388                      (gnus-delete-line)))
1389                  (if (or (eobp)
1390                          (/= art article))
1391                      (beginning-of-line)
1392                    (gnus-delete-line))
1393                  ;; Nuke the article.
1394                  (when (file-exists-p (setq file (gnus-agent-article-name
1395                                                   (number-to-string article)
1396                                                   group)))
1397                    (delete-file file))
1398                  ;; Schedule the history line for nuking.
1399                  (push (cdr elem) histories)))
1400              (gnus-make-directory (file-name-directory nov-file))
1401              (let ((coding-system-for-write
1402                     gnus-agent-file-coding-system))
1403                (write-region (point-min) (point-max) nov-file nil 'silent))
1404              ;; Delete the unwanted entries in the alist.
1405              (setq gnus-agent-article-alist
1406                    (sort gnus-agent-article-alist 'car-less-than-car))
1407              (let* ((alist gnus-agent-article-alist)
1408                     (prev (cons nil alist))
1409                     (first prev)
1410                     expired)
1411                (while (and alist
1412                            (<= (caar alist) article))
1413                  (if (or (not (cdar alist))
1414                          (not (file-exists-p
1415                                (gnus-agent-article-name
1416                                 (number-to-string
1417                                  (caar alist))
1418                                 group))))
1419                      (progn
1420                        (push (caar alist) expired)
1421                        (setcdr prev (setq alist (cdr alist))))
1422                    (setq prev alist
1423                          alist (cdr alist))))
1424                (setq gnus-agent-article-alist (cdr first))
1425                (gnus-agent-save-alist group)
1426                ;; Mark all articles up to the first article
1427                ;; in `gnus-article-alist' as read.
1428                (when (and info (caar gnus-agent-article-alist))
1429                  (setcar (nthcdr 2 info)
1430                          (gnus-range-add
1431                           (nth 2 info)
1432                           (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1433                ;; Maybe everything has been expired from `gnus-article-alist'
1434                ;; and so the above marking as read could not be conducted,
1435                ;; or there are expired article within the range of the alist.
1436                (if expired
1437                    (when (or (not (caar gnus-agent-article-alist))
1438                              (> (car expired) (caar gnus-agent-article-alist)))  
1439                      (setcar (nthcdr 2 info)
1440                              (gnus-add-to-range
1441                               (nth 2 info)
1442                               (nreverse expired)))))
1443                (gnus-dribble-enter
1444                 (concat "(gnus-group-set-info '"
1445                         (gnus-prin1-to-string info)
1446                         ")"))))
1447            expiry-hashtb)
1448           (set-buffer history)
1449           (setq histories (nreverse (sort histories '<)))
1450           (while histories
1451             (goto-char (pop histories))
1452             (gnus-delete-line))
1453           (gnus-agent-save-history)
1454           (gnus-agent-close-history))
1455         (gnus-message 4 "Expiry...done"))))))
1456
1457 ;;;###autoload
1458 (defun gnus-agent-batch ()
1459   (interactive)
1460   (let ((init-file-user "")
1461         (gnus-always-read-dribble-file t))
1462     (gnus))
1463   (gnus-group-send-drafts)
1464   (gnus-agent-fetch-session))
1465
1466 (provide 'gnus-agent)
1467
1468 ;;; gnus-agent.el ends here