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