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