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