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