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