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