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