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