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