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