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