Sync up with gnus-5.6.42
[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-article-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       (let ((coding-system-for-write gnus-agent-article-file-coding-system))
521         (write-region (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 (point-min) (point-max) file nil 'silent))
530     (when (file-exists-p (gnus-agent-lib-file "active"))
531       (delete-file (gnus-agent-lib-file "active"))))
532
533 (defun gnus-agent-save-group-info (method group active)
534   (when (gnus-agent-method-p method)
535     (let* ((gnus-command-method method)
536            (file (if nntp-server-list-active-group
537                      (gnus-agent-lib-file "active")
538                    (gnus-agent-lib-file "groups"))))
539       (gnus-make-directory (file-name-directory file))
540       (nnheader-temp-write file
541         (when (file-exists-p file)
542           (nnheader-insert-file-contents file))
543         (goto-char (point-min))
544         (if nntp-server-list-active-group
545             (progn
546               (when (re-search-forward
547                      (concat "^" (regexp-quote group) " ") nil t)
548                 (gnus-delete-line))
549               (insert group " " (number-to-string (cdr active)) " "
550                       (number-to-string (car active)) "\n"))
551           (when (re-search-forward (concat (regexp-quote group) " ") nil t)
552             (gnus-delete-line))
553           (insert-buffer-substring nntp-server-buffer))))))
554
555 (defun gnus-agent-group-path (group)
556   "Translate GROUP into a path."
557   (if nnmail-use-long-file-names
558       (gnus-group-real-name group)
559     (nnheader-replace-chars-in-string
560      (nnheader-translate-file-chars (gnus-group-real-name group))
561      ?. ?/)))
562
563 \f
564
565 (defun gnus-agent-method-p (method)
566   "Say whether METHOD is covered by the agent."
567   (member method gnus-agent-covered-methods))
568
569 (defun gnus-agent-get-function (method)
570   (if (and (not gnus-plugged)
571            (gnus-agent-method-p method))
572       (progn
573         (require 'nnagent)
574         'nnagent)
575     (car method)))
576
577 ;;; History functions
578
579 (defun gnus-agent-history-buffer ()
580   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
581
582 (defun gnus-agent-open-history ()
583   (save-excursion
584     (push (cons (gnus-agent-method)
585                 (set-buffer (gnus-get-buffer-create
586                              (format " *Gnus agent %s history*"
587                                      (gnus-agent-method)))))
588           gnus-agent-history-buffers)
589     (erase-buffer)
590     (insert "\n")
591     (let ((file (gnus-agent-lib-file "history")))
592       (when (file-exists-p file)
593         (insert-file file))
594       (set (make-local-variable 'gnus-agent-file-name) file))))
595
596 (defun gnus-agent-save-history ()
597   (save-excursion
598     (set-buffer gnus-agent-current-history)
599     (gnus-make-directory (file-name-directory gnus-agent-file-name))
600     (write-region (1+ (point-min)) (point-max)
601                   gnus-agent-file-name nil 'silent)))
602
603 (defun gnus-agent-close-history ()
604   (when (gnus-buffer-live-p gnus-agent-current-history)
605     (kill-buffer gnus-agent-current-history)
606     (setq gnus-agent-history-buffers
607           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
608                 gnus-agent-history-buffers))))
609
610 (defun gnus-agent-enter-history (id group-arts date)
611   (save-excursion
612     (set-buffer gnus-agent-current-history)
613     (goto-char (point-max))
614     (insert id "\t" (number-to-string date) "\t")
615     (while group-arts
616       (insert (caar group-arts) " " (number-to-string (cdr (pop group-arts)))
617               " "))
618     (insert "\n")))
619
620 (defun gnus-agent-article-in-history-p (id)
621   (save-excursion
622     (set-buffer (gnus-agent-history-buffer))
623     (goto-char (point-min))
624     (search-forward (concat "\n" id "\t") nil t)))
625
626 (defun gnus-agent-history-path (id)
627   (save-excursion
628     (set-buffer (gnus-agent-history-buffer))
629     (goto-char (point-min))
630     (when (search-forward (concat "\n" id "\t") nil t)
631       (let ((method (gnus-agent-method)))
632         (let (paths group)
633           (while (not (numberp (setq group (read (current-buffer)))))
634             (push (concat method "/" group) paths))
635           (nreverse paths))))))
636
637 ;;;
638 ;;; Fetching
639 ;;;
640
641 (defun gnus-agent-fetch-articles (group articles)
642   "Fetch ARTICLES from GROUP and put them into the Agent."
643   (when articles
644     ;; Prune off articles that we have already fetched.
645     (while (and articles
646                 (cdr (assq (car articles) gnus-agent-article-alist)))
647       (pop articles))
648     (let ((arts articles))
649       (while (cdr arts)
650         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
651             (setcdr arts (cddr arts))
652           (setq arts (cdr arts)))))
653     (when articles
654       (let ((dir (concat
655                   (gnus-agent-directory)
656                   (gnus-agent-group-path group) "/"))
657             (date (gnus-time-to-day (current-time)))
658             (case-fold-search t)
659             pos crosses id elem)
660         (gnus-make-directory dir)
661         (gnus-message 7 "Fetching articles for %s..." group)
662         ;; Fetch the articles from the backend.
663         (if (gnus-check-backend-function 'retrieve-articles group)
664             (setq pos (gnus-retrieve-articles articles group))
665           (nnheader-temp-write nil
666             (let (article)
667               (while (setq article (pop articles))
668                 (when (gnus-request-article article group)
669                   (goto-char (point-max))
670                   (push (cons article (point)) pos)
671                   (insert-buffer-substring nntp-server-buffer)))
672               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
673               (setq pos (nreverse pos)))))
674         ;; Then save these articles into the Agent.
675         (save-excursion
676           (set-buffer nntp-server-buffer)
677           (while pos
678             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
679             (goto-char (point-min))
680             (when (search-forward "\n\n" nil t)
681               (when (search-backward "\nXrefs: " nil t)
682                 ;; Handle crossposting.
683                 (skip-chars-forward "^ ")
684                 (skip-chars-forward " ")
685                 (setq crosses nil)
686                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
687                   (push (cons (buffer-substring (match-beginning 1)
688                                                 (match-end 1))
689                               (buffer-substring (match-beginning 2)
690                                                 (match-end 2)))
691                         crosses)
692                   (goto-char (match-end 0)))
693                 (gnus-agent-crosspost crosses (caar pos))))
694             (goto-char (point-min))
695             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
696                 (setq id "No-Message-ID-in-article")
697               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
698             (let ((coding-system-for-write
699                    gnus-agent-article-file-coding-system))
700               (write-region (point-min) (point-max)
701                             (concat dir (number-to-string (caar pos)))
702                             nil 'silent))
703             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
704               (setcdr elem t))
705             (gnus-agent-enter-history
706              id (or crosses (list (cons group (caar pos)))) date)
707             (widen)
708             (pop pos)))
709         (gnus-agent-save-alist group)))))
710
711 (defun gnus-agent-crosspost (crosses article)
712   (let (gnus-agent-article-alist group alist beg end)
713     (save-excursion
714       (set-buffer gnus-agent-overview-buffer)
715       (when (nnheader-find-nov-line article)
716         (forward-word 1)
717         (setq beg (point))
718         (setq end (progn (forward-line 1) (point)))))
719     (while crosses
720       (setq group (caar crosses))
721       (unless (setq alist (assoc group gnus-agent-group-alist))
722         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
723               gnus-agent-group-alist))
724       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
725       (save-excursion
726         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
727                                                group)))
728         (when (= (point-max) (point-min))
729           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
730           (ignore-errors
731             (nnheader-insert-file-contents
732              (gnus-agent-article-name ".overview" group))))
733         (nnheader-find-nov-line (string-to-number (cdar crosses)))
734         (insert (string-to-number (cdar crosses)))
735         (insert-buffer-substring gnus-agent-overview-buffer beg end))
736       (pop crosses))))
737
738 (defun gnus-agent-flush-cache ()
739   (save-excursion
740     (while gnus-agent-buffer-alist
741       (set-buffer (cdar gnus-agent-buffer-alist))
742       (write-region (point-min) (point-max)
743                     (gnus-agent-article-name ".overview"
744                                              (caar gnus-agent-buffer-alist))
745                      nil 'silent)
746       (pop gnus-agent-buffer-alist))
747     (while gnus-agent-group-alist
748       (nnheader-temp-write (caar gnus-agent-group-alist)
749         (princ (cdar gnus-agent-group-alist))
750         (insert "\n"))
751       (pop gnus-agent-group-alist))))
752
753 (defun gnus-agent-fetch-headers (group &optional force)
754   (gnus-agent-load-alist group)
755   ;; Find out what headers we need to retrieve.
756   (when articles
757     (while (and articles
758                 (assq (car articles) gnus-agent-article-alist))
759       (pop articles))
760     (let ((arts articles))
761       (while (cdr arts)
762         (if (assq (cadr arts) gnus-agent-article-alist)
763             (setcdr arts (cddr arts))
764           (setq arts (cdr arts)))))
765     ;; Fetch them.
766     (when articles
767       (gnus-message 7 "Fetching headers for %s..." group)
768       (save-excursion
769         (set-buffer nntp-server-buffer)
770         (unless (eq 'nov (gnus-retrieve-headers articles group))
771           (nnvirtual-convert-headers))
772         ;; Save these headers for later processing.
773         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
774         (let (file)
775           (when (file-exists-p
776                  (setq file (gnus-agent-article-name ".overview" group)))
777             (gnus-agent-braid-nov group articles file))
778           (gnus-make-directory (nnheader-translate-file-chars
779                                 (file-name-directory file)))
780           (write-region (point-min) (point-max) file nil 'silent)
781           (gnus-agent-save-alist group articles nil)
782           (gnus-agent-enter-history "last-header-fetched-for-session"
783                                     (list (cons group (nth (- (length  articles) 1) articles)))
784                                     (gnus-time-to-day (current-time)))
785         t)))))
786
787
788 (defsubst gnus-agent-copy-nov-line (article)
789   (let (b e)
790     (set-buffer gnus-agent-overview-buffer)
791     (setq b (point))
792     (if (eq article (read (current-buffer)))
793         (setq e (progn (forward-line 1) (point)))
794       (progn
795         (beginning-of-line)
796         (setq e b)))
797     (set-buffer nntp-server-buffer)
798     (insert-buffer-substring gnus-agent-overview-buffer b e)))
799
800 (defun gnus-agent-braid-nov (group articles file)
801   (set-buffer gnus-agent-overview-buffer)
802   (goto-char (point-min))
803   (set-buffer nntp-server-buffer)
804   (erase-buffer)
805   (nnheader-insert-file-contents file)
806   (goto-char (point-max))
807   (if (or (= (point-min) (point-max))
808           (progn
809             (forward-line -1)
810             (< (read (current-buffer)) (car articles))))
811       ;; We have only headers that are after the older headers,
812       ;; so we just append them.
813       (progn
814         (goto-char (point-max))
815         (insert-buffer-substring gnus-agent-overview-buffer))
816     ;; We do it the hard way.
817     (nnheader-find-nov-line (car articles))
818     (gnus-agent-copy-nov-line (car articles))
819     (pop articles)
820     (while (and articles
821                 (not (eobp)))
822       (while (and (not (eobp))
823                   (< (read (current-buffer)) (car articles)))
824         (forward-line 1))
825       (beginning-of-line)
826       (unless (eobp)
827         (gnus-agent-copy-nov-line (car articles))
828         (setq articles (cdr articles))))
829     (when articles
830       (let (b e)
831         (set-buffer gnus-agent-overview-buffer)
832         (setq b (point)
833               e (point-max))
834         (set-buffer nntp-server-buffer)
835         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
836
837 (defun gnus-agent-load-alist (group &optional dir)
838   "Load the article-state alist for GROUP."
839   (setq gnus-agent-article-alist
840         (gnus-agent-read-file
841          (if dir
842              (concat dir ".agentview")
843            (gnus-agent-article-name ".agentview" group)))))
844
845 (defun gnus-agent-save-alist (group &optional articles state dir)
846   "Save the article-state alist for GROUP."
847   (nnheader-temp-write (if dir
848                            (concat dir ".agentview")
849                          (gnus-agent-article-name ".agentview" group))
850     (princ (setq gnus-agent-article-alist
851                  (nconc gnus-agent-article-alist
852                         (mapcar (lambda (article) (cons article state))
853                                 articles)))
854            (current-buffer))
855     (insert "\n")))
856
857 (defun gnus-agent-article-name (article group)
858   (concat (gnus-agent-directory) (gnus-agent-group-path group) "/"
859           (if (stringp article) article (string-to-number article))))
860
861 ;;;###autoload
862 (defun gnus-agent-batch-fetch ()
863   "Start Gnus and fetch session."
864   (interactive)
865   (gnus)
866   (gnus-agent-fetch-session)
867   (gnus-group-exit))
868
869 (defun gnus-agent-fetch-session ()
870   "Fetch all articles and headers that are eligible for fetching."
871   (interactive)
872   (unless gnus-agent-covered-methods
873     (error "No servers are covered by the Gnus agent"))
874   (unless gnus-plugged
875     (error "Can't fetch articles while Gnus is unplugged"))
876   (let ((methods gnus-agent-covered-methods)
877         groups group gnus-command-method)
878     (save-excursion
879       (while methods
880         (setq gnus-command-method (car methods))
881         (when (or (gnus-server-opened gnus-command-method)
882                   (gnus-open-server gnus-command-method))
883           (setq groups (gnus-groups-from-server (car methods)))
884           (gnus-agent-with-fetch
885             (while (setq group (pop groups))
886               (when (<= (gnus-group-level group) gnus-agent-handle-level)
887                 (gnus-agent-fetch-group-1 group gnus-command-method)))))
888         (pop methods))
889       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
890
891 (defun gnus-agent-fetch-group-1 (group method)
892   "Fetch GROUP."
893   (let ((gnus-command-method method)
894         gnus-newsgroup-dependencies gnus-newsgroup-headers
895         gnus-newsgroup-scored gnus-headers gnus-score
896         gnus-use-cache articles arts
897         category predicate info marks score-param)
898     ;; Fetch headers.
899     (when (and (or (gnus-active group) (gnus-activate-group group))
900                (setq articles (gnus-agent-fetch-headers group)))
901       ;; Parse them and see which articles we want to fetch.
902       (setq gnus-newsgroup-dependencies
903             (make-vector (length articles) 0))
904       (setq gnus-newsgroup-headers
905             (gnus-get-newsgroup-headers-xover articles nil nil group))
906       (setq category (gnus-group-category group))
907       (setq predicate
908             (gnus-get-predicate 
909              (or (gnus-group-get-parameter group 'agent-predicate)
910                  (cadr category))))
911       (setq score-param
912             (or (gnus-group-get-parameter group 'agent-score)
913                 (caddr category)))
914       (when score-param
915         (gnus-score-headers (list (list score-param))))
916       (setq arts nil)
917       (while (setq gnus-headers (pop gnus-newsgroup-headers))
918         (setq gnus-score
919               (or (cdr (assq (mail-header-number gnus-headers)
920                              gnus-newsgroup-scored))
921                   gnus-summary-default-score))
922         (when (funcall predicate)
923           (push (mail-header-number gnus-headers)
924                 arts)))
925       ;; Fetch the articles.
926       (when arts
927         (gnus-agent-fetch-articles group arts)))
928     ;; Perhaps we have some additional articles to fetch.
929     (setq arts (assq 'download (gnus-info-marks
930                                 (setq info (gnus-get-info group)))))
931     (when (cdr arts)
932       (gnus-agent-fetch-articles
933        group (gnus-uncompress-range (cdr arts)))
934       (setq marks (delq arts (gnus-info-marks info)))
935       (gnus-info-set-marks info marks))))
936
937 ;;;
938 ;;; Agent Category Mode
939 ;;;
940
941 (defvar gnus-category-mode-hook nil
942   "Hook run in `gnus-category-mode' buffers.")
943
944 (defvar gnus-category-line-format "     %(%20c%): %g\n"
945   "Format of category lines.")
946
947 (defvar gnus-category-mode-line-format "Gnus: %%b"
948   "The format specification for the category mode line.")
949
950 (defvar gnus-agent-short-article 100
951   "Articles that have fewer lines than this are short.")
952
953 (defvar gnus-agent-long-article 200
954   "Articles that have more lines than this are long.")
955
956 (defvar gnus-agent-low-score 0
957   "Articles that have a score lower than this have a low score.")
958
959 (defvar gnus-agent-high-score 0
960   "Articles that have a score higher than this have a high score.")
961
962
963 ;;; Internal variables.
964
965 (defvar gnus-category-buffer "*Agent Category*")
966
967 (defvar gnus-category-line-format-alist
968   `((?c gnus-tmp-name ?s)
969     (?g gnus-tmp-groups ?d)))
970
971 (defvar gnus-category-mode-line-format-alist
972   `((?u user-defined ?s)))
973
974 (defvar gnus-category-line-format-spec nil)
975 (defvar gnus-category-mode-line-format-spec nil)
976
977 (defvar gnus-category-mode-map nil)
978 (put 'gnus-category-mode 'mode-class 'special)
979
980 (unless gnus-category-mode-map
981   (setq gnus-category-mode-map (make-sparse-keymap))
982   (suppress-keymap gnus-category-mode-map)
983
984   (gnus-define-keys gnus-category-mode-map
985     "q" gnus-category-exit
986     "k" gnus-category-kill
987     "c" gnus-category-copy
988     "a" gnus-category-add
989     "p" gnus-category-edit-predicate
990     "g" gnus-category-edit-groups
991     "s" gnus-category-edit-score
992     "l" gnus-category-list
993
994     "\C-c\C-i" gnus-info-find-node
995     "\C-c\C-b" gnus-bug))
996
997 (defvar gnus-category-menu-hook nil
998   "*Hook run after the creation of the menu.")
999
1000 (defun gnus-category-make-menu-bar ()
1001   (gnus-turn-off-edit-menu 'category)
1002   (unless (boundp 'gnus-category-menu)
1003     (easy-menu-define
1004      gnus-category-menu gnus-category-mode-map ""
1005      '("Categories"
1006        ["Add" gnus-category-add t]
1007        ["Kill" gnus-category-kill t]
1008        ["Copy" gnus-category-copy t]
1009        ["Edit predicate" gnus-category-edit-predicate t]
1010        ["Edit score" gnus-category-edit-score t]
1011        ["Edit groups" gnus-category-edit-groups t]
1012        ["Exit" gnus-category-exit t]))
1013
1014     (gnus-run-hooks 'gnus-category-menu-hook)))
1015
1016 (defun gnus-category-mode ()
1017   "Major mode for listing and editing agent categories.
1018
1019 All normal editing commands are switched off.
1020 \\<gnus-category-mode-map>
1021 For more in-depth information on this mode, read the manual
1022 (`\\[gnus-info-find-node]').
1023
1024 The following commands are available:
1025
1026 \\{gnus-category-mode-map}"
1027   (interactive)
1028   (when (gnus-visual-p 'category-menu 'menu)
1029     (gnus-category-make-menu-bar))
1030   (kill-all-local-variables)
1031   (gnus-simplify-mode-line)
1032   (setq major-mode 'gnus-category-mode)
1033   (setq mode-name "Category")
1034   (gnus-set-default-directory)
1035   (setq mode-line-process nil)
1036   (use-local-map gnus-category-mode-map)
1037   (buffer-disable-undo (current-buffer))
1038   (setq truncate-lines t)
1039   (setq buffer-read-only t)
1040   (gnus-run-hooks 'gnus-category-mode-hook))
1041
1042 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1043
1044 (defun gnus-category-insert-line (category)
1045   (let* ((gnus-tmp-name (car category))
1046          (gnus-tmp-groups (length (cadddr category))))
1047     (beginning-of-line)
1048     (gnus-add-text-properties
1049      (point)
1050      (prog1 (1+ (point))
1051        ;; Insert the text.
1052        (eval gnus-category-line-format-spec))
1053      (list 'gnus-category gnus-tmp-name))))
1054
1055 (defun gnus-enter-category-buffer ()
1056   "Go to the Category buffer."
1057   (interactive)
1058   (gnus-category-setup-buffer)
1059   (gnus-configure-windows 'category)
1060   (gnus-category-prepare))
1061
1062 (defun gnus-category-setup-buffer ()
1063   (unless (get-buffer gnus-category-buffer)
1064     (save-excursion
1065       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1066       (gnus-category-mode))))
1067
1068 (defun gnus-category-prepare ()
1069   (gnus-set-format 'category-mode)
1070   (gnus-set-format 'category t)
1071   (let ((alist gnus-category-alist)
1072         (buffer-read-only nil))
1073     (erase-buffer)
1074     (while alist
1075       (gnus-category-insert-line (pop alist)))
1076     (goto-char (point-min))
1077     (gnus-category-position-point)))
1078
1079 (defun gnus-category-name ()
1080   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1081       (error "No category on the current line")))
1082
1083 (defun gnus-category-read ()
1084   "Read the category alist."
1085   (setq gnus-category-alist
1086         (or (gnus-agent-read-file
1087              (nnheader-concat gnus-agent-directory "lib/categories"))
1088             (list (list 'default 'short nil nil)))))
1089     
1090 (defun gnus-category-write ()
1091   "Write the category alist."
1092   (setq gnus-category-predicate-cache nil
1093         gnus-category-group-cache nil)
1094   (nnheader-temp-write (nnheader-concat gnus-agent-directory "lib/categories")
1095     (prin1 gnus-category-alist (current-buffer))))
1096
1097 (defun gnus-category-edit-predicate (category)
1098   "Edit the predicate for CATEGORY."
1099   (interactive (list (gnus-category-name)))
1100   (let ((info (assq category gnus-category-alist)))
1101     (gnus-edit-form
1102      (cadr info) (format "Editing the predicate for category %s" category)
1103      `(lambda (predicate)
1104         (setf (cadr (assq ',category gnus-category-alist)) predicate)
1105         (gnus-category-write)
1106         (gnus-category-list)))))
1107   
1108 (defun gnus-category-edit-score (category)
1109   "Edit the score expression for CATEGORY."
1110   (interactive (list (gnus-category-name)))
1111   (let ((info (assq category gnus-category-alist)))
1112     (gnus-edit-form
1113      (caddr info)
1114      (format "Editing the score expression for category %s" category)
1115      `(lambda (groups)
1116         (setf (caddr (assq ',category gnus-category-alist)) groups)
1117         (gnus-category-write)
1118         (gnus-category-list)))))
1119
1120 (defun gnus-category-edit-groups (category)
1121   "Edit the group list for CATEGORY."
1122   (interactive (list (gnus-category-name)))
1123   (let ((info (assq category gnus-category-alist)))
1124     (gnus-edit-form
1125      (cadddr info) (format "Editing the group list for category %s" category)
1126      `(lambda (groups)
1127         (setf (cadddr (assq ',category gnus-category-alist)) groups)
1128         (gnus-category-write)
1129         (gnus-category-list)))))
1130
1131 (defun gnus-category-kill (category)
1132   "Kill the current category."
1133   (interactive (list (gnus-category-name)))
1134   (let ((info (assq category gnus-category-alist))
1135         (buffer-read-only nil))
1136     (gnus-delete-line)
1137     (gnus-category-write)
1138     (setq gnus-category-alist (delq info gnus-category-alist))))
1139
1140 (defun gnus-category-copy (category to)
1141   "Copy the current category."
1142   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1143   (let ((info (assq category gnus-category-alist)))
1144     (push (list to (gnus-copy-sequence (cadr info))
1145                 (gnus-copy-sequence (caddr info)) nil)
1146           gnus-category-alist)
1147     (gnus-category-write)
1148     (gnus-category-list)))
1149
1150 (defun gnus-category-add (category)
1151   "Create a new category."
1152   (interactive "SCategory name: ")
1153   (when (assq category gnus-category-alist)
1154     (error "Category %s already exists" category))
1155   (push (list category 'true nil nil)
1156         gnus-category-alist)
1157   (gnus-category-write)
1158   (gnus-category-list))
1159
1160 (defun gnus-category-list ()
1161   "List all categories."
1162   (interactive)
1163   (gnus-category-prepare))
1164
1165 (defun gnus-category-exit ()
1166   "Return to the group buffer."
1167   (interactive)
1168   (kill-buffer (current-buffer))
1169   (gnus-configure-windows 'group t))
1170
1171 ;; To avoid having 8-bit characters in the source file.
1172 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1173
1174 (defvar gnus-category-predicate-alist
1175   '((spam . gnus-agent-spam-p)
1176     (short . gnus-agent-short-p)
1177     (long . gnus-agent-long-p)
1178     (low . gnus-agent-low-scored-p)
1179     (high . gnus-agent-high-scored-p)
1180     (true . gnus-agent-true)
1181     (false . gnus-agent-false))
1182   "Mapping from short score predicate symbols to predicate functions.")
1183
1184 (defun gnus-agent-spam-p ()
1185   "Say whether an article is spam or not."
1186   (unless gnus-agent-spam-hashtb
1187     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1188   (if (not (equal (mail-header-references gnus-headers) ""))
1189       nil
1190     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1191       (prog1
1192           (gnus-gethash string gnus-agent-spam-hashtb)
1193         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1194
1195 (defun gnus-agent-short-p ()
1196   "Say whether an article is short or not."
1197   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1198
1199 (defun gnus-agent-long-p ()
1200   "Say whether an article is long or not."
1201   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1202
1203 (defun gnus-agent-low-scored-p ()
1204   "Say whether an article has a low score or not."
1205   (< gnus-score gnus-agent-low-score))
1206
1207 (defun gnus-agent-high-scored-p ()
1208   "Say whether an article has a high score or not."
1209   (> gnus-score gnus-agent-high-score))
1210
1211 (defun gnus-category-make-function (cat)
1212   "Make a function from category CAT."
1213   `(lambda () ,(gnus-category-make-function-1 cat)))
1214
1215 (defun gnus-agent-true ()
1216   "Return t."
1217   t)
1218
1219 (defun gnus-agent-false ()
1220   "Return nil."
1221   nil)
1222   
1223 (defun gnus-category-make-function-1 (cat)
1224   "Make a function from category CAT."
1225   (cond
1226    ;; Functions are just returned as is.
1227    ((or (symbolp cat)
1228         (gnus-functionp cat))
1229     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1230            cat)))
1231    ;; More complex category.
1232    ((consp cat)
1233     `(,(cond
1234         ((memq (car cat) '(& and))
1235          'and)
1236         ((memq (car cat) '(| or))
1237          'or)
1238         ((memq (car cat) gnus-category-not)
1239          'not))
1240       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1241    (t
1242     (error "Unknown category type: %s" cat))))
1243
1244 (defun gnus-get-predicate (predicate)
1245   "Return the predicate for CATEGORY."
1246   (or (cdr (assoc predicate gnus-category-predicate-cache))
1247       (cdar (push (cons predicate
1248                         (gnus-category-make-function predicate))
1249                   gnus-category-predicate-cache))))
1250
1251 (defun gnus-group-category (group)
1252   "Return the category GROUP belongs to."
1253   (unless gnus-category-group-cache
1254     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1255     (let ((cs gnus-category-alist)
1256           groups cat)
1257       (while (setq cat (pop cs))
1258         (setq groups (cadddr cat))
1259         (while groups
1260           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1261   (or (gnus-gethash group gnus-category-group-cache)
1262       (assq 'default gnus-category-alist)))
1263
1264 (defun gnus-agent-expire ()
1265   "Expire all old articles."
1266   (interactive)
1267   (let ((methods gnus-agent-covered-methods)
1268         (day (- (gnus-time-to-day (current-time)) gnus-agent-expire-days))
1269         gnus-command-method sym group articles
1270         history overview file histories elem art nov-file low info
1271         unreads marked article)
1272     (save-excursion
1273       (setq overview (gnus-get-buffer-create " *expire overview*"))
1274       (while (setq gnus-command-method (pop methods))
1275         (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1276         (gnus-agent-open-history)
1277         (set-buffer
1278          (setq gnus-agent-current-history
1279                (setq history (gnus-agent-history-buffer))))
1280         (goto-char (point-min))
1281         (when (> (buffer-size) 1)
1282           (goto-char (point-min))
1283           (while (not (eobp))
1284             (skip-chars-forward "^\t")
1285             (if (> (read (current-buffer)) day)
1286                 ;; New article; we don't expire it.
1287                 (forward-line 1)
1288               ;; Old article.  Schedule it for possible nuking.
1289               (while (not (eolp))
1290                 (setq sym (let ((obarray expiry-hashtb))
1291                             (read (current-buffer))))
1292                 (if (boundp sym)
1293                     (set sym (cons (cons (read (current-buffer)) (point))
1294                                    (symbol-value sym)))
1295                   (set sym (list (cons (read (current-buffer)) (point)))))
1296                 (skip-chars-forward " "))
1297               (forward-line 1)))
1298           ;; We now have all articles that can possibly be expired.
1299           (mapatoms
1300            (lambda (sym)
1301              (setq group (symbol-name sym)
1302                    articles (sort (symbol-value sym) 'car-less-than-car)
1303                    low (car (gnus-active group))
1304                    info (gnus-get-info group)
1305                    unreads (ignore-errors (gnus-list-of-unread-articles group))
1306                    marked (nconc (gnus-uncompress-range
1307                                   (cdr (assq 'tick (gnus-info-marks info))))
1308                                  (gnus-uncompress-range
1309                                   (cdr (assq 'dormant
1310                                              (gnus-info-marks info)))))
1311                    nov-file (gnus-agent-article-name ".overview" group))
1312              (gnus-agent-load-alist group)
1313              (gnus-message 5 "Expiring articles in %s" group)
1314              (set-buffer overview)
1315              (erase-buffer)
1316              (when (file-exists-p nov-file)
1317                (nnheader-insert-file-contents nov-file))
1318              (goto-char (point-min))
1319              (setq article 0)
1320              (while (setq elem (pop articles))
1321                (setq article (car elem))
1322                (when (or (null low)
1323                          (< article low)
1324                          gnus-agent-expire-all
1325                          (and (not (memq article unreads))
1326                               (not (memq article marked))))
1327                  ;; Find and nuke the NOV line.
1328                  (while (and (not (eobp))
1329                              (or (not (numberp
1330                                        (setq art (read (current-buffer)))))
1331                                  (< art article)))
1332                    (if (file-exists-p
1333                         (gnus-agent-article-name
1334                          (number-to-string art) group))
1335                        (forward-line 1)
1336                      ;; Remove old NOV lines that have no articles.
1337                      (gnus-delete-line)))
1338                  (if (or (eobp)
1339                          (/= art article))
1340                      (beginning-of-line)
1341                    (gnus-delete-line))
1342                  ;; Nuke the article.
1343                  (when (file-exists-p (setq file (gnus-agent-article-name
1344                                                   (number-to-string article)
1345                                                   group)))
1346                    (delete-file file))
1347                  ;; Schedule the history line for nuking.
1348                  (push (cdr elem) histories)))
1349              (gnus-make-directory (file-name-directory nov-file))
1350              (write-region (point-min) (point-max) nov-file nil 'silent)
1351              ;; Delete the unwanted entries in the alist.
1352              (setq gnus-agent-article-alist
1353                    (sort gnus-agent-article-alist 'car-less-than-car))
1354              (let* ((alist gnus-agent-article-alist)
1355                     (prev (cons nil alist))
1356                     (first prev))
1357                (while (and alist
1358                            (<= (caar alist) article))
1359                  (if (or (not (cdar alist))
1360                          (not (file-exists-p
1361                                (gnus-agent-article-name
1362                                 (number-to-string
1363                                  (caar alist))
1364                                 group))))
1365                      (setcdr prev (setq alist (cdr alist)))
1366                    (setq prev alist
1367                          alist (cdr alist))))
1368                (setq gnus-agent-article-alist (cdr first))
1369                ;;; Mark all articles up to the first article
1370                ;;; in `gnus-article-alist' as read.
1371                (when (caar gnus-agent-article-alist)
1372                  (setcar (nthcdr 2 info)
1373                          (gnus-range-add
1374                           (nth 2 info)
1375                           (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1376                (gnus-dribble-enter
1377                 (concat "(gnus-group-set-info '"
1378                         (gnus-prin1-to-string info)
1379                         ")"))
1380                (gnus-agent-save-alist group)))
1381            expiry-hashtb)
1382           (set-buffer history)
1383           (setq histories (nreverse (sort histories '<)))
1384           (while histories
1385             (goto-char (pop histories))
1386             (gnus-delete-line))
1387           (gnus-agent-save-history)
1388           (gnus-agent-close-history))
1389         (gnus-message 4 "Expiry...done"))))))
1390
1391 ;;;###autoload
1392 (defun gnus-agent-batch ()
1393   (interactive)
1394   (let ((init-file-user "")
1395         (gnus-always-read-dribble-file t))
1396     (gnus))
1397   (gnus-group-send-drafts)
1398   (gnus-agent-fetch-session))
1399
1400 (provide 'gnus-agent)
1401
1402 ;;; gnus-agent.el ends here