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