Synch to Gnus 200311211553.
[elisp/gnus.git-] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Semi-gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (eval-when-compile (require 'gnus-clfns))
30
31 (require 'gnus)
32 (require 'gnus-cache)
33 (require 'nnmail)
34 (require 'nnvirtual)
35 (require 'gnus-sum)
36 (require 'gnus-score)
37 (require 'gnus-srvr)
38 (require 'gnus-util)
39 (eval-when-compile
40   (if (featurep 'xemacs)
41       (require 'itimer)
42     (require 'timer))
43   (require 'gnus-group))
44
45 (eval-and-compile
46   (autoload 'gnus-server-update-server "gnus-srvr")
47   (autoload 'gnus-agent-customize-category "gnus-cus")
48 )
49
50 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
51   "Where the Gnus agent will store its files."
52   :group 'gnus-agent
53   :type 'directory)
54
55 (defcustom gnus-agent-plugged-hook nil
56   "Hook run when plugging into the network."
57   :group 'gnus-agent
58   :type 'hook)
59
60 (defcustom gnus-agent-unplugged-hook nil
61   "Hook run when unplugging from the network."
62   :group 'gnus-agent
63   :type 'hook)
64
65 (defcustom gnus-agent-fetched-hook nil
66   "Hook run when finished fetching articles."
67   :group 'gnus-agent
68   :type 'hook)
69
70 (defcustom gnus-agent-handle-level gnus-level-subscribed
71   "Groups on levels higher than this variable will be ignored by the Agent."
72   :group 'gnus-agent
73   :type 'integer)
74
75 (defcustom gnus-agent-expire-days 7
76   "Read articles older than this will be expired."
77   :group 'gnus-agent
78   :type '(number :tag "days"))
79
80 (defcustom gnus-agent-expire-all nil
81   "If non-nil, also expire unread, ticked and dormant articles.
82 If nil, only read articles will be expired."
83   :group 'gnus-agent
84   :type 'boolean)
85
86 (defcustom gnus-agent-group-mode-hook nil
87   "Hook run in Agent group minor modes."
88   :group 'gnus-agent
89   :type 'hook)
90
91 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
92 (when (featurep 'xemacs)
93   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
94
95 (defcustom gnus-agent-summary-mode-hook nil
96   "Hook run in Agent summary minor modes."
97   :group 'gnus-agent
98   :type 'hook)
99
100 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
101 (when (featurep 'xemacs)
102   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
103
104 (defcustom gnus-agent-server-mode-hook nil
105   "Hook run in Agent summary minor modes."
106   :group 'gnus-agent
107   :type 'hook)
108
109 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
110 (when (featurep 'xemacs)
111   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
112
113 (defcustom gnus-agent-confirmation-function 'y-or-n-p
114   "Function to confirm when error happens."
115   :version "21.1"
116   :group 'gnus-agent
117   :type 'function)
118
119 (defcustom gnus-agent-large-newsgroup nil
120   "*The number of articles which indicates a large newsgroup.
121 If the number of unread articles exceeds it, The number of articles to be
122 fetched will be limited to it. If not a positive integer, never consider it."
123   :group 'gnus-agent
124   :type '(choice (const nil)
125                  (integer :tag "Number")))
126
127 (defcustom gnus-agent-synchronize-flags 'ask
128   "Indicate if flags are synchronized when you plug in.
129 If this is `ask' the hook will query the user."
130   :version "21.1"
131   :type '(choice (const :tag "Always" t)
132                  (const :tag "Never" nil)
133                  (const :tag "Ask" ask))
134   :group 'gnus-agent)
135
136 (defcustom gnus-agent-go-online 'ask
137   "Indicate if offline servers go online when you plug in.
138 If this is `ask' the hook will query the user."
139   :version "21.1"
140   :type '(choice (const :tag "Always" t)
141                  (const :tag "Never" nil)
142                  (const :tag "Ask" ask))
143   :group 'gnus-agent)
144
145 (defcustom gnus-agent-mark-unread-after-downloaded t
146   "Indicate whether to mark articles unread after downloaded."
147   :version "21.1"
148   :type 'boolean
149   :group 'gnus-agent)
150
151 (defcustom gnus-agent-download-marks '(download)
152   "Marks for downloading."
153   :version "21.1"
154   :type '(repeat (symbol :tag "Mark"))
155   :group 'gnus-agent)
156
157 (defcustom gnus-agent-consider-all-articles nil
158   "If non-nil, consider also the read articles for downloading."
159   :version "21.4"
160   :type 'boolean
161   :group 'gnus-agent)
162
163 (defcustom gnus-agent-max-fetch-size 10000000 ;; 10 Mb
164   "Chunk size for `gnus-agent-fetch-session'.
165 The function will split its article fetches into chunks smaller than
166 this limit."
167   :group 'gnus-agent
168   :type 'integer)
169
170 (defcustom gnus-agent-enable-expiration 'ENABLE
171   "The default expiration state for each group.
172 When set to ENABLE, the default, `gnus-agent-expire' will expire old
173 contents from a group's local storage.  This value may be overridden
174 to disable expiration in specific categories, topics, and groups.  Of
175 course, you could change gnus-agent-enable-expiration to DISABLE then
176 enable expiration per categories, topics, and groups."
177   :group 'gnus-agent
178   :type '(radio (const :format "Enable " ENABLE)
179                 (const :format "Disable " DISABLE)))
180
181 (defcustom gnus-agent-expire-unagentized-dirs t
182 "Have gnus-agent-expire scan the directories under
183 \(gnus-agent-directory) for groups that are no longer agentized.  When
184 found, offer to remove them.")
185
186 ;;; Internal variables
187
188 (defvar gnus-agent-history-buffers nil)
189 (defvar gnus-agent-buffer-alist nil)
190 (defvar gnus-agent-article-alist nil
191   "An assoc list identifying the articles whose headers have been fetched.  
192 If successfully fetched, these headers will be stored in the group's overview
193 file.  The key of each assoc pair is the article ID, the value of each assoc
194 pair is a flag indicating whether the identified article has been downloaded
195 \(gnus-agent-fetch-articles sets the value to the day of the download).
196 NOTES:
197 1) The last element of this list can not be expired as some 
198    routines (for example, get-agent-fetch-headers) use the last
199    value to track which articles have had their headers retrieved.
200 2) The function `gnus-agent-regenerate' may destructively modify the value.")
201 (defvar gnus-agent-group-alist nil)
202 (defvar gnus-category-alist nil)
203 (defvar gnus-agent-current-history nil)
204 (defvar gnus-agent-overview-buffer nil)
205 (defvar gnus-category-predicate-cache nil)
206 (defvar gnus-category-group-cache nil)
207 (defvar gnus-agent-spam-hashtb nil)
208 (defvar gnus-agent-file-name nil)
209 (defvar gnus-agent-send-mail-function nil)
210 (defvar gnus-agent-file-coding-system 'raw-text)
211 (defvar gnus-agent-file-loading-cache nil)
212 (defvar gnus-agent-file-header-cache nil)
213
214 (defvar gnus-agent-auto-agentize-methods '(nntp nnimap)
215   "Initially, all servers from these methods are agentized.
216 The user may remove or add servers using the Server buffer.  See Info
217 node `(gnus)Server Buffer'.")
218
219 ;; Dynamic variables
220 (defvar gnus-headers)
221 (defvar gnus-score)
222
223 ;;;
224 ;;; Setup
225 ;;;
226
227 (defun gnus-open-agent ()
228   (setq gnus-agent t)
229   (gnus-agent-read-servers)
230   (gnus-category-read)
231   (gnus-agent-create-buffer)
232   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
233   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
234   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
235
236 (defun gnus-agent-create-buffer ()
237   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
238       t
239     (setq gnus-agent-overview-buffer
240           (gnus-get-buffer-create " *Gnus agent overview*"))
241     (with-current-buffer gnus-agent-overview-buffer
242       (set-buffer-multibyte t))
243     nil))
244
245 (gnus-add-shutdown 'gnus-close-agent 'gnus)
246
247 (defun gnus-close-agent ()
248   (setq gnus-category-predicate-cache nil
249         gnus-category-group-cache nil
250         gnus-agent-spam-hashtb nil)
251   (gnus-kill-buffer gnus-agent-overview-buffer))
252
253 ;;;
254 ;;; Utility functions
255 ;;;
256
257 (defun gnus-agent-read-file (file)
258   "Load FILE and do a `read' there."
259   (with-temp-buffer
260     (ignore-errors
261       (nnheader-insert-file-contents file)
262       (goto-char (point-min))
263       (read (current-buffer)))))
264
265 (defsubst gnus-agent-method ()
266   (concat (symbol-name (car gnus-command-method)) "/"
267           (if (equal (cadr gnus-command-method) "")
268               "unnamed"
269             (cadr gnus-command-method))))
270
271 (defsubst gnus-agent-directory ()
272   "The name of the Gnus agent directory."
273   (nnheader-concat gnus-agent-directory
274                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
275
276 (defun gnus-agent-lib-file (file)
277   "The full name of the Gnus agent library FILE."
278   (expand-file-name file
279                     (file-name-as-directory
280                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
281
282 (defun gnus-agent-cat-set-property (category property value)
283   (if value
284       (setcdr (or (assq property category)
285               (let ((cell (cons property nil)))
286                     (setcdr category (cons cell (cdr category)))
287                     cell)) value)
288     (let ((category category))
289       (while (cond ((eq property (caadr category))
290                     (setcdr category (cddr category))
291                     nil)
292                    (t
293                     (setq category (cdr category)))))))
294   category)
295
296 (eval-when-compile
297   (defmacro gnus-agent-cat-defaccessor (name prop-name)
298     "Define accessor and setter methods for manipulating a list of the form
299 \(NAME (PROPERTY1 VALUE1) ... (PROPERTY_N VALUE_N)).
300 Given the call (gnus-agent-cat-defaccessor func PROPERTY1), the list may be
301 manipulated as follows:
302   (func LIST): Returns VALUE1
303   (setf (func LIST) NEW_VALUE1): Replaces VALUE1 with NEW_VALUE1."
304     `(progn (defmacro ,name (category)
305               (list (quote cdr) (list (quote assq)
306                                       (quote (quote ,prop-name)) category)))
307
308             (define-setf-method ,name (category)
309               (let* ((--category--temp-- (make-symbol "--category--"))
310                      (--value--temp-- (make-symbol "--value--")))
311                 (list (list --category--temp--) ; temporary-variables
312                       (list category)   ; value-forms
313                       (list --value--temp--) ; store-variables
314                       (let* ((category --category--temp--) ; store-form
315                              (value --value--temp--))
316                         (list (quote gnus-agent-cat-set-property)
317                               category
318                               (quote (quote ,prop-name))
319                               value))
320                       (list (quote ,name) --category--temp--) ; access-form
321                       )))))
322   )
323
324 (defmacro gnus-agent-cat-name (category)
325   `(car ,category))
326
327 (gnus-agent-cat-defaccessor
328  gnus-agent-cat-days-until-old             agent-days-until-old)
329 (gnus-agent-cat-defaccessor
330  gnus-agent-cat-enable-expiration          agent-enable-expiration)
331 (gnus-agent-cat-defaccessor
332  gnus-agent-cat-groups                     agent-groups)
333 (gnus-agent-cat-defaccessor
334  gnus-agent-cat-high-score                 agent-high-score)
335 (gnus-agent-cat-defaccessor
336  gnus-agent-cat-length-when-long           agent-length-when-long)
337 (gnus-agent-cat-defaccessor
338  gnus-agent-cat-length-when-short          agent-length-when-short)
339 (gnus-agent-cat-defaccessor
340  gnus-agent-cat-low-score                  agent-low-score)
341 (gnus-agent-cat-defaccessor
342  gnus-agent-cat-predicate                  agent-predicate)
343 (gnus-agent-cat-defaccessor
344  gnus-agent-cat-score-file                 agent-score-file)
345 (gnus-agent-cat-defaccessor
346  gnus-agent-cat-disable-undownloaded-faces agent-disable-undownloaded-faces)
347
348 (eval-when-compile
349   (defsetf gnus-agent-cat-groups (category) (groups)
350     (list 'gnus-agent-set-cat-groups category groups)))
351
352 (defun gnus-agent-set-cat-groups (category groups)
353   (unless (eq groups 'ignore)
354     (let ((new-g groups)
355           (old-g (gnus-agent-cat-groups category)))
356       (cond ((eq new-g old-g)
357              ;; gnus-agent-add-group is fiddling with the group
358              ;; list. Still, Im done.
359              nil
360              )
361             ((eq new-g (cdr old-g))
362              ;; gnus-agent-add-group is fiddling with the group list
363              (setcdr (or (assq 'agent-groups category)
364                          (let ((cell (cons 'agent-groups nil)))
365                            (setcdr category (cons cell (cdr category)))
366                            cell)) new-g))
367             (t
368              (let ((groups groups))
369                (while groups
370                  (let* ((group        (pop groups))
371                         (old-category (gnus-group-category group)))
372                    (if (eq category old-category)
373                        nil
374                      (setf (gnus-agent-cat-groups old-category)
375                            (delete group (gnus-agent-cat-groups
376                                           old-category))))))
377                ;; Purge cache as preceeding loop invalidated it.
378                (setq gnus-category-group-cache nil))
379
380              (setcdr (or (assq 'agent-groups category)
381                          (let ((cell (cons 'agent-groups nil)))
382                            (setcdr category (cons cell (cdr category)))
383                            cell)) groups))))))
384
385 (defsubst gnus-agent-cat-make (name &optional default-agent-predicate)
386   (list name `(agent-predicate . ,(or default-agent-predicate 'false))))
387
388 ;;; Fetching setup functions.
389
390 (defun gnus-agent-start-fetch ()
391   "Initialize data structures for efficient fetching."
392   (gnus-agent-create-buffer))
393
394 (defun gnus-agent-stop-fetch ()
395   "Save all data structures and clean up."
396   (setq gnus-agent-spam-hashtb nil)
397   (save-excursion
398     (set-buffer nntp-server-buffer)
399     (widen)))
400
401 (defmacro gnus-agent-with-fetch (&rest forms)
402   "Do FORMS safely."
403   `(unwind-protect
404        (let ((gnus-agent-fetching t))
405          (gnus-agent-start-fetch)
406          ,@forms)
407      (gnus-agent-stop-fetch)))
408
409 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
410 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
411
412 (defmacro gnus-agent-append-to-list (tail value)
413   `(setq ,tail (setcdr ,tail (cons ,value nil))))
414
415 (defmacro gnus-agent-message (level &rest args)
416   `(if (<= ,level gnus-verbose)
417        (message ,@args)))
418
419 ;;;
420 ;;; Mode infestation
421 ;;;
422
423 (defvar gnus-agent-mode-hook nil
424   "Hook run when installing agent mode.")
425
426 (defvar gnus-agent-mode nil)
427 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
428
429 (defun gnus-agent-mode ()
430   "Minor mode for providing a agent support in Gnus buffers."
431   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
432                                       (symbol-name major-mode))
433                         (match-string 1 (symbol-name major-mode))))
434          (mode (intern (format "gnus-agent-%s-mode" buffer))))
435     (set (make-local-variable 'gnus-agent-mode) t)
436     (set mode nil)
437     (set (make-local-variable mode) t)
438     ;; Set up the menu.
439     (when (gnus-visual-p 'agent-menu 'menu)
440       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
441     (unless (assq 'gnus-agent-mode minor-mode-alist)
442       (push gnus-agent-mode-status minor-mode-alist))
443     (unless (assq mode minor-mode-map-alist)
444       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
445                                                      buffer))))
446             minor-mode-map-alist))
447     (when (eq major-mode 'gnus-group-mode)
448       (let ((init-plugged gnus-plugged)
449             (gnus-agent-go-online nil))
450         ;; g-a-t-p does nothing when gnus-plugged isn't changed.
451         ;; Therefore, make certain that the current value does not
452         ;; match the desired initial value.
453         (setq gnus-plugged :unknown)
454         (gnus-agent-toggle-plugged init-plugged)))
455     (gnus-run-hooks 'gnus-agent-mode-hook
456                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
457
458 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
459 (gnus-define-keys gnus-agent-group-mode-map
460   "Ju" gnus-agent-fetch-groups
461   "Jc" gnus-enter-category-buffer
462   "Jj" gnus-agent-toggle-plugged
463   "Js" gnus-agent-fetch-session
464   "JY" gnus-agent-synchronize-flags
465   "JS" gnus-group-send-queue
466   "Ja" gnus-agent-add-group
467   "Jr" gnus-agent-remove-group
468   "Jo" gnus-agent-toggle-group-plugged)
469
470 (defun gnus-agent-group-make-menu-bar ()
471   (unless (boundp 'gnus-agent-group-menu)
472     (easy-menu-define
473      gnus-agent-group-menu gnus-agent-group-mode-map ""
474      '("Agent"
475        ["Toggle plugged" gnus-agent-toggle-plugged t]
476        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
477        ["List categories" gnus-enter-category-buffer t]
478        ["Add (current) group to category" gnus-agent-add-group t]
479        ["Remove (current) group from category" gnus-agent-remove-group t]
480        ["Send queue" gnus-group-send-queue gnus-plugged]
481        ("Fetch"
482         ["All" gnus-agent-fetch-session gnus-plugged]
483         ["Group" gnus-agent-fetch-group gnus-plugged])
484        ["Synchronize flags" gnus-agent-synchronize-flags t]
485        ))))
486
487 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
488 (gnus-define-keys gnus-agent-summary-mode-map
489   "Jj" gnus-agent-toggle-plugged
490   "Ju" gnus-agent-summary-fetch-group
491   "JS" gnus-agent-fetch-group
492   "Js" gnus-agent-summary-fetch-series
493   "J#" gnus-agent-mark-article
494   "J\M-#" gnus-agent-unmark-article
495   "@" gnus-agent-toggle-mark
496   "Jc" gnus-agent-catchup)
497
498 (defun gnus-agent-summary-make-menu-bar ()
499   (unless (boundp 'gnus-agent-summary-menu)
500     (easy-menu-define
501      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
502      '("Agent"
503        ["Toggle plugged" gnus-agent-toggle-plugged t]
504        ["Mark as downloadable" gnus-agent-mark-article t]
505        ["Unmark as downloadable" gnus-agent-unmark-article t]
506        ["Toggle mark" gnus-agent-toggle-mark t]
507        ["Fetch downloadable" gnus-agent-summary-fetch-group t]
508        ["Catchup undownloaded" gnus-agent-catchup t]))))
509
510 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
511 (gnus-define-keys gnus-agent-server-mode-map
512   "Jj" gnus-agent-toggle-plugged
513   "Ja" gnus-agent-add-server
514   "Jr" gnus-agent-remove-server)
515
516 (defun gnus-agent-server-make-menu-bar ()
517   (unless (boundp 'gnus-agent-server-menu)
518     (easy-menu-define
519      gnus-agent-server-menu gnus-agent-server-mode-map ""
520      '("Agent"
521        ["Toggle plugged" gnus-agent-toggle-plugged t]
522        ["Add" gnus-agent-add-server t]
523        ["Remove" gnus-agent-remove-server t]))))
524
525 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
526   (if (and (fboundp 'propertize)
527            (fboundp 'make-mode-line-mouse-map))
528       (propertize string 'local-map
529                   (make-mode-line-mouse-map mouse-button mouse-func))
530     string))
531
532 (defun gnus-agent-toggle-plugged (set-to)
533   "Toggle whether Gnus is unplugged or not."
534   (interactive (list (not gnus-plugged)))
535   (cond ((eq set-to gnus-plugged)
536          nil)
537         (set-to
538          (setq gnus-plugged set-to)
539          (gnus-run-hooks 'gnus-agent-plugged-hook)
540          (setcar (cdr gnus-agent-mode-status)
541                  (gnus-agent-make-mode-line-string " Plugged"
542                                                    'mouse-2
543                                                    'gnus-agent-toggle-plugged))
544          (gnus-agent-go-online gnus-agent-go-online)
545          (gnus-agent-possibly-synchronize-flags))
546         (t
547          (gnus-agent-close-connections)
548          (setq gnus-plugged set-to)
549          (gnus-run-hooks 'gnus-agent-unplugged-hook)
550          (setcar (cdr gnus-agent-mode-status)
551                  (gnus-agent-make-mode-line-string " Unplugged"
552                                                    'mouse-2
553                                                    'gnus-agent-toggle-plugged))))
554   (force-mode-line-update)
555   (set-buffer-modified-p t))
556
557 (defmacro gnus-agent-while-plugged (&rest body)
558   `(let ((original-gnus-plugged gnus-plugged))
559     (unwind-protect
560         (progn (gnus-agent-toggle-plugged t)
561                ,@body)
562       (gnus-agent-toggle-plugged original-gnus-plugged))))
563
564 (put 'gnus-agent-while-plugged 'lisp-indent-function 0)
565 (put 'gnus-agent-while-plugged 'edebug-form-spec '(body))
566
567 (defun gnus-agent-close-connections ()
568   "Close all methods covered by the Gnus agent."
569   (let ((methods (gnus-agent-covered-methods)))
570     (while methods
571       (gnus-close-server (pop methods)))))
572
573 ;;;###autoload
574 (defun gnus-unplugged ()
575   "Start Gnus unplugged."
576   (interactive)
577   (setq gnus-plugged nil)
578   (gnus))
579
580 ;;;###autoload
581 (defun gnus-plugged ()
582   "Start Gnus plugged."
583   (interactive)
584   (setq gnus-plugged t)
585   (gnus))
586
587 ;;;###autoload
588 (defun gnus-slave-unplugged (&optional arg)
589   "Read news as a slave unplugged."
590   (interactive "P")
591   (setq gnus-plugged nil)
592   (gnus arg nil 'slave))
593
594 ;;;###autoload
595 (defun gnus-agentize ()
596   "Allow Gnus to be an offline newsreader.
597
598 The gnus-agentize function is now called internally by gnus when
599 gnus-agent is set.  If you wish to avoid calling gnus-agentize,
600 customize gnus-agent to nil.
601
602 This will modify the `gnus-setup-news-hook', and
603 `message-send-mail-real-function' variables, and install the Gnus agent
604 minor mode in all Gnus buffers."
605   (interactive)
606   (gnus-open-agent)
607   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
608   (unless gnus-agent-send-mail-function
609     (setq gnus-agent-send-mail-function
610           (or message-send-mail-real-function
611               message-send-mail-function)
612           message-send-mail-real-function 'gnus-agent-send-mail))
613
614   (unless gnus-agent-covered-methods
615     (mapc
616      (lambda (server-or-method)
617        (let ((method (gnus-server-to-method server-or-method)))
618          (when (memq (car method)
619                      gnus-agent-auto-agentize-methods)
620            (push (gnus-method-to-server method)
621                  gnus-agent-covered-methods)
622            (setq gnus-agent-method-p-cache nil))))
623      (cons gnus-select-method gnus-secondary-select-methods))))
624
625 (defun gnus-agent-queue-setup (&optional group-name)
626   "Make sure the queue group exists.
627 Optional arg GROUP-NAME allows to specify another group."
628   (unless (gnus-gethash (format "nndraft:%s" (or group-name "queue"))
629                         gnus-newsrc-hashtb)
630     (gnus-request-create-group (or group-name "queue") '(nndraft ""))
631     (let ((gnus-level-default-subscribed 1))
632       (gnus-subscribe-group (format "nndraft:%s" (or group-name "queue"))
633                             nil '(nndraft "")))
634     (gnus-group-set-parameter
635      (format "nndraft:%s" (or group-name "queue"))
636      'gnus-dummy '((gnus-draft-mode)))))
637
638 (defun gnus-agent-send-mail ()
639   (if gnus-plugged
640       (funcall gnus-agent-send-mail-function)
641     (goto-char (point-min))
642     (re-search-forward
643      (concat "^" (regexp-quote mail-header-separator) "\n"))
644     (replace-match "\n")
645     (gnus-agent-insert-meta-information 'mail)
646     (gnus-request-accept-article "nndraft:queue" nil t t)))
647
648 (defun gnus-agent-insert-meta-information (type &optional method)
649   "Insert meta-information into the message that says how it's to be posted.
650 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
651 be a select method."
652   (save-excursion
653     (message-remove-header gnus-agent-meta-information-header)
654     (goto-char (point-min))
655     (insert gnus-agent-meta-information-header ": "
656             (symbol-name type) " " (format "%S" method)
657             "\n")
658     (forward-char -1)
659     (while (search-backward "\n" nil t)
660       (replace-match "\\n" t t))))
661
662 (defun gnus-agent-restore-gcc ()
663   "Restore GCC field from saved header."
664   (save-excursion
665     (goto-char (point-min))
666     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
667       (replace-match "Gcc:" 'fixedcase))))
668
669 (defun gnus-agent-any-covered-gcc ()
670   (save-restriction
671     (message-narrow-to-headers)
672     (let* ((gcc (mail-fetch-field "gcc" nil t))
673            (methods (and gcc
674                          (mapcar 'gnus-inews-group-method
675                                  (message-unquote-tokens
676                                   (message-tokenize-header
677                                    gcc " ,")))))
678            covered)
679       (while (and (not covered) methods)
680         (setq covered (gnus-agent-method-p (car methods))
681               methods (cdr methods)))
682       covered)))
683
684 ;;;###autoload
685 (defun gnus-agent-possibly-save-gcc ()
686   "Save GCC if Gnus is unplugged."
687   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
688     (save-excursion
689       (goto-char (point-min))
690       (let ((case-fold-search t))
691         (while (re-search-forward "^gcc:" nil t)
692           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
693
694 (defun gnus-agent-possibly-do-gcc ()
695   "Do GCC if Gnus is plugged."
696   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
697     (gnus-inews-do-gcc)))
698
699 ;;;
700 ;;; Group mode commands
701 ;;;
702
703 (defun gnus-agent-fetch-groups (n)
704   "Put all new articles in the current groups into the Agent."
705   (interactive "P")
706   (unless gnus-plugged
707     (error "Groups can't be fetched when Gnus is unplugged"))
708   (gnus-group-iterate n 'gnus-agent-fetch-group))
709
710 (defun gnus-agent-fetch-group (&optional group)
711   "Put all new articles in GROUP into the Agent."
712   (interactive (list (gnus-group-group-name)))
713   (setq group (or group gnus-newsgroup-name))
714   (unless group
715     (error "No group on the current line"))
716
717   (gnus-agent-while-plugged
718     (let ((gnus-command-method (gnus-find-method-for-group group)))
719       (gnus-agent-with-fetch
720         (gnus-agent-fetch-group-1 group gnus-command-method)
721         (gnus-message 5 "Fetching %s...done" group)))))
722
723 (defun gnus-agent-add-group (category arg)
724   "Add the current group to an agent category."
725   (interactive
726    (list
727     (intern
728      (completing-read
729       "Add to category: "
730       (mapcar (lambda (cat) (list (symbol-name (car cat))))
731               gnus-category-alist)
732       nil t))
733     current-prefix-arg))
734   (let ((cat (assq category gnus-category-alist))
735         c groups)
736     (gnus-group-iterate arg
737       (lambda (group)
738         (when (gnus-agent-cat-groups (setq c (gnus-group-category group)))
739           (setf (gnus-agent-cat-groups c)
740                 (delete group (gnus-agent-cat-groups c))))
741         (push group groups)))
742     (setf (gnus-agent-cat-groups cat)
743           (nconc (gnus-agent-cat-groups cat) groups))
744     (gnus-category-write)))
745
746 (defun gnus-agent-remove-group (arg)
747   "Remove the current group from its agent category, if any."
748   (interactive "P")
749   (let (c)
750     (gnus-group-iterate arg
751       (lambda (group)
752         (when (gnus-agent-cat-groups (setq c (gnus-group-category group)))
753           (setf (gnus-agent-cat-groups c)
754                 (delete group (gnus-agent-cat-groups c))))))
755     (gnus-category-write)))
756
757 (defun gnus-agent-synchronize-flags ()
758   "Synchronize unplugged flags with servers."
759   (interactive)
760   (save-excursion
761     (dolist (gnus-command-method (gnus-agent-covered-methods))
762       (when (file-exists-p (gnus-agent-lib-file "flags"))
763         (gnus-agent-synchronize-flags-server gnus-command-method)))))
764
765 (defun gnus-agent-possibly-synchronize-flags ()
766   "Synchronize flags according to `gnus-agent-synchronize-flags'."
767   (interactive)
768   (save-excursion
769     (dolist (gnus-command-method (gnus-agent-covered-methods))
770       (when (file-exists-p (gnus-agent-lib-file "flags"))
771         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
772
773 (defun gnus-agent-synchronize-flags-server (method)
774   "Synchronize flags set when unplugged for server."
775   (let ((gnus-command-method method))
776     (when (file-exists-p (gnus-agent-lib-file "flags"))
777       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
778       (erase-buffer)
779       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
780       (if (null (gnus-check-server gnus-command-method))
781           (gnus-message 1 "Couldn't open server %s" (nth 1 gnus-command-method))
782         (while (not (eobp))
783           (if (null (eval (read (current-buffer))))
784               (gnus-delete-line)
785             (write-file (gnus-agent-lib-file "flags"))
786             (error "Couldn't set flags from file %s"
787                    (gnus-agent-lib-file "flags"))))
788         (delete-file (gnus-agent-lib-file "flags")))
789       (kill-buffer nil))))
790
791 (defun gnus-agent-possibly-synchronize-flags-server (method)
792   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
793   (when (or (and gnus-agent-synchronize-flags
794                  (not (eq gnus-agent-synchronize-flags 'ask)))
795             (and (eq gnus-agent-synchronize-flags 'ask)
796                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
797                                         (cadr method)))))
798     (gnus-agent-synchronize-flags-server method)))
799
800 ;;;
801 ;;; Server mode commands
802 ;;;
803
804 (defun gnus-agent-add-server (server)
805   "Enroll SERVER in the agent program."
806   (interactive (list (gnus-server-server-name)))
807   (unless server
808     (error "No server on the current line"))
809   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
810     (when (gnus-agent-method-p method)
811       (error "Server already in the agent program"))
812     (push (gnus-method-to-server method) gnus-agent-covered-methods)
813     (setq gnus-agent-method-p-cache nil)
814     (gnus-server-update-server server)
815     (gnus-agent-write-servers)
816     (gnus-message 1 "Entered %s into the Agent" server)))
817
818 (defun gnus-agent-remove-server (server)
819   "Remove SERVER from the agent program."
820   (interactive (list (gnus-server-server-name)))
821   (unless server
822     (error "No server on the current line"))
823   (let* ((server (gnus-server-server-name)))
824     (unless (member server gnus-agent-covered-methods)
825       (error "Server not in the agent program"))
826     (setq gnus-agent-covered-methods 
827           (delete server gnus-agent-covered-methods)
828           gnus-agent-method-p-cache nil)
829
830     (gnus-server-update-server server)
831     (gnus-agent-write-servers)
832     (gnus-message 1 "Removed %s from the agent" server)))
833
834 (defun gnus-agent-read-servers ()
835   "Read the alist of covered servers."
836   (setq gnus-agent-covered-methods 
837         (gnus-agent-read-file
838          (nnheader-concat gnus-agent-directory "lib/servers"))
839         gnus-agent-method-p-cache nil)
840
841   ;; I am called so early in start-up that I can not validate server
842   ;; names.  When that is the case, I skip the validation.  That is
843   ;; alright as the gnus startup code calls the validate methods
844   ;; directly.
845   (if gnus-server-alist
846       (gnus-agent-read-servers-validate)))
847
848 (defun gnus-agent-read-servers-validate ()
849   (mapcar (lambda (server-or-method)
850             (let* ((server (if (stringp server-or-method)
851                                server-or-method
852                              (gnus-method-to-server server-or-method)))
853                    (method (gnus-server-to-method server)))
854               (if method
855                   (unless (member server gnus-agent-covered-methods)
856                     (push server gnus-agent-covered-methods)
857                     (setq gnus-agent-method-p-cache nil))
858                 (gnus-message 1 "Ignoring disappeared server `%s'" server))))
859           (prog1 gnus-agent-covered-methods
860             (setq gnus-agent-covered-methods nil))))
861
862 (defun gnus-agent-read-servers-validate-native (native-method)
863   (setq gnus-agent-covered-methods
864         (mapcar (lambda (method)
865                   (if (or (not method)
866                           (equal method native-method))
867                       "native"
868                     method)) gnus-agent-covered-methods)))
869
870 (defun gnus-agent-write-servers ()
871   "Write the alist of covered servers."
872   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
873   (let ((coding-system-for-write nnheader-file-coding-system)
874         (output-coding-system nnheader-file-coding-system)
875         (file-name-coding-system nnmail-pathname-coding-system)
876         (pathname-coding-system nnmail-pathname-coding-system))
877     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
878       (prin1 gnus-agent-covered-methods
879              (current-buffer)))))
880
881 ;;;
882 ;;; Summary commands
883 ;;;
884
885 (defun gnus-agent-mark-article (n &optional unmark)
886   "Mark the next N articles as downloadable.
887 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
888 the mark instead.  The difference between N and the actual number of
889 articles marked is returned."
890   (interactive "p")
891   (let ((backward (< n 0))
892         (n (abs n)))
893     (while (and
894             (> n 0)
895             (progn
896               (gnus-summary-set-agent-mark
897                (gnus-summary-article-number) unmark)
898               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
899       (setq n (1- n)))
900     (when (/= 0 n)
901       (gnus-message 7 "No more articles"))
902     (gnus-summary-recenter)
903     (gnus-summary-position-point)
904     n))
905
906 (defun gnus-agent-unmark-article (n)
907   "Remove the downloadable mark from the next N articles.
908 If N is negative, unmark backward instead.  The difference between N and
909 the actual number of articles unmarked is returned."
910   (interactive "p")
911   (gnus-agent-mark-article n t))
912
913 (defun gnus-agent-toggle-mark (n)
914   "Toggle the downloadable mark from the next N articles.
915 If N is negative, toggle backward instead.  The difference between N and
916 the actual number of articles toggled is returned."
917   (interactive "p")
918   (gnus-agent-mark-article n 'toggle))
919
920 (defun gnus-summary-set-agent-mark (article &optional unmark)
921   "Mark ARTICLE as downloadable.  If UNMARK is nil, article is marked.
922 When UNMARK is t, the article is unmarked.  For any other value, the
923 article's mark is toggled."
924   (let ((unmark (cond ((eq nil unmark)
925                        nil)
926                       ((eq t unmark)
927                        t)
928                       (t
929                        (memq article gnus-newsgroup-downloadable)))))
930     (when (gnus-summary-goto-subject article nil t)
931       (gnus-summary-update-mark
932        (if unmark
933            (progn
934              (setq gnus-newsgroup-downloadable
935                    (delq article gnus-newsgroup-downloadable))
936              (gnus-article-mark article))
937          (progn
938            (setq gnus-newsgroup-downloadable
939                  (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
940            gnus-downloadable-mark)
941          )
942        'unread))))
943
944 (defun gnus-agent-get-undownloaded-list ()
945   "Construct list of articles that have not been downloaded."
946   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
947     (when (set (make-local-variable 'gnus-newsgroup-agentized)
948                (gnus-agent-method-p gnus-command-method))
949       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
950              (headers (sort (mapcar (lambda (h)
951                                       (mail-header-number h))
952                                     gnus-newsgroup-headers) '<))
953              (cached (and gnus-use-cache gnus-newsgroup-cached))
954              (undownloaded (list nil))
955              (tail-undownloaded undownloaded)
956              (unfetched (list nil))
957              (tail-unfetched unfetched))
958         (while (and alist headers)
959           (let ((a (caar alist))
960                 (h (car headers)))
961             (cond ((< a h)
962                    ;; Ignore IDs in the alist that are not being
963                    ;; displayed in the summary.
964                    (setq alist (cdr alist)))
965                   ((> a h)
966                    ;; Headers that are not in the alist should be
967                    ;; fictious (see nnagent-retrieve-headers); they
968                    ;; imply that this article isn't in the agent.
969                    (gnus-agent-append-to-list tail-undownloaded h)
970                    (gnus-agent-append-to-list tail-unfetched    h)
971                    (setq headers (cdr headers))) 
972                   ((cdar alist)
973                    (setq alist (cdr alist))
974                    (setq headers (cdr headers))
975                    nil                  ; ignore already downloaded
976                    )
977                   (t
978                    (setq alist (cdr alist))
979                    (setq headers (cdr headers))
980                    
981                    ;; This article isn't in the agent.  Check to see
982                    ;; if it is in the cache.  If it is, it's been
983                    ;; downloaded.
984                    (while (and cached (< (car cached) a))
985                      (setq cached (cdr cached)))
986                    (unless (equal a (car cached))
987                      (gnus-agent-append-to-list tail-undownloaded a))))))
988
989         (while headers
990           (let ((num (pop headers)))
991             (gnus-agent-append-to-list tail-undownloaded num)
992             (gnus-agent-append-to-list tail-unfetched    num)))
993
994         (setq gnus-newsgroup-undownloaded (cdr undownloaded)
995               gnus-newsgroup-unfetched    (cdr unfetched))))))
996
997 (defun gnus-agent-catchup ()
998   "Mark as read all unhandled articles.
999 An article is unhandled if it is neither cached, nor downloaded, nor
1000 downloadable."
1001   (interactive)
1002   (save-excursion
1003     (let ((articles gnus-newsgroup-undownloaded))
1004       (when (or gnus-newsgroup-downloadable
1005                 gnus-newsgroup-cached)
1006         (setq articles (gnus-sorted-ndifference
1007                         (gnus-sorted-ndifference
1008                          (gnus-copy-sequence articles)
1009                          gnus-newsgroup-downloadable)
1010                         gnus-newsgroup-cached)))
1011
1012       (while articles
1013         (gnus-summary-mark-article
1014          (pop articles) gnus-catchup-mark)))
1015     (gnus-summary-position-point)))
1016
1017 (defun gnus-agent-summary-fetch-series ()
1018   (interactive)
1019   (when gnus-newsgroup-processable
1020     (setq gnus-newsgroup-downloadable
1021           (let* ((dl gnus-newsgroup-downloadable)
1022                  (gnus-newsgroup-downloadable
1023                   (sort (gnus-copy-sequence gnus-newsgroup-processable) '<))
1024                  (fetched-articles (gnus-agent-summary-fetch-group)))
1025             ;; The preceeding call to (gnus-agent-summary-fetch-group)
1026             ;; updated gnus-newsgroup-downloadable to remove each
1027             ;; article successfully fetched.
1028
1029             ;; For each article that I processed, remove its
1030             ;; processable mark IF the article is no longer
1031             ;; downloadable (i.e. it's already downloaded)
1032             (dolist (article gnus-newsgroup-processable)
1033               (unless (memq article gnus-newsgroup-downloadable)
1034                 (gnus-summary-remove-process-mark article)))
1035             (gnus-sorted-ndifference dl fetched-articles)))))
1036
1037 (defun gnus-agent-summary-fetch-group (&optional all)
1038   "Fetch the downloadable articles in the group.
1039 Optional arg ALL, if non-nil, means to fetch all articles."
1040   (interactive "P")
1041   (let ((articles
1042          (if all gnus-newsgroup-articles
1043            gnus-newsgroup-downloadable))
1044         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
1045         fetched-articles)
1046     (gnus-agent-while-plugged
1047       (unless articles
1048         (error "No articles to download"))
1049       (gnus-agent-with-fetch
1050         (setq gnus-newsgroup-undownloaded
1051               (gnus-sorted-ndifference
1052                gnus-newsgroup-undownloaded
1053                (setq fetched-articles
1054                      (gnus-agent-fetch-articles
1055                       gnus-newsgroup-name articles)))))
1056       (save-excursion
1057         (dolist (article articles)
1058           (let ((was-marked-downloadable 
1059                  (memq article gnus-newsgroup-downloadable)))
1060             (cond (gnus-agent-mark-unread-after-downloaded
1061                    (setq gnus-newsgroup-downloadable
1062                          (delq article gnus-newsgroup-downloadable))
1063
1064                    ;; The downloadable mark is implemented as a
1065                    ;; type of read mark.  Therefore, marking the
1066                    ;; article as unread is sufficient to clear
1067                    ;; its downloadable flag.  
1068                    (gnus-summary-mark-article article gnus-unread-mark))
1069                   (was-marked-downloadable
1070                    (gnus-summary-set-agent-mark article t)))
1071             (when (gnus-summary-goto-subject article nil t)
1072               (gnus-summary-update-download-mark article))))))
1073     fetched-articles))
1074
1075 (defun gnus-agent-fetch-selected-article ()
1076   "Fetch the current article as it is selected.
1077 This can be added to `gnus-select-article-hook' or
1078 `gnus-mark-article-hook'."
1079   (let ((gnus-command-method gnus-current-select-method))
1080     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
1081       (when (gnus-agent-fetch-articles
1082              gnus-newsgroup-name
1083              (list gnus-current-article))
1084         (setq gnus-newsgroup-undownloaded
1085               (delq gnus-current-article gnus-newsgroup-undownloaded))
1086         (gnus-summary-update-download-mark gnus-current-article)))))
1087
1088 ;;;
1089 ;;; Internal functions
1090 ;;;
1091
1092 ;;; NOTES:
1093 ;;; The agent's active range is defined as follows:
1094 ;;;  If the agent has no record of the group, use the actual active
1095 ;;;    range.
1096 ;;;  If the agent has a record, set the agent's active range to
1097 ;;;    include the max limit of the actual active range.
1098 ;;;  When expiring, update the min limit to match the smallest of the
1099 ;;;    min article not expired or the min actual active range.
1100
1101 (defun gnus-agent-save-active (method)
1102   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
1103
1104 (defun gnus-agent-save-active-1 (method function)
1105   (when (gnus-agent-method-p method)
1106     (let* ((gnus-command-method method)
1107            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
1108            (file (gnus-agent-lib-file "active")))
1109       (funcall function nil new)
1110       (gnus-agent-write-active file new)
1111       (erase-buffer)
1112       (nnheader-insert-file-contents file))))
1113
1114 (defun gnus-agent-write-active (file new &optional literal-replacement)
1115   (let ((old new))
1116     (when (and (not literal-replacement)
1117                (file-exists-p file))
1118       (setq old (gnus-make-hashtable (count-lines (point-min) (point-max))))
1119       (with-temp-buffer
1120         (nnheader-insert-file-contents file)
1121         (gnus-active-to-gnus-format nil old))
1122       ;; Iterate over the current active groups, the current active
1123       ;; range may expand, but NOT CONTRACT, the agent's active range.
1124       (mapatoms
1125        (lambda (nsym)
1126          (let ((new-active (and nsym (boundp nsym) (symbol-value nsym))))
1127            (when new-active
1128              (let* ((osym       (intern (symbol-name nsym) old))
1129                     (old-active (and (boundp osym) (symbol-value osym))))
1130                (if old-active
1131                    (let ((new-min (car new-active))
1132                          (old-min (car old-active))
1133                          (new-max (cdr new-active))
1134                          (old-max (cdr old-active)))
1135                      (if (and (integerp new-min)
1136                               (< new-min old-min))
1137                          (setcar old-active new-min))
1138                      (if (and (integerp new-max)
1139                               (> new-max old-max))
1140                          (setcdr old-active new-max)))
1141                  (set osym new-active))))))
1142        new))
1143     (gnus-make-directory (file-name-directory file))
1144     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
1145       ;; The hashtable contains real names of groups.  However, do NOT
1146       ;; add the foreign server prefix as gnus-active-to-gnus-format
1147       ;; will add it while reading the file.
1148       (gnus-write-active-file file old nil))))
1149
1150 (defun gnus-agent-save-groups (method)
1151   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
1152
1153 (defun gnus-agent-save-group-info (method group active)
1154   (when (gnus-agent-method-p method)
1155     (let* ((gnus-command-method method)
1156            (coding-system-for-write nnheader-file-coding-system)
1157            (output-coding-system nnheader-file-coding-system)
1158            (file-name-coding-system nnmail-pathname-coding-system)
1159            (pathname-coding-system nnmail-pathname-coding-system)
1160            (file (gnus-agent-lib-file "active"))
1161            oactive-min oactive-max)
1162       (gnus-make-directory (file-name-directory file))
1163       (with-temp-file file
1164         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
1165         (set-buffer-multibyte nil)
1166         (when (file-exists-p file)
1167           (nnheader-insert-file-contents file)
1168
1169           (goto-char (point-min))
1170           (when (re-search-forward
1171                  (concat "^" (regexp-quote group) " ") nil t)
1172             (save-excursion
1173               (setq oactive-max (read (current-buffer)) ;; max
1174                     oactive-min (read (current-buffer)))) ;; min
1175             (gnus-delete-line)))
1176         (insert (format "%S %d %d y\n" (intern group)
1177                         (max (or oactive-max (cdr active)) (cdr active))
1178                         (min (or oactive-min (car active)) (car active))))
1179         (goto-char (point-max))
1180         (while (search-backward "\\." nil t)
1181           (delete-char 1))))))
1182
1183 (defun gnus-agent-group-path (group)
1184   "Translate GROUP into a file name."
1185
1186   ;; NOTE: This is what nnmail-group-pathname does as of Apr 2003.
1187   ;; The two methods must be kept synchronized, which is why
1188   ;; gnus-agent-group-pathname was added.
1189
1190   (setq group
1191         (nnheader-translate-file-chars
1192          (nnheader-replace-duplicate-chars-in-string
1193           (nnheader-replace-chars-in-string 
1194            (gnus-group-real-name group)
1195            ?/ ?_)
1196           ?. ?_)))
1197   (if (or nnmail-use-long-file-names
1198           (file-directory-p (expand-file-name group (gnus-agent-directory))))
1199       group
1200     (mm-encode-coding-string
1201      (nnheader-replace-chars-in-string group ?. ?/)
1202      nnmail-pathname-coding-system)))
1203
1204 (defun gnus-agent-group-pathname (group)
1205   "Translate GROUP into a file name."
1206   ;; nnagent uses nnmail-group-pathname to read articles while
1207   ;; unplugged.  The agent must, therefore, use the same directory
1208   ;; while plugged.
1209   (let ((gnus-command-method (or gnus-command-method
1210                                  (gnus-find-method-for-group group))))
1211     (nnmail-group-pathname (gnus-group-real-name group) (gnus-agent-directory))))
1212
1213 (defun gnus-agent-get-function (method)
1214   (if (gnus-online method)
1215       (car method)
1216     (require 'nnagent)
1217     'nnagent))
1218
1219 (defun gnus-agent-covered-methods ()
1220   "Return the subset of methods that are covered by the agent."
1221   (mapcar #'gnus-server-to-method gnus-agent-covered-methods))
1222
1223 ;;; History functions
1224
1225 (defun gnus-agent-history-buffer ()
1226   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1227
1228 (defun gnus-agent-open-history ()
1229   (save-excursion
1230     (push (cons (gnus-agent-method)
1231                 (set-buffer (gnus-get-buffer-create
1232                              (format " *Gnus agent %s history*"
1233                                      (gnus-agent-method)))))
1234           gnus-agent-history-buffers)
1235     (set-buffer-multibyte nil) ;; everything is binary
1236     (erase-buffer)
1237     (insert "\n")
1238     (let ((file (gnus-agent-lib-file "history")))
1239       (when (file-exists-p file)
1240         (nnheader-insert-file-contents file))
1241       (set (make-local-variable 'gnus-agent-file-name) file))))
1242
1243 (defun gnus-agent-close-history ()
1244   (when (gnus-buffer-live-p gnus-agent-current-history)
1245     (kill-buffer gnus-agent-current-history)
1246     (setq gnus-agent-history-buffers
1247           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1248                 gnus-agent-history-buffers))))
1249
1250 ;;;
1251 ;;; Fetching
1252 ;;;
1253
1254 (defun gnus-agent-fetch-articles (group articles)
1255   "Fetch ARTICLES from GROUP and put them into the Agent."
1256   (when articles
1257     (gnus-agent-load-alist group)
1258     (let* ((alist   gnus-agent-article-alist)
1259            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1260            (selected-sets (list nil))
1261            (current-set-size 0)
1262            article
1263            header-number)
1264       ;; Check each article
1265       (while (setq article (pop articles))
1266         ;; Skip alist entries preceeding this article
1267         (while (> article (or (caar alist) (1+ article)))
1268           (setq alist (cdr alist)))
1269
1270         ;; Prune off articles that we have already fetched.
1271         (unless (and (eq article (caar alist))
1272                      (cdar alist))
1273           ;; Skip headers preceeding this article
1274           (while (> article 
1275                     (setq header-number
1276                           (let* ((header (car headers)))
1277                             (if header
1278                                 (mail-header-number header)
1279                               (1+ article)))))
1280             (setq headers (cdr headers)))
1281
1282           ;; Add this article to the current set
1283           (setcar selected-sets (cons article (car selected-sets)))
1284
1285           ;; Update the set size, when the set is too large start a
1286           ;; new one.  I do this after adding the article as I want at
1287           ;; least one article in each set.
1288           (when (< gnus-agent-max-fetch-size
1289                    (setq current-set-size
1290                          (+ current-set-size
1291                             (if (= header-number article)
1292                                 (let ((char-size (mail-header-chars
1293                                                   (car headers))))
1294                                   (if (<= char-size 0)
1295                                       ;; The char size was missing/invalid,
1296                                       ;; assume a worst-case situation of
1297                                       ;; 65 char/line.  If the line count
1298                                       ;; is missing, arbitrarily assume a
1299                                       ;; size of 1000 characters.
1300                                     (max (* 65 (mail-header-lines
1301                                                 (car headers)))
1302                                          1000)
1303                                     char-size))
1304                               0))))
1305             (setcar selected-sets (nreverse (car selected-sets)))
1306             (setq selected-sets (cons nil selected-sets)
1307                   current-set-size 0))))
1308
1309       (when (or (cdr selected-sets) (car selected-sets))
1310         (let* ((fetched-articles (list nil))
1311                (tail-fetched-articles fetched-articles)
1312                (dir (gnus-agent-group-pathname group))
1313                (date (time-to-days (current-time)))
1314                (case-fold-search t)
1315                pos crosses id)
1316
1317           (setcar selected-sets (nreverse (car selected-sets)))
1318           (setq selected-sets (nreverse selected-sets))
1319
1320           (gnus-make-directory dir)
1321           (gnus-message 7 "Fetching articles for %s..." group)
1322
1323           (unwind-protect
1324               (while (setq articles (pop selected-sets))
1325                 ;; Fetch the articles from the backend.
1326                 (if (gnus-check-backend-function 'retrieve-articles group)
1327                     (setq pos (gnus-retrieve-articles articles group))
1328                   (with-temp-buffer
1329                     (let (article)
1330                       (while (setq article (pop articles))
1331                         (gnus-message 10 "Fetching article %s for %s..."
1332                                       article group)
1333                         (when (or
1334                                (gnus-backlog-request-article group article
1335                                                              nntp-server-buffer)
1336                                (gnus-request-article article group))
1337                           (goto-char (point-max))
1338                           (push (cons article (point)) pos)
1339                           (insert-buffer-substring nntp-server-buffer)))
1340                       (copy-to-buffer
1341                        nntp-server-buffer (point-min) (point-max))
1342                       (setq pos (nreverse pos)))))
1343                 ;; Then save these articles into the Agent.
1344                 (save-excursion
1345                   (set-buffer nntp-server-buffer)
1346                   (while pos
1347                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1348                     (goto-char (point-min))
1349                     (unless (eobp) ;; Don't save empty articles.
1350                       (when (search-forward "\n\n" nil t)
1351                         (when (search-backward "\nXrefs: " nil t)
1352                           ;; Handle cross posting.
1353                           (goto-char (match-end 0)) ; move to end of header name
1354                           (skip-chars-forward "^ ") ; skip server name
1355                           (skip-chars-forward " ")
1356                           (setq crosses nil)
1357                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1358                             (push (cons (buffer-substring (match-beginning 1)
1359                                                           (match-end 1))
1360                                         (string-to-int
1361                                          (buffer-substring (match-beginning 2)
1362                                                            (match-end 2))))
1363                                   crosses)
1364                             (goto-char (match-end 0)))
1365                           (gnus-agent-crosspost crosses (caar pos) date)))
1366                       (goto-char (point-min))
1367                       (if (not (re-search-forward
1368                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1369                           (setq id "No-Message-ID-in-article")
1370                         (setq id (buffer-substring
1371                                   (match-beginning 1) (match-end 1))))
1372                       (write-region-as-coding-system
1373                        gnus-agent-file-coding-system (point-min) (point-max)
1374                        (concat dir (number-to-string (caar pos))) nil 'silent)
1375
1376                       (gnus-agent-append-to-list
1377                        tail-fetched-articles (caar pos)))
1378                     (widen)
1379                     (setq pos (cdr pos)))))
1380
1381             (gnus-agent-save-alist group (cdr fetched-articles) date)
1382             (gnus-message 7 ""))
1383           (cdr fetched-articles))))))
1384
1385 (defun gnus-agent-crosspost (crosses article &optional date)
1386   (setq date (or date t))
1387
1388   (let (gnus-agent-article-alist group alist beg end)
1389     (save-excursion
1390       (set-buffer gnus-agent-overview-buffer)
1391       (when (nnheader-find-nov-line article)
1392         (forward-word 1)
1393         (setq beg (point))
1394         (setq end (progn (forward-line 1) (point)))))
1395     (while crosses
1396       (setq group (caar crosses))
1397       (unless (setq alist (assoc group gnus-agent-group-alist))
1398         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1399               gnus-agent-group-alist))
1400       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1401       (save-excursion
1402         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1403                                                     group)))
1404         (when (= (point-max) (point-min))
1405           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1406           (ignore-errors
1407             (nnheader-insert-file-contents
1408              (gnus-agent-article-name ".overview" group))))
1409         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1410         (insert (string-to-number (cdar crosses)))
1411         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1412         (gnus-agent-check-overview-buffer))
1413       (setq crosses (cdr crosses)))))
1414
1415 (defun gnus-agent-backup-overview-buffer ()
1416   (when gnus-newsgroup-name
1417     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1418           (cnt 0)
1419           name)
1420       (while (file-exists-p
1421               (setq name (concat root "~"
1422                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1423       (write-region (point-min) (point-max) name nil 'no-msg)
1424       (gnus-message 1 "Created backup copy of overview in %s." name)))
1425   t)
1426
1427 (defun gnus-agent-check-overview-buffer (&optional buffer)
1428   "Check the overview file given for sanity.
1429 In particular, checks that the file is sorted by article number
1430 and that there are no duplicates."
1431   (let ((prev-num -1)
1432         (backed-up nil))
1433     (save-excursion
1434       (when buffer
1435         (set-buffer buffer))
1436       (save-restriction
1437         (widen)
1438         (goto-char (point-min))
1439
1440         (while (< (point) (point-max))
1441           (let ((p (point))
1442                 (cur (condition-case nil
1443                          (read (current-buffer))
1444                        (error nil))))
1445             (cond
1446              ((or (not (integerp cur))
1447                   (not (eq (char-after) ?\t)))
1448               (or backed-up
1449                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1450               (gnus-message 1
1451                             "Overview buffer contains garbage '%s'."
1452                             (buffer-substring
1453                              p (gnus-point-at-eol))))
1454              ((= cur prev-num)
1455               (or backed-up
1456                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1457               (gnus-message 1
1458                             "Duplicate overview line for %d" cur)
1459               (delete-region (point) (progn (forward-line 1) (point))))
1460              ((< cur prev-num)
1461               (or backed-up
1462                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1463               (gnus-message 1 "Overview buffer not sorted!")
1464               (sort-numeric-fields 1 (point-min) (point-max))
1465               (goto-char (point-min))
1466               (setq prev-num -1))
1467              (t
1468               (setq prev-num cur)))
1469             (forward-line 1)))))))
1470
1471 (defun gnus-agent-flush-cache ()
1472   (save-excursion
1473     (while gnus-agent-buffer-alist
1474       (set-buffer (cdar gnus-agent-buffer-alist))
1475       (write-region-as-coding-system
1476        gnus-agent-file-coding-system
1477        (point-min) (point-max)
1478        (gnus-agent-article-name ".overview"
1479                                 (caar gnus-agent-buffer-alist))
1480        nil 'silent)
1481       (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1482     (while gnus-agent-group-alist
1483       (with-temp-file (gnus-agent-article-name
1484                        ".agentview" (caar gnus-agent-group-alist))
1485         (princ (cdar gnus-agent-group-alist))
1486         (insert "\n")
1487         (princ 1 (current-buffer))
1488         (insert "\n"))
1489       (setq gnus-agent-group-alist (cdr gnus-agent-group-alist)))))
1490
1491 (defun gnus-agent-find-parameter (group symbol)
1492   "Search for GROUPs SYMBOL in the group's parameters, the group's
1493 topic parameters, the group's category, or the customizable
1494 variables.  Returns the first non-nil value found."
1495   (or (gnus-group-find-parameter group symbol t)
1496       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1497       (symbol-value
1498        (cdr
1499         (assq symbol
1500               '((agent-short-article . gnus-agent-short-article)
1501                 (agent-long-article . gnus-agent-long-article)
1502                 (agent-low-score . gnus-agent-low-score)
1503                 (agent-high-score . gnus-agent-high-score)
1504                 (agent-days-until-old . gnus-agent-expire-days)
1505                 (agent-enable-expiration
1506                  . gnus-agent-enable-expiration)
1507                 (agent-predicate . gnus-agent-predicate)))))))
1508
1509 (defun gnus-agent-fetch-headers (group &optional force)
1510   "Fetch interesting headers into the agent.  The group's overview
1511 file will be updated to include the headers while a list of available
1512 article numbers will be returned."
1513   (let* ((fetch-all (and gnus-agent-consider-all-articles
1514                          ;; Do not fetch all headers if the predicate
1515                          ;; implies that we only consider unread articles.
1516                          (not (gnus-predicate-implies-unread
1517                                (gnus-agent-find-parameter group
1518                                                           'agent-predicate)))))
1519          (articles (if fetch-all
1520                        (gnus-uncompress-range (gnus-active group))
1521                      (gnus-list-of-unread-articles group)))
1522          (gnus-decode-encoded-word-function 'identity)
1523          (file (gnus-agent-article-name ".overview" group)))
1524     ;; Check whether the number of articles is not too large.
1525     (when (and (integerp gnus-agent-large-newsgroup)
1526                (> gnus-agent-large-newsgroup 0))
1527       (setq articles (nthcdr (max (- (length articles)
1528                                      gnus-agent-large-newsgroup)
1529                                   0)
1530                              articles)))
1531     (unless fetch-all
1532       ;; Add articles with marks to the list of article headers we want to
1533       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1534       ;; mark, but do fetch recent or seen articles if they have other, more
1535       ;; interesting marks.  (We have to fetch articles with boring marks
1536       ;; because otherwise the agent will remove their marks.)
1537       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1538         (unless (memq (car arts) '(seen recent killed cache))
1539           (setq articles (gnus-range-add articles (cdr arts)))))
1540       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1541
1542     ;; At this point, I have the list of articles to consider for
1543     ;; fetching.  This is the list that I'll return to my caller. Some
1544     ;; of these articles may have already been fetched.  That's OK as
1545     ;; the fetch article code will filter those out.  Internally, I'll
1546     ;; filter this list to just those articles whose headers need to
1547     ;; be fetched.
1548     (let ((articles articles))
1549       ;; Remove known articles.
1550       (when (and (or gnus-agent-cache
1551                      (not gnus-plugged))
1552                  (gnus-agent-load-alist group))
1553         ;; Remove articles marked as downloaded.
1554         (if fetch-all
1555             ;; I want to fetch all headers in the active range.
1556             ;; Therefore, exclude only those headers that are in the
1557             ;; article alist.
1558             ;; NOTE: This is probably NOT what I want to do after
1559             ;; agent expiration in this group.
1560             (setq articles (gnus-agent-uncached-articles articles group))
1561
1562           ;; I want to only fetch those headers that have never been
1563           ;; fetched.  Therefore, exclude all headers that are, or
1564           ;; WERE, in the article alist.
1565           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1566                 (high (cdr (gnus-active group))))
1567             ;; Low can be greater than High when the same group is
1568             ;; fetched twice in the same session {The first fetch will
1569             ;; fill the article alist such that (last
1570             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1571             ;; group))}.  The addition of one(the 1+ above) then
1572             ;; forces Low to be greater than High.  When this happens,
1573             ;; gnus-list-range-intersection returns nil which
1574             ;; indicates that no headers need to be fetched. -- Kevin
1575             (setq articles (gnus-list-range-intersection
1576                             articles (list (cons low high)))))))
1577
1578       (gnus-message
1579        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1580        (gnus-compress-sequence articles t))
1581
1582       (save-excursion
1583         (set-buffer nntp-server-buffer)
1584
1585         (if articles
1586             (progn
1587               (gnus-message 7 "Fetching headers for %s..." group)
1588
1589               ;; Fetch them.
1590               (gnus-make-directory (nnheader-translate-file-chars
1591                                     (file-name-directory file) t))
1592
1593               (unless (eq 'nov (gnus-retrieve-headers articles group))
1594                 (nnvirtual-convert-headers))
1595               (gnus-agent-check-overview-buffer)
1596               ;; Move these headers to the overview buffer so that
1597               ;; gnus-agent-braid-nov can merge them with the contents
1598               ;; of FILE.
1599               (copy-to-buffer
1600                gnus-agent-overview-buffer (point-min) (point-max))
1601               (when (file-exists-p file)
1602                 (gnus-agent-braid-nov group articles file))
1603               (gnus-agent-check-overview-buffer)
1604               (write-region-as-coding-system
1605                gnus-agent-file-coding-system
1606                (point-min) (point-max) file nil 'silent)
1607               (gnus-agent-save-alist group articles nil)
1608               articles)
1609           (ignore-errors
1610             (erase-buffer)
1611             (nnheader-insert-file-contents file)))))
1612     articles))
1613
1614 (defsubst gnus-agent-copy-nov-line (article)
1615   (let (art b e)
1616     (set-buffer gnus-agent-overview-buffer)
1617     (while (and (not (eobp))
1618                 (< (setq art (read (current-buffer))) article))
1619       (forward-line 1))
1620     (beginning-of-line)
1621     (if (or (eobp)
1622             (not (eq article art)))
1623         (set-buffer nntp-server-buffer)
1624       (setq b (point))
1625       (setq e (progn (forward-line 1) (point)))
1626       (set-buffer nntp-server-buffer)
1627       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1628
1629 (defun gnus-agent-braid-nov (group articles file)
1630   "Merge agent overview data with given file.
1631 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1632 FILE and places the combined headers into `nntp-server-buffer'."
1633   (let (start last)
1634     (set-buffer gnus-agent-overview-buffer)
1635     (goto-char (point-min))
1636     (set-buffer nntp-server-buffer)
1637     (erase-buffer)
1638     (nnheader-insert-file-contents file)
1639     (goto-char (point-max))
1640     (forward-line -1)
1641     (unless (looking-at "[0-9]+\t")
1642       ;; Remove corrupted lines
1643       (gnus-message
1644        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1645       (goto-char (point-min))
1646       (while (not (eobp))
1647         (if (looking-at "[0-9]+\t")
1648             (forward-line 1)
1649           (delete-region (point) (progn (forward-line 1) (point)))))
1650       (forward-line -1))
1651     (unless (or (= (point-min) (point-max))
1652                 (< (setq last (read (current-buffer))) (car articles)))
1653       ;; We do it the hard way.
1654       (when (nnheader-find-nov-line (car articles))
1655         ;; Replacing existing NOV entry
1656         (delete-region (point) (progn (forward-line 1) (point))))
1657       (gnus-agent-copy-nov-line (pop articles))
1658
1659       (ignore-errors
1660         (while articles
1661           (while (let ((art (read (current-buffer))))
1662                    (cond ((< art (car articles))
1663                           (forward-line 1)
1664                           t)
1665                          ((= art (car articles))
1666                           (beginning-of-line)
1667                           (delete-region
1668                            (point) (progn (forward-line 1) (point)))
1669                           nil)
1670                          (t
1671                           (beginning-of-line)
1672                           nil))))
1673
1674           (gnus-agent-copy-nov-line (pop articles)))))
1675
1676     ;; Copy the rest lines
1677     (set-buffer nntp-server-buffer)
1678     (goto-char (point-max))
1679     (when articles
1680       (when last
1681         (set-buffer gnus-agent-overview-buffer)
1682         (ignore-errors
1683           (while (<= (read (current-buffer)) last)
1684             (forward-line 1)))
1685         (beginning-of-line)
1686         (setq start (point))
1687         (set-buffer nntp-server-buffer))
1688       (insert-buffer-substring gnus-agent-overview-buffer start))))
1689
1690 ;; Keeps the compiler from warning about the free variable in
1691 ;; gnus-agent-read-agentview.
1692 (eval-when-compile
1693   (defvar gnus-agent-read-agentview))
1694
1695 (defun gnus-agent-load-alist (group)
1696   "Load the article-state alist for GROUP."
1697   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1698   (let ((gnus-agent-read-agentview group))
1699     (setq gnus-agent-article-alist
1700           (gnus-cache-file-contents
1701            (gnus-agent-article-name ".agentview" group)
1702            'gnus-agent-file-loading-cache
1703            'gnus-agent-read-agentview))))
1704
1705 ;; Save format may be either 1 or 2.  Two is the new, compressed
1706 ;; format that is still being tested.  Format 1 is uncompressed but
1707 ;; known to be reliable.
1708 (defconst gnus-agent-article-alist-save-format 2)
1709
1710 (defun gnus-agent-read-agentview (file)
1711   "Load FILE and do a `read' there."
1712   (with-temp-buffer
1713     (ignore-errors
1714       (nnheader-insert-file-contents file)
1715       (goto-char (point-min))
1716       (let ((alist (read (current-buffer)))
1717             (version (condition-case nil (read (current-buffer))
1718                        (end-of-file 0)))
1719             changed-version)
1720
1721         (cond
1722          ((= version 0)
1723           (let ((inhibit-quit t)
1724                 entry)
1725             (gnus-agent-open-history)
1726             (set-buffer (gnus-agent-history-buffer))
1727             (goto-char (point-min))
1728             (while (not (eobp))
1729               (if (and (looking-at
1730                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1731                        (string= (match-string 2)
1732                                 gnus-agent-read-agentview)
1733                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1734                   (setcdr entry (string-to-number (match-string 1))))
1735               (forward-line 1))
1736             (gnus-agent-close-history)
1737             (setq changed-version t)))
1738          ((= version 1)
1739           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1740          ((= version 2)
1741           (let (uncomp)
1742             (mapcar
1743              (lambda (comp-list)
1744                (let ((state (car comp-list))
1745                      (sequence (gnus-uncompress-sequence
1746                                 (cdr comp-list))))
1747                  (mapcar (lambda (article-id)
1748                            (setq uncomp (cons (cons article-id state) uncomp)))
1749                          sequence)))
1750              alist)
1751             (setq alist (sort uncomp
1752                               (lambda (first second)
1753                                 (< (car first) (car second))))))))
1754         (when changed-version
1755           (let ((gnus-agent-article-alist alist))
1756             (gnus-agent-save-alist gnus-agent-read-agentview)))
1757         alist))))
1758
1759 (defun gnus-agent-save-alist (group &optional articles state dir)
1760   "Save the article-state alist for GROUP."
1761   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1762          (pathname-coding-system nnmail-pathname-coding-system)
1763          (prev (cons nil gnus-agent-article-alist))
1764          (all prev)
1765          print-level print-length item article)
1766     (while (setq article (pop articles))
1767       (while (and (cdr prev)
1768                   (< (caadr prev) article))
1769         (setq prev (cdr prev)))
1770       (cond
1771        ((not (cdr prev))
1772         (setcdr prev (list (cons article state))))
1773        ((> (caadr prev) article)
1774         (setcdr prev (cons (cons article state) (cdr prev))))
1775        ((= (caadr prev) article)
1776         (setcdr (cadr prev) state)))
1777       (setq prev (cdr prev)))
1778     (setq gnus-agent-article-alist (cdr all))
1779     (if dir
1780         (gnus-make-directory dir)
1781       (gnus-make-directory (gnus-agent-article-name "" group)))
1782     (with-temp-file (if dir
1783                         (expand-file-name ".agentview" dir)
1784                       (gnus-agent-article-name ".agentview" group))
1785       (cond ((eq gnus-agent-article-alist-save-format 1)
1786              (princ gnus-agent-article-alist (current-buffer)))
1787             ((eq gnus-agent-article-alist-save-format 2)
1788              (let ((compressed nil))
1789                (mapcar (lambda (pair)
1790                          (let* ((article-id (car pair))
1791                                 (day-of-download (cdr pair))
1792                                 (comp-list (assq day-of-download compressed)))
1793                            (if comp-list
1794                                (setcdr comp-list
1795                                        (cons article-id (cdr comp-list)))
1796                              (setq compressed
1797                                    (cons (list day-of-download article-id)
1798                                          compressed)))
1799                            nil)) gnus-agent-article-alist)
1800                (mapcar (lambda (comp-list)
1801                          (setcdr comp-list
1802                                  (gnus-compress-sequence
1803                                   (nreverse (cdr comp-list)))))
1804                        compressed)
1805                (princ compressed (current-buffer)))))
1806       (insert "\n")
1807       (princ gnus-agent-article-alist-save-format (current-buffer))
1808       (insert "\n"))))
1809
1810 (defun gnus-agent-article-name (article group)
1811   (expand-file-name article
1812                     (file-name-as-directory
1813                      (gnus-agent-group-pathname group))))
1814
1815 (defun gnus-agent-batch-confirmation (msg)
1816   "Show error message and return t."
1817   (gnus-message 1 msg)
1818   t)
1819
1820 ;;;###autoload
1821 (defun gnus-agent-batch-fetch ()
1822   "Start Gnus and fetch session."
1823   (interactive)
1824   (gnus)
1825   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1826     (gnus-agent-fetch-session))
1827   (gnus-group-exit))
1828
1829 (defun gnus-agent-fetch-session ()
1830   "Fetch all articles and headers that are eligible for fetching."
1831   (interactive)
1832   (unless gnus-agent-covered-methods
1833     (error "No servers are covered by the Gnus agent"))
1834   (unless gnus-plugged
1835     (error "Can't fetch articles while Gnus is unplugged"))
1836   (let ((methods (gnus-agent-covered-methods))
1837         groups group gnus-command-method)
1838     (save-excursion
1839       (while methods
1840         (setq gnus-command-method (car methods))
1841         (when (and (or (gnus-server-opened gnus-command-method)
1842                        (gnus-open-server gnus-command-method))
1843                    (gnus-online gnus-command-method))
1844           (setq groups (gnus-groups-from-server (car methods)))
1845           (gnus-agent-with-fetch
1846             (while (setq group (pop groups))
1847               (when (<= (gnus-group-level group)
1848                         gnus-agent-handle-level)
1849                 (if (or debug-on-error debug-on-quit)
1850                     (gnus-agent-fetch-group-1
1851                      group gnus-command-method)
1852                   (condition-case err
1853                       (gnus-agent-fetch-group-1
1854                        group gnus-command-method)
1855                     (error
1856                      (unless (funcall gnus-agent-confirmation-function
1857                                       (format "Error %s.  Continue? "
1858                                               (error-message-string err)))
1859                        (error "Cannot fetch articles into the Gnus agent")))
1860                     (quit
1861                      (unless (funcall gnus-agent-confirmation-function
1862                                       (format
1863                                        "Quit fetching session %s.  Continue? "
1864                                        (error-message-string err)))
1865                        (signal 'quit
1866                                "Cannot fetch articles into the Gnus agent")))))))))
1867         (setq methods (cdr methods)))
1868       (gnus-run-hooks 'gnus-agent-fetched-hook)
1869       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1870
1871 (defun gnus-agent-fetch-group-1 (group method)
1872   "Fetch GROUP."
1873   (let ((gnus-command-method method)
1874         (gnus-newsgroup-name group)
1875         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1876         (gnus-newsgroup-headers gnus-newsgroup-headers)
1877         (gnus-newsgroup-scored gnus-newsgroup-scored)
1878         (gnus-use-cache gnus-use-cache)
1879         (gnus-summary-expunge-below gnus-summary-expunge-below)
1880         (gnus-summary-mark-below gnus-summary-mark-below)
1881         (gnus-orphan-score gnus-orphan-score)
1882         ;; Maybe some other gnus-summary local variables should also
1883         ;; be put here.
1884
1885         gnus-headers
1886         gnus-score
1887         articles arts
1888         category predicate info marks score-param
1889         )
1890     (unless (gnus-check-group group)
1891       (error "Can't open server for %s" group))
1892
1893     ;; Fetch headers.
1894     (when (or gnus-newsgroup-active
1895               (gnus-active group)
1896               (gnus-activate-group group))
1897       (let ((marked-articles gnus-newsgroup-downloadable))
1898         ;; Identify the articles marked for download
1899         (unless gnus-newsgroup-active
1900           ;; The variable gnus-newsgroup-active was selected as I need
1901           ;; a gnus-summary local variable that is NOT bound to any
1902           ;; value (its global value should default to nil).
1903           (dolist (mark gnus-agent-download-marks)
1904             (let ((arts (cdr (assq mark (gnus-info-marks
1905                                          (setq info (gnus-get-info group)))))))
1906               (when arts
1907                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1908                                              marked-articles))
1909                 ))))
1910         (setq marked-articles (sort marked-articles '<))
1911
1912         ;; Fetch any new articles from the server
1913         (setq articles (gnus-agent-fetch-headers group))
1914
1915         ;; Merge new articles with marked
1916         (setq articles (sort (append marked-articles articles) '<))
1917
1918         (when articles
1919           ;; Parse them and see which articles we want to fetch.
1920           (setq gnus-newsgroup-dependencies
1921                 (or gnus-newsgroup-dependencies
1922                     (make-vector (length articles) 0)))
1923           (setq gnus-newsgroup-headers
1924                 (or gnus-newsgroup-headers
1925                     (gnus-get-newsgroup-headers-xover articles nil nil
1926                                                       group)))
1927           ;; `gnus-agent-overview-buffer' may be killed for
1928           ;; timeout reason.  If so, recreate it.
1929           (gnus-agent-create-buffer)
1930
1931           ;; Figure out how to select articles in this group
1932           (setq category (gnus-group-category group))
1933
1934           (setq predicate
1935                 (gnus-get-predicate
1936                  (gnus-agent-find-parameter group 'agent-predicate)))
1937
1938           ;; If the selection predicate requires scoring, score each header
1939           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1940             (let ((score-param
1941                    (gnus-agent-find-parameter group 'agent-score-file)))
1942               ;; Translate score-param into real one
1943               (cond
1944                ((not score-param))
1945                ((eq score-param 'file)
1946                 (setq score-param (gnus-all-score-files group)))
1947                ((stringp (car score-param)))
1948                (t
1949                 (setq score-param (list (list score-param)))))
1950               (when score-param
1951                 (gnus-score-headers score-param))))
1952
1953           (unless (and (eq predicate 'gnus-agent-false)
1954                        (not marked-articles))
1955             (let ((arts (list nil)))
1956               (let ((arts-tail arts)
1957                     (alist (gnus-agent-load-alist group))
1958                     (marked-articles marked-articles)
1959                     (gnus-newsgroup-headers gnus-newsgroup-headers))
1960                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
1961                   (let ((num (mail-header-number gnus-headers)))
1962                     ;; Determine if this article is already in the cache
1963                     (while (and alist
1964                                 (> num (caar alist)))
1965                       (setq alist (cdr alist)))
1966
1967                     (unless (and (eq num (caar alist))
1968                                  (cdar alist))
1969
1970                       ;; Determine if this article was marked for download.
1971                       (while (and marked-articles
1972                                   (> num (car marked-articles)))
1973                         (setq marked-articles
1974                               (cdr marked-articles)))
1975
1976                       ;; When this article is marked, or selected by the
1977                       ;; predicate, add it to the download list
1978                       (when (or (eq num (car marked-articles))
1979                                 (let ((gnus-score
1980                                        (or (cdr
1981                                             (assq num gnus-newsgroup-scored))
1982                                            gnus-summary-default-score))
1983                                       (gnus-agent-long-article
1984                                        (gnus-agent-find-parameter
1985                                         group 'agent-long-article))
1986                                       (gnus-agent-short-article
1987                                        (gnus-agent-find-parameter
1988                                         group 'agent-short-article))
1989                                       (gnus-agent-low-score
1990                                        (gnus-agent-find-parameter
1991                                         group 'agent-low-score))
1992                                       (gnus-agent-high-score
1993                                        (gnus-agent-find-parameter
1994                                         group 'agent-high-score))
1995                                       (gnus-agent-expire-days
1996                                        (gnus-agent-find-parameter
1997                                         group 'agent-days-until-old)))
1998                                   (funcall predicate)))
1999                         (gnus-agent-append-to-list arts-tail num))))))
2000
2001               (let (fetched-articles)
2002                 ;; Fetch all selected articles
2003                 (setq gnus-newsgroup-undownloaded
2004                       (gnus-sorted-ndifference
2005                        gnus-newsgroup-undownloaded
2006                        (setq fetched-articles
2007                              (if (cdr arts)
2008                                  (gnus-agent-fetch-articles group (cdr arts))
2009                                nil))))
2010
2011                 (let ((unfetched-articles
2012                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2013                   (if gnus-newsgroup-active
2014                       ;; Update the summary buffer
2015                       (progn
2016                         (dolist (article marked-articles)
2017                           (gnus-summary-set-agent-mark article t))
2018                         (dolist (article fetched-articles)
2019                           (if gnus-agent-mark-unread-after-downloaded
2020                               (gnus-summary-mark-article
2021                                article gnus-unread-mark))
2022                           (when (gnus-summary-goto-subject article nil t)
2023                             (gnus-summary-update-download-mark article)))
2024                         (dolist (article unfetched-articles)
2025                           (gnus-summary-mark-article
2026                            article gnus-canceled-mark)))
2027
2028                     ;; Update the group buffer.
2029
2030                     ;; When some, or all, of the marked articles came
2031                     ;; from the download mark.  Remove that mark.  I
2032                     ;; didn't do this earlier as I only want to remove
2033                     ;; the marks after the fetch is completed.
2034
2035                     (dolist (mark gnus-agent-download-marks)
2036                       (when (eq mark 'download)
2037                         (let ((marked-arts
2038                                (assq mark (gnus-info-marks
2039                                            (setq info (gnus-get-info group))))))
2040                           (when (cdr marked-arts)
2041                             (setq marks
2042                                   (delq marked-arts (gnus-info-marks info)))
2043                             (gnus-info-set-marks info marks)))))
2044                     (let ((read (gnus-info-read
2045                                  (or info (setq info (gnus-get-info group))))))
2046                       (gnus-info-set-read
2047                        info (gnus-add-to-range read unfetched-articles)))
2048
2049                     (gnus-group-update-group group t)
2050                     (sit-for 0)
2051
2052                     (gnus-dribble-enter
2053                      (concat "(gnus-group-set-info '"
2054                              (gnus-prin1-to-string info)
2055                              ")"))))))))))))
2056
2057 ;;;
2058 ;;; Agent Category Mode
2059 ;;;
2060
2061 (defvar gnus-category-mode-hook nil
2062   "Hook run in `gnus-category-mode' buffers.")
2063
2064 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2065   "Format of category lines.
2066
2067 Valid specifiers include:
2068 %c  Topic name (string)
2069 %g  The number of groups in the topic (integer)
2070
2071 General format specifiers can also be used.  See Info node
2072 `(gnus)Formatting Variables'.")
2073
2074 (defvar gnus-category-mode-line-format "Gnus: %%b"
2075   "The format specification for the category mode line.")
2076
2077 (defvar gnus-agent-predicate 'false
2078   "The selection predicate used when no other source is available.")
2079
2080 (defvar gnus-agent-short-article 100
2081   "Articles that have fewer lines than this are short.")
2082
2083 (defvar gnus-agent-long-article 200
2084   "Articles that have more lines than this are long.")
2085
2086 (defvar gnus-agent-low-score 0
2087   "Articles that have a score lower than this have a low score.")
2088
2089 (defvar gnus-agent-high-score 0
2090   "Articles that have a score higher than this have a high score.")
2091
2092
2093 ;;; Internal variables.
2094
2095 (defvar gnus-category-buffer "*Agent Category*")
2096
2097 (defvar gnus-category-line-format-alist
2098   `((?c gnus-tmp-name ?s)
2099     (?g gnus-tmp-groups ?d)))
2100
2101 (defvar gnus-category-mode-line-format-alist
2102   `((?u user-defined ?s)))
2103
2104 (defvar gnus-category-line-format-spec nil)
2105 (defvar gnus-category-mode-line-format-spec nil)
2106
2107 (defvar gnus-category-mode-map nil)
2108 (put 'gnus-category-mode 'mode-class 'special)
2109
2110 (unless gnus-category-mode-map
2111   (setq gnus-category-mode-map (make-sparse-keymap))
2112   (suppress-keymap gnus-category-mode-map)
2113
2114   (gnus-define-keys gnus-category-mode-map
2115     "q" gnus-category-exit
2116     "k" gnus-category-kill
2117     "c" gnus-category-copy
2118     "a" gnus-category-add
2119     "e" gnus-agent-customize-category
2120     "p" gnus-category-edit-predicate
2121     "g" gnus-category-edit-groups
2122     "s" gnus-category-edit-score
2123     "l" gnus-category-list
2124
2125     "\C-c\C-i" gnus-info-find-node
2126     "\C-c\C-b" gnus-bug))
2127
2128 (defvar gnus-category-menu-hook nil
2129   "*Hook run after the creation of the menu.")
2130
2131 (defun gnus-category-make-menu-bar ()
2132   (gnus-turn-off-edit-menu 'category)
2133   (unless (boundp 'gnus-category-menu)
2134     (easy-menu-define
2135      gnus-category-menu gnus-category-mode-map ""
2136      '("Categories"
2137        ["Add" gnus-category-add t]
2138        ["Kill" gnus-category-kill t]
2139        ["Copy" gnus-category-copy t]
2140        ["Edit category" gnus-agent-customize-category t]
2141        ["Edit predicate" gnus-category-edit-predicate t]
2142        ["Edit score" gnus-category-edit-score t]
2143        ["Edit groups" gnus-category-edit-groups t]
2144        ["Exit" gnus-category-exit t]))
2145
2146     (gnus-run-hooks 'gnus-category-menu-hook)))
2147
2148 (defun gnus-category-mode ()
2149   "Major mode for listing and editing agent categories.
2150
2151 All normal editing commands are switched off.
2152 \\<gnus-category-mode-map>
2153 For more in-depth information on this mode, read the manual
2154 \(`\\[gnus-info-find-node]').
2155
2156 The following commands are available:
2157
2158 \\{gnus-category-mode-map}"
2159   (interactive)
2160   (when (gnus-visual-p 'category-menu 'menu)
2161     (gnus-category-make-menu-bar))
2162   (kill-all-local-variables)
2163   (gnus-simplify-mode-line)
2164   (setq major-mode 'gnus-category-mode)
2165   (setq mode-name "Category")
2166   (gnus-set-default-directory)
2167   (setq mode-line-process nil)
2168   (use-local-map gnus-category-mode-map)
2169   (buffer-disable-undo)
2170   (setq truncate-lines t)
2171   (setq buffer-read-only t)
2172   (gnus-run-hooks 'gnus-category-mode-hook))
2173
2174 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2175
2176 (defun gnus-category-insert-line (category)
2177   (let* ((gnus-tmp-name (format "%s" (car category)))
2178          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2179     (beginning-of-line)
2180     (gnus-add-text-properties
2181      (point)
2182      (prog1 (1+ (point))
2183        ;; Insert the text.
2184        (eval gnus-category-line-format-spec))
2185      (list 'gnus-category gnus-tmp-name))))
2186
2187 (defun gnus-enter-category-buffer ()
2188   "Go to the Category buffer."
2189   (interactive)
2190   (gnus-category-setup-buffer)
2191   (gnus-configure-windows 'category)
2192   (gnus-category-prepare))
2193
2194 (defun gnus-category-setup-buffer ()
2195   (unless (get-buffer gnus-category-buffer)
2196     (save-excursion
2197       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2198       (gnus-category-mode))))
2199
2200 (defun gnus-category-prepare ()
2201   (gnus-set-format 'category-mode)
2202   (gnus-set-format 'category t)
2203   (let ((alist gnus-category-alist)
2204         (buffer-read-only nil))
2205     (erase-buffer)
2206     (while alist
2207       (gnus-category-insert-line (pop alist)))
2208     (goto-char (point-min))
2209     (gnus-category-position-point)))
2210
2211 (defun gnus-category-name ()
2212   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
2213       (error "No category on the current line")))
2214
2215 (defun gnus-category-read ()
2216   "Read the category alist."
2217   (setq gnus-category-alist
2218         (or
2219          (with-temp-buffer
2220            (ignore-errors
2221             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2222             (goto-char (point-min))
2223             ;; This code isn't temp, it will be needed so long as
2224             ;; anyone may be migrating from an older version.
2225
2226             ;; Once we're certain that people will not revert to an
2227             ;; earlier version, we can take out the old-list code in
2228             ;; gnus-category-write.
2229             (let* ((old-list (read (current-buffer)))
2230                    (new-list (ignore-errors (read (current-buffer)))))
2231               (if new-list
2232                   new-list
2233                 ;; Convert from a positional list to an alist.
2234                 (mapcar
2235                  (lambda (c)
2236                    (setcdr c
2237                            (delq nil
2238                                  (gnus-mapcar
2239                                   (lambda (valu symb)
2240                                     (if valu
2241                                         (cons symb valu)))
2242                                   (cdr c)
2243                                   '(agent-predicate agent-score-file agent-groups))))
2244                    c)
2245                  old-list)))))
2246          (list (gnus-agent-cat-make 'default 'short)))))
2247
2248 (defun gnus-category-write ()
2249   "Write the category alist."
2250   (setq gnus-category-predicate-cache nil
2251         gnus-category-group-cache nil)
2252   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2253   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2254     ;; This prin1 is temporary.  It exists so that people can revert
2255     ;; to an earlier version of gnus-agent.
2256     (prin1 (mapcar (lambda (c)
2257               (list (car c)
2258                     (cdr (assoc 'agent-predicate c))
2259                     (cdr (assoc 'agent-score-file c))
2260                     (cdr (assoc 'agent-groups c))))
2261                    gnus-category-alist)
2262            (current-buffer))
2263     (newline)
2264     (prin1 gnus-category-alist (current-buffer))))
2265
2266 (defun gnus-category-edit-predicate (category)
2267   "Edit the predicate for CATEGORY."
2268   (interactive (list (gnus-category-name)))
2269   (let ((info (assq category gnus-category-alist)))
2270     (gnus-edit-form
2271      (gnus-agent-cat-predicate info)
2272      (format "Editing the select predicate for category %s" category)
2273      `(lambda (predicate)
2274         ;; Avoid run-time execution of setf form
2275         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2276         ;;       predicate)
2277         ;; use its expansion instead:
2278         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2279                                      'agent-predicate predicate)
2280
2281         (gnus-category-write)
2282         (gnus-category-list)))))
2283
2284 (defun gnus-category-edit-score (category)
2285   "Edit the score expression for CATEGORY."
2286   (interactive (list (gnus-category-name)))
2287   (let ((info (assq category gnus-category-alist)))
2288     (gnus-edit-form
2289      (gnus-agent-cat-score-file info)
2290      (format "Editing the score expression for category %s" category)
2291      `(lambda (score-file)
2292         ;; Avoid run-time execution of setf form
2293         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2294         ;;       score-file)
2295         ;; use its expansion instead:
2296         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2297                                      'agent-score-file score-file)
2298
2299         (gnus-category-write)
2300         (gnus-category-list)))))
2301
2302 (defun gnus-category-edit-groups (category)
2303   "Edit the group list for CATEGORY."
2304   (interactive (list (gnus-category-name)))
2305   (let ((info (assq category gnus-category-alist)))
2306     (gnus-edit-form
2307      (gnus-agent-cat-groups info)
2308      (format "Editing the group list for category %s" category)
2309      `(lambda (groups)
2310         ;; Avoid run-time execution of setf form
2311         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2312         ;;       groups)
2313         ;; use its expansion instead:
2314         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2315                                    groups)
2316
2317         (gnus-category-write)
2318         (gnus-category-list)))))
2319
2320 (defun gnus-category-kill (category)
2321   "Kill the current category."
2322   (interactive (list (gnus-category-name)))
2323   (let ((info (assq category gnus-category-alist))
2324         (buffer-read-only nil))
2325     (gnus-delete-line)
2326     (setq gnus-category-alist (delq info gnus-category-alist))
2327     (gnus-category-write)))
2328
2329 (defun gnus-category-copy (category to)
2330   "Copy the current category."
2331   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2332   (let ((info (assq category gnus-category-alist)))
2333     (push (let ((newcat (gnus-copy-sequence info)))
2334             (setf (gnus-agent-cat-name newcat) to)
2335             (setf (gnus-agent-cat-groups newcat) nil)
2336             newcat)
2337           gnus-category-alist)
2338     (gnus-category-write)
2339     (gnus-category-list)))
2340
2341 (defun gnus-category-add (category)
2342   "Create a new category."
2343   (interactive "SCategory name: ")
2344   (when (assq category gnus-category-alist)
2345     (error "Category %s already exists" category))
2346   (push (gnus-agent-cat-make category)
2347         gnus-category-alist)
2348   (gnus-category-write)
2349   (gnus-category-list))
2350
2351 (defun gnus-category-list ()
2352   "List all categories."
2353   (interactive)
2354   (gnus-category-prepare))
2355
2356 (defun gnus-category-exit ()
2357   "Return to the group buffer."
2358   (interactive)
2359   (kill-buffer (current-buffer))
2360   (gnus-configure-windows 'group t))
2361
2362 ;; To avoid having 8-bit characters in the source file.
2363 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2364
2365 (defvar gnus-category-predicate-alist
2366   '((spam . gnus-agent-spam-p)
2367     (short . gnus-agent-short-p)
2368     (long . gnus-agent-long-p)
2369     (low . gnus-agent-low-scored-p)
2370     (high . gnus-agent-high-scored-p)
2371     (read . gnus-agent-read-p)
2372     (true . gnus-agent-true)
2373     (false . gnus-agent-false))
2374   "Mapping from short score predicate symbols to predicate functions.")
2375
2376 (defun gnus-agent-spam-p ()
2377   "Say whether an article is spam or not."
2378   (unless gnus-agent-spam-hashtb
2379     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2380   (if (not (equal (mail-header-references gnus-headers) ""))
2381       nil
2382     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2383       (prog1
2384           (gnus-gethash string gnus-agent-spam-hashtb)
2385         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2386
2387 (defun gnus-agent-short-p ()
2388   "Say whether an article is short or not."
2389   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2390
2391 (defun gnus-agent-long-p ()
2392   "Say whether an article is long or not."
2393   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2394
2395 (defun gnus-agent-low-scored-p ()
2396   "Say whether an article has a low score or not."
2397   (< gnus-score gnus-agent-low-score))
2398
2399 (defun gnus-agent-high-scored-p ()
2400   "Say whether an article has a high score or not."
2401   (> gnus-score gnus-agent-high-score))
2402
2403 (defun gnus-agent-read-p ()
2404   "Say whether an article is read or not."
2405   (gnus-member-of-range (mail-header-number gnus-headers)
2406                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2407
2408 (defun gnus-category-make-function (predicate)
2409   "Make a function from PREDICATE."
2410   (let ((func (gnus-category-make-function-1 predicate)))
2411     (if (and (= (length func) 1)
2412              (symbolp (car func)))
2413         (car func)
2414       (gnus-byte-compile `(lambda () ,func)))))
2415
2416 (defun gnus-agent-true ()
2417   "Return t."
2418   t)
2419
2420 (defun gnus-agent-false ()
2421   "Return nil."
2422   nil)
2423
2424 (defun gnus-category-make-function-1 (predicate)
2425   "Make a function from PREDICATE."
2426   (cond
2427    ;; Functions are just returned as is.
2428    ((or (symbolp predicate)
2429         (functionp predicate))
2430     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2431            predicate)))
2432    ;; More complex predicate.
2433    ((consp predicate)
2434     `(,(cond
2435         ((memq (car predicate) '(& and))
2436          'and)
2437         ((memq (car predicate) '(| or))
2438          'or)
2439         ((memq (car predicate) gnus-category-not)
2440          'not))
2441       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2442    (t
2443     (error "Unknown predicate type: %s" predicate))))
2444
2445 (defun gnus-get-predicate (predicate)
2446   "Return the function implementing PREDICATE."
2447   (or (cdr (assoc predicate gnus-category-predicate-cache))
2448       (let ((func (gnus-category-make-function predicate)))
2449         (setq gnus-category-predicate-cache
2450               (nconc gnus-category-predicate-cache
2451                      (list (cons predicate func))))
2452         func)))
2453
2454 (defun gnus-predicate-implies-unread (predicate)
2455   "Say whether PREDICATE implies unread articles only.
2456 It is okay to miss some cases, but there must be no false positives.
2457 That is, if this function returns true, then indeed the predicate must
2458 return only unread articles."
2459   (gnus-function-implies-unread-1 (gnus-category-make-function predicate)))
2460
2461 (defun gnus-function-implies-unread-1 (function)
2462   (cond ((eq function (symbol-function 'gnus-agent-read-p))
2463          nil)
2464         ((not function)
2465          nil)
2466         ((functionp function)
2467          'ignore)
2468         ((memq (car function) '(or and not))
2469          (apply (car function)
2470                 (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2471         (t
2472          (error "Unknown function: %s" function))))
2473
2474 (defun gnus-group-category (group)
2475   "Return the category GROUP belongs to."
2476   (unless gnus-category-group-cache
2477     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2478     (let ((cs gnus-category-alist)
2479           groups cat)
2480       (while (setq cat (pop cs))
2481         (setq groups (gnus-agent-cat-groups cat))
2482         (while groups
2483           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2484   (or (gnus-gethash group gnus-category-group-cache)
2485       (assq 'default gnus-category-alist)))
2486
2487 (defun gnus-agent-expire-group (group &optional articles force)
2488   "Expire all old articles in GROUP.
2489 If you want to force expiring of certain articles, this function can
2490 take ARTICLES, and FORCE parameters as well.
2491
2492 The articles on which the expiration process runs are selected as follows:
2493   if ARTICLES is null, all read and unmarked articles.
2494   if ARTICLES is t, all articles.
2495   if ARTICLES is a list, just those articles.
2496 FORCE is equivalent to setting the expiration predicates to true."
2497   (interactive
2498    (list (let ((def (or (gnus-group-group-name)
2499                         gnus-newsgroup-name)))
2500            (let ((select (read-string (if def
2501                                           (concat "Group Name ("
2502                                                   def "): ")
2503                                         "Group Name: "))))
2504              (if (and (equal "" select)
2505                       def)
2506                  def
2507                select)))))
2508
2509   (if (not group)
2510       (gnus-agent-expire articles group force)
2511     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2512            ;; expiration statistics of this single group
2513           (gnus-agent-expire-stats (list 0 0 0.0)))
2514       (if (or (not (eq articles t))
2515               (yes-or-no-p
2516                (concat "Are you sure that you want to "
2517                        "expire all articles in " group ".")))
2518           (let ((gnus-command-method (gnus-find-method-for-group group))
2519                 (overview (gnus-get-buffer-create " *expire overview*"))
2520                 orig)
2521             (unwind-protect
2522                 (let ((active-file (gnus-agent-lib-file "active")))
2523                   (when (file-exists-p active-file)
2524                     (with-temp-buffer
2525                       (nnheader-insert-file-contents active-file)
2526                       (gnus-active-to-gnus-format
2527                        gnus-command-method
2528                        (setq orig (gnus-make-hashtable
2529                                    (count-lines (point-min) (point-max))))))
2530                     (save-excursion
2531                       (gnus-agent-expire-group-1
2532                        group overview (gnus-gethash-safe group orig)
2533                        articles force))
2534                     (gnus-agent-write-active active-file orig t)))
2535               (kill-buffer overview))))
2536       (gnus-message 4 (gnus-agent-expire-done-message)))))
2537
2538 (defun gnus-agent-expire-group-1 (group overview active articles force)
2539   ;; Internal function - requires caller to have set
2540   ;; gnus-command-method, initialized overview buffer, and to have
2541   ;; provided a non-nil active
2542
2543   (let ((dir (gnus-agent-group-pathname group)))
2544     (when (boundp 'gnus-agent-expire-current-dirs)
2545       (set 'gnus-agent-expire-current-dirs 
2546            (cons dir 
2547                  (symbol-value 'gnus-agent-expire-current-dirs))))
2548
2549     (if (and (not force)
2550              (eq 'DISABLE (gnus-agent-find-parameter group 
2551                                                      'agent-enable-expiration)))
2552         (gnus-message 5 "Expiry skipping over %s" group)
2553       (gnus-message 5 "Expiring articles in %s" group)
2554       (gnus-agent-load-alist group)
2555       (let* ((stats (if (boundp 'gnus-agent-expire-stats)
2556                         ;; Use the list provided by my caller
2557                         (symbol-value 'gnus-agent-expire-stats)
2558                       ;; otherwise use my own temporary list
2559                       (list 0 0 0.0)))
2560              (info (gnus-get-info group))
2561              (alist gnus-agent-article-alist)
2562              (day (- (time-to-days (current-time))
2563                      (gnus-agent-find-parameter group 'agent-days-until-old)))
2564              (specials (if (and alist
2565                                 (not force))
2566                            ;; This could be a bit of a problem.  I need to
2567                            ;; keep the last article to avoid refetching
2568                            ;; headers when using nntp in the backend.  At
2569                            ;; the same time, if someone uses a backend
2570                            ;; that supports article moving then I may have
2571                            ;; to remove the last article to complete the
2572                            ;; move.  Right now, I'm going to assume that
2573                            ;; FORCE overrides specials.
2574                            (list (caar (last alist)))))
2575              (unreads ;; Articles that are excluded from the
2576               ;; expiration process
2577               (cond (gnus-agent-expire-all
2578                      ;; All articles are marked read by global decree
2579                      nil)
2580                     ((eq articles t)
2581                      ;; All articles are marked read by function
2582                      ;; parameter
2583                      nil)
2584                     ((not articles)
2585                      ;; Unread articles are marked protected from
2586                      ;; expiration Don't call
2587                      ;; gnus-list-of-unread-articles as it returns
2588                      ;; articles that have not been fetched into the
2589                      ;; agent.
2590                      (ignore-errors
2591                        (gnus-agent-unread-articles group)))
2592                     (t
2593                      ;; All articles EXCEPT those named by the caller
2594                      ;; are protected from expiration
2595                      (gnus-sorted-difference
2596                       (gnus-uncompress-range
2597                        (cons (caar alist)
2598                              (caar (last alist))))
2599                       (sort articles '<)))))
2600              (marked ;; More articles that are excluded from the
2601               ;; expiration process
2602               (cond (gnus-agent-expire-all
2603                      ;; All articles are unmarked by global decree
2604                      nil)
2605                     ((eq articles t)
2606                      ;; All articles are unmarked by function
2607                      ;; parameter
2608                      nil)
2609                     (articles
2610                      ;; All articles may as well be unmarked as the
2611                      ;; unreads list already names the articles we are
2612                      ;; going to keep
2613                      nil)
2614                     (t
2615                      ;; Ticked and/or dormant articles are excluded
2616                      ;; from expiration
2617                      (nconc
2618                       (gnus-uncompress-range
2619                        (cdr (assq 'tick (gnus-info-marks info))))
2620                       (gnus-uncompress-range
2621                        (cdr (assq 'dormant
2622                                   (gnus-info-marks info))))))))
2623              (nov-file (concat dir ".overview"))
2624              (cnt 0)
2625              (completed -1)
2626              dlist
2627              type)
2628
2629         ;; The normal article alist contains elements that look like
2630         ;; (article# .  fetch_date) I need to combine other
2631         ;; information with this list.  For example, a flag indicating
2632         ;; that a particular article MUST BE KEPT.  To do this, I'm
2633         ;; going to transform the elements to look like (article#
2634         ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2635         ;; the process to generate the expired article alist.
2636
2637         ;; Convert the alist elements to (article# fetch_date nil
2638         ;; nil).
2639         (setq dlist (mapcar (lambda (e)
2640                               (list (car e) (cdr e) nil nil)) alist))
2641
2642         ;; Convert the keep lists to elements that look like (article#
2643         ;; nil keep_flag nil) then append it to the expanded dlist
2644         ;; These statements are sorted by ascending precidence of the
2645         ;; keep_flag.
2646         (setq dlist (nconc dlist
2647                            (mapcar (lambda (e)
2648                                      (list e nil 'unread  nil))
2649                                    unreads)))
2650         (setq dlist (nconc dlist
2651                            (mapcar (lambda (e)
2652                                      (list e nil 'marked  nil))
2653                                    marked)))
2654         (setq dlist (nconc dlist
2655                            (mapcar (lambda (e)
2656                                      (list e nil 'special nil))
2657                                    specials)))
2658
2659         (set-buffer overview)
2660         (erase-buffer)
2661         (buffer-disable-undo)
2662         (when (file-exists-p nov-file)
2663           (gnus-message 7 "gnus-agent-expire: Loading overview...")
2664           (nnheader-insert-file-contents nov-file)
2665           (goto-char (point-min))
2666
2667           (let (p)
2668             (while (< (setq p (point)) (point-max))
2669               (condition-case nil
2670                   ;; If I successfully read an integer (the plus zero
2671                   ;; ensures a numeric type), prepend a marker entry
2672                   ;; to the list
2673                   (push (list (+ 0 (read (current-buffer))) nil nil
2674                               (set-marker (make-marker) p))
2675                         dlist)
2676                 (error
2677                  (gnus-message 1 "gnus-agent-expire: read error \
2678 occurred when reading expression at %s in %s.  Skipping to next \
2679 line." (point) nov-file)))
2680               ;; Whether I succeeded, or failed, it doesn't matter.
2681               ;; Move to the next line then try again.
2682               (forward-line 1)))
2683
2684           (gnus-message
2685            7 "gnus-agent-expire: Loading overview... Done"))
2686         (set-buffer-modified-p nil)
2687
2688         ;; At this point, all of the information is in dlist.  The
2689         ;; only problem is that much of it is spread across multiple
2690         ;; entries.  Sort then MERGE!!
2691         (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2692         ;; If two entries have the same article-number then sort by
2693         ;; ascending keep_flag.
2694         (let ((special 0)
2695               (marked 1)
2696               (unread 2))
2697           (setq dlist
2698                 (sort dlist
2699                       (lambda (a b)
2700                         (cond ((< (nth 0 a) (nth 0 b))
2701                                t)
2702                               ((> (nth 0 a) (nth 0 b))
2703                                nil)
2704                               (t
2705                                (let ((a (or (symbol-value (nth 2 a))
2706                                             3))
2707                                      (b (or (symbol-value (nth 2 b))
2708                                             3)))
2709                                  (<= a b))))))))
2710         (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2711         (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2712         (let ((dlist dlist))
2713           (while (cdr dlist)            ; I'm not at the end-of-list
2714             (if (eq (caar dlist) (caadr dlist))
2715                 (let ((first (cdr (car dlist)))
2716                       (secnd (cdr (cadr dlist))))
2717                   (setcar first (or (car first)
2718                                     (car secnd))) ; fetch_date
2719                   (setq first (cdr first)
2720                         secnd (cdr secnd))
2721                   (setcar first (or (car first)
2722                                     (car secnd))) ; Keep_flag
2723                   (setq first (cdr first)
2724                         secnd (cdr secnd))
2725                   (setcar first (or (car first)
2726                                     (car secnd))) ; NOV_entry_marker
2727
2728                   (setcdr dlist (cddr dlist)))
2729               (setq dlist (cdr dlist)))))
2730         (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2731
2732         (let* ((len (float (length dlist)))
2733                (alist (list nil))
2734                (tail-alist alist))
2735           (while dlist
2736             (let ((new-completed (truncate (* 100.0
2737                                               (/ (setq cnt (1+ cnt))
2738                                                  len)))))
2739               (when (> new-completed completed)
2740                 (setq completed new-completed)
2741                 (gnus-message 7 "%3d%% completed..."  completed)))
2742             (let* ((entry          (car dlist))
2743                    (article-number (nth 0 entry))
2744                    (fetch-date     (nth 1 entry))
2745                    (keep           (nth 2 entry))
2746                    (marker         (nth 3 entry)))
2747
2748               (cond
2749                ;; Kept articles are unread, marked, or special.
2750                (keep
2751                 (gnus-agent-message 10
2752                                     "gnus-agent-expire: Article %d: Kept %s article%s."
2753                                     article-number keep (if fetch-date " and file" ""))
2754                 (when fetch-date
2755                   (unless (file-exists-p
2756                            (concat dir (number-to-string
2757                                         article-number)))
2758                     (setf (nth 1 entry) nil)
2759                     (gnus-agent-message 3 "gnus-agent-expire cleared \
2760 download flag on article %d as the cached article file is missing."
2761                                         (caar dlist)))
2762                   (unless marker
2763                     (gnus-message 1 "gnus-agent-expire detected a \
2764 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2765                 (gnus-agent-append-to-list
2766                  tail-alist
2767                  (cons article-number fetch-date)))
2768
2769                ;; The following articles are READ, UNMARKED, and
2770                ;; ORDINARY.  See if they can be EXPIRED!!!
2771                ((setq type
2772                       (cond
2773                        ((not (integerp fetch-date))
2774                         'read) ;; never fetched article (may expire
2775                        ;; right now)
2776                        ((not (file-exists-p
2777                               (concat dir (number-to-string
2778                                            article-number))))
2779                         (setf (nth 1 entry) nil)
2780                         'externally-expired) ;; Can't find the cached
2781                        ;; article.  Handle case
2782                        ;; as though this article
2783                        ;; was never fetched.
2784
2785                        ;; We now have the arrival day, so we see
2786                        ;; whether it's old enough to be expired.
2787                        ((< fetch-date day)
2788                         'expired)
2789                        (force
2790                         'forced)))
2791
2792                 ;; I found some reason to expire this entry.
2793
2794                 (let ((actions nil))
2795                   (when (memq type '(forced expired))
2796                     (ignore-errors      ; Just being paranoid.
2797                       (let ((file-name (concat dir (number-to-string
2798                                                 article-number))))
2799                         (incf (nth 2 stats) (nth 7 (file-attributes file-name)))
2800                         (incf (nth 1 stats))
2801                         (delete-file file-name))
2802                       (push "expired cached article" actions))
2803                     (setf (nth 1 entry) nil)
2804                     )
2805
2806                   (when marker
2807                     (push "NOV entry removed" actions)
2808                     (goto-char marker)
2809
2810                     (incf (nth 0 stats))
2811
2812                     (let ((from (gnus-point-at-bol))
2813                           (to (progn (forward-line 1) (point))))
2814                       (incf (nth 2 stats) (- to from))
2815                       (delete-region from to)))
2816
2817                   ;; If considering all articles is set, I can only
2818                   ;; expire article IDs that are no longer in the
2819                   ;; active range (That is, articles that preceed the
2820                   ;; first article in the new alist).
2821                   (if (and gnus-agent-consider-all-articles
2822                            (>= article-number (car active)))
2823                       ;; I have to keep this ID in the alist
2824                       (gnus-agent-append-to-list
2825                        tail-alist (cons article-number fetch-date))
2826                     (push (format "Removed %s article number from \
2827 article alist" type) actions))
2828
2829                   (gnus-agent-message 8 "gnus-agent-expire: Article %d: %s"
2830                                       article-number
2831                                       (mapconcat 'identity actions ", "))))
2832                (t
2833                 (gnus-agent-message
2834                  10 "gnus-agent-expire: Article %d: Article kept as \
2835 expiration tests failed." article-number)
2836                 (gnus-agent-append-to-list
2837                  tail-alist (cons article-number fetch-date)))
2838                )
2839
2840               ;; Clean up markers as I want to recycle this buffer
2841               ;; over several groups.
2842               (when marker
2843                 (set-marker marker nil))
2844
2845               (setq dlist (cdr dlist))))
2846
2847           (setq alist (cdr alist))
2848
2849           (let ((inhibit-quit t))
2850             (unless (equal alist gnus-agent-article-alist)
2851               (setq gnus-agent-article-alist alist)
2852               (gnus-agent-save-alist group)
2853
2854               ;; The active list changed, set the agent's active range
2855               ;; to match the beginning of the list.
2856               (if alist
2857                   (setcar active (caar alist))))
2858
2859             (when (buffer-modified-p)
2860               (gnus-make-directory dir)
2861               (write-region-as-coding-system gnus-agent-file-coding-system
2862                                              (point-min) (point-max) nov-file
2863                                              nil 'silent)
2864               ;; clear the modified flag as that I'm not confused by
2865               ;; its status on the next pass through this routine.
2866               (set-buffer-modified-p nil))
2867
2868             (when (eq articles t)
2869               (gnus-summary-update-info))))))))
2870
2871 (defun gnus-agent-expire (&optional articles group force)
2872   "Expire all old articles.
2873 If you want to force expiring of certain articles, this function can
2874 take ARTICLES, GROUP and FORCE parameters as well.
2875
2876 The articles on which the expiration process runs are selected as follows:
2877   if ARTICLES is null, all read and unmarked articles.
2878   if ARTICLES is t, all articles.
2879   if ARTICLES is a list, just those articles.
2880 Setting GROUP will limit expiration to that group.
2881 FORCE is equivalent to setting the expiration predicates to true."
2882   (interactive)
2883   
2884   (if group
2885       (gnus-agent-expire-group group articles force)
2886     (if (or (not (eq articles t))
2887             (yes-or-no-p "Are you sure that you want to expire all \
2888 articles in every agentized group."))
2889         (let ((methods (gnus-agent-covered-methods))
2890               ;; Bind gnus-agent-expire-current-dirs to enable tracking
2891               ;; of agent directories.
2892               (gnus-agent-expire-current-dirs nil)
2893               ;; Bind gnus-agent-expire-stats to enable tracking of
2894               ;; expiration statistics across all groups
2895               (gnus-agent-expire-stats (list 0 0 0.0))
2896               gnus-command-method overview orig)
2897           (setq overview (gnus-get-buffer-create " *expire overview*"))
2898           (unwind-protect
2899               (while (setq gnus-command-method (pop methods))
2900                 (let ((active-file (gnus-agent-lib-file "active")))
2901                   (when (file-exists-p active-file)
2902                     (with-temp-buffer
2903                       (nnheader-insert-file-contents active-file)
2904                       (gnus-active-to-gnus-format
2905                        gnus-command-method
2906                        (setq orig (gnus-make-hashtable
2907                                    (count-lines (point-min) (point-max))))))
2908                     (dolist (expiring-group (gnus-groups-from-server
2909                                              gnus-command-method))
2910                       (let* ((active
2911                               (gnus-gethash-safe expiring-group orig)))
2912                                         
2913                         (when active
2914                           (save-excursion
2915                             (gnus-agent-expire-group-1
2916                              expiring-group overview active articles force)))))
2917                     (gnus-agent-write-active active-file orig t))))
2918             (kill-buffer overview))
2919           (gnus-agent-expire-unagentized-dirs)
2920           (gnus-message 4 (gnus-agent-expire-done-message))))))
2921
2922 (defun gnus-agent-expire-done-message ()
2923   (if (and (> gnus-verbose 4)
2924            (boundp 'gnus-agent-expire-stats))
2925       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
2926              (size (nth 2 stats))
2927             (units '(B KB MB GB)))
2928         (while (and (> size 1024.0)
2929                     (cdr units))
2930           (setq size (/ size 1024.0)
2931                 units (cdr units)))
2932
2933         (format "Expiry recovered %d NOV entries, deleted %d files,\
2934  and freed %f %s." 
2935                 (nth 0 stats) 
2936                 (nth 1 stats) 
2937                 size (car units)))
2938     "Expiry...done"))
2939
2940 (defun gnus-agent-expire-unagentized-dirs ()
2941   (when (and gnus-agent-expire-unagentized-dirs
2942              (boundp 'gnus-agent-expire-current-dirs))
2943     (let* ((keep (gnus-make-hashtable))
2944            ;; Formally bind gnus-agent-expire-current-dirs so that the
2945            ;; compiler will not complain about free references.
2946            (gnus-agent-expire-current-dirs
2947             (symbol-value 'gnus-agent-expire-current-dirs))
2948            dir)
2949
2950       (gnus-sethash gnus-agent-directory t keep)
2951       (while gnus-agent-expire-current-dirs
2952         (setq dir (pop gnus-agent-expire-current-dirs))
2953         (when (and (stringp dir)
2954                    (file-directory-p dir))
2955           (while (not (gnus-gethash dir keep))
2956             (gnus-sethash dir t keep)
2957             (setq dir (file-name-directory (directory-file-name dir))))))
2958
2959       (let* (to-remove
2960              checker
2961              (checker
2962               (function
2963                (lambda (d)
2964                  "Given a directory, check it and its subdirectories for 
2965               membership in the keep hash.  If it isn't found, add 
2966               it to to-remove." 
2967                  (let ((files (directory-files d))
2968                        file)
2969                    (while (setq file (pop files))
2970                      (cond ((equal file ".") ; Ignore self
2971                             nil)
2972                            ((equal file "..") ; Ignore parent
2973                             nil)
2974                            ((equal file ".overview") 
2975                             ;; Directory must contain .overview to be
2976                             ;; agent's cache of a group.
2977                             (let ((d (file-name-as-directory d))
2978                                   r)
2979                               ;; Search ancestor's for last directory NOT
2980                               ;; found in keep hash.
2981                               (while (not (gnus-gethash
2982                                            (setq d (file-name-directory d)) keep))
2983                                 (setq r d
2984                                       d (directory-file-name d)))
2985                               ;; if ANY ancestor was NOT in keep hash and
2986                               ;; it it's already in to-remove, add it to
2987                               ;; to-remove.                          
2988                               (if (and r
2989                                        (not (member r to-remove)))
2990                                   (push r to-remove))))
2991                            ((file-directory-p (setq file (nnheader-concat d file)))
2992                             (funcall checker file)))))))))
2993         (funcall checker (expand-file-name gnus-agent-directory))
2994
2995         (when (and to-remove
2996                    (or gnus-expert-user
2997                        (gnus-y-or-n-p
2998                         "gnus-agent-expire has identified local directories that are\
2999  not currently required by any agentized group.  Do you wish to consider\
3000  deleting them?")))
3001           (while to-remove
3002             (let ((dir (pop to-remove)))
3003               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3004                   (let* (delete-recursive
3005                          (delete-recursive
3006                           (function
3007                            (lambda (f-or-d)
3008                              (ignore-errors
3009                                (if (file-directory-p f-or-d)
3010                                    (condition-case nil
3011                                        (delete-directory f-or-d)
3012                                      (file-error
3013                                       (mapcar (lambda (f)
3014                                                 (or (member f '("." ".."))
3015                                                     (funcall delete-recursive
3016                                                              (nnheader-concat
3017                                                               f-or-d f))))
3018                                               (directory-files f-or-d))
3019                                       (delete-directory f-or-d)))
3020                                  (delete-file f-or-d)))))))
3021                     (funcall delete-recursive dir))))))))))
3022
3023 ;;;###autoload
3024 (defun gnus-agent-batch ()
3025   "Start Gnus, send queue and fetch session."
3026   (interactive)
3027   (let ((init-file-user "")
3028         (gnus-always-read-dribble-file t))
3029     (gnus))
3030   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3031     (gnus-group-send-queue)
3032     (gnus-agent-fetch-session)))
3033
3034 (defun gnus-agent-unread-articles (group)
3035   (let* ((read (gnus-info-read (gnus-get-info group)))
3036          (known (gnus-agent-load-alist group))
3037          (unread (list nil))
3038          (tail-unread unread))
3039     (while (and known read)
3040       (let ((candidate (car (pop known))))
3041         (while (let* ((range (car read))
3042                       (min   (if (numberp range) range (car range)))
3043                       (max   (if (numberp range) range (cdr range))))
3044                  (cond ((or (not min)
3045                             (< candidate min))
3046                         (gnus-agent-append-to-list tail-unread candidate)
3047                         nil)
3048                        ((> candidate max)
3049                         (setq read (cdr read))
3050                         ;; return t so that I always loop one more
3051                         ;; time.  If I just iterated off the end of
3052                         ;; read, min will become nil and the current
3053                         ;; candidate will be added to the unread list.
3054                         t))))))
3055     (while known
3056       (gnus-agent-append-to-list tail-unread (car (pop known))))
3057     (cdr unread)))
3058
3059 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3060   "Restrict ARTICLES to numbers already fetched.
3061 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3062 that have already been fetched.
3063 If CACHED-HEADER is nil, articles are only excluded if the article itself
3064 has been fetched."
3065
3066   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3067   ;; 'car gnus-agent-article-alist))
3068
3069   ;; Functionally, I don't need to construct a temp list using mapcar.
3070
3071   (if (and (or gnus-agent-cache (not gnus-plugged))
3072            (gnus-agent-load-alist group))
3073     (let* ((ref gnus-agent-article-alist)
3074            (arts articles)
3075            (uncached (list nil))
3076            (tail-uncached uncached))
3077       (while (and ref arts)
3078         (let ((v1 (car arts))
3079               (v2 (caar ref)))
3080           (cond ((< v1 v2) ; v1 does not appear in the reference list
3081                  (gnus-agent-append-to-list tail-uncached v1)
3082                  (setq arts (cdr arts)))
3083                 ((= v1 v2)
3084                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3085                    (gnus-agent-append-to-list tail-uncached v1))
3086                  (setq arts (cdr arts))
3087                  (setq ref (cdr ref)))
3088                 (t ; reference article (v2) preceeds the list being filtered
3089                  (setq ref (cdr ref))))))
3090       (while arts
3091         (gnus-agent-append-to-list tail-uncached (pop arts)))
3092       (cdr uncached))
3093     ;; if gnus-agent-load-alist fails, no articles are cached.
3094     articles))
3095
3096 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3097   (save-excursion
3098     (gnus-agent-create-buffer)
3099     (let ((gnus-decode-encoded-word-function 'identity)
3100           (file (gnus-agent-article-name ".overview" group))
3101           cached-articles uncached-articles)
3102       (gnus-make-directory (nnheader-translate-file-chars
3103                             (file-name-directory file) t))
3104
3105       ;; Populate temp buffer with known headers
3106       (when (file-exists-p file)
3107         (with-current-buffer gnus-agent-overview-buffer
3108           (erase-buffer)
3109           (let ((nnheader-file-coding-system
3110                  gnus-agent-file-coding-system))
3111             (nnheader-insert-nov-file file (car articles)))))
3112
3113       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3114                                                                 t))
3115           (progn
3116             ;; Populate nntp-server-buffer with uncached headers
3117             (set-buffer nntp-server-buffer)
3118             (erase-buffer)
3119             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3120                                    (gnus-retrieve-headers
3121                                     uncached-articles group fetch-old))))
3122                    (nnvirtual-convert-headers))
3123                   ((eq 'nntp (car gnus-current-select-method))
3124                    ;; The author of gnus-get-newsgroup-headers-xover
3125                    ;; reports that the XOVER command is commonly
3126                    ;; unreliable. The problem is that recently
3127                    ;; posted articles may not be entered into the
3128                    ;; NOV database in time to respond to my XOVER
3129                    ;; query.
3130                    ;;
3131                    ;; I'm going to use his assumption that the NOV
3132                    ;; database is updated in order of ascending
3133                    ;; article ID.  Therefore, a response containing
3134                    ;; article ID N implies that all articles from 1
3135                    ;; to N-1 are up-to-date.  Therefore, missing
3136                    ;; articles in that range have expired.
3137
3138                    (set-buffer nntp-server-buffer)
3139                    (let* ((fetched-articles (list nil))
3140                           (tail-fetched-articles fetched-articles)
3141                           (min (cond ((numberp fetch-old)
3142                                       (max 1 (- (car articles) fetch-old)))
3143                                      (fetch-old
3144                                       1)
3145                                      (t
3146                                       (car articles))))
3147                           (max (car (last articles))))
3148
3149                      ;; Get the list of articles that were fetched
3150                      (goto-char (point-min))
3151                      (let ((pm (point-max)))
3152                        (while (< (point) pm)
3153                          (when (looking-at "[0-9]+\t")
3154                            (gnus-agent-append-to-list
3155                             tail-fetched-articles
3156                             (read (current-buffer))))
3157                          (forward-line 1)))
3158
3159                      ;; Clip this list to the headers that will
3160                      ;; actually be returned
3161                      (setq fetched-articles (gnus-list-range-intersection
3162                                              (cdr fetched-articles)
3163                                              (cons min max)))
3164
3165                      ;; Clip the uncached articles list to exclude
3166                      ;; IDs after the last FETCHED header.  The
3167                      ;; excluded IDs may be fetchable using HEAD.
3168                      (if (car tail-fetched-articles)
3169                          (setq uncached-articles
3170                                (gnus-list-range-intersection
3171                                 uncached-articles
3172                                 (cons (car uncached-articles)
3173                                       (car tail-fetched-articles)))))
3174
3175                      ;; Create the list of articles that were
3176                      ;; "successfully" fetched.  Success, in this
3177                      ;; case, means that the ID should not be
3178                      ;; fetched again.  In the case of an expired
3179                      ;; article, the header will not be fetched.
3180                      (setq uncached-articles
3181                            (gnus-sorted-nunion fetched-articles
3182                                                uncached-articles))
3183                      )))
3184
3185             ;; Erase the temp buffer
3186             (set-buffer gnus-agent-overview-buffer)
3187             (erase-buffer)
3188
3189             ;; Copy the nntp-server-buffer to the temp buffer
3190             (set-buffer nntp-server-buffer)
3191             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3192
3193             ;; Merge the temp buffer with the known headers (found on
3194             ;; disk in FILE) into the nntp-server-buffer
3195             (when (and uncached-articles (file-exists-p file))
3196               (gnus-agent-braid-nov group uncached-articles file))
3197
3198             ;; Save the new set of known headers to FILE
3199             (set-buffer nntp-server-buffer)
3200             (gnus-agent-check-overview-buffer)
3201             (write-region-as-coding-system
3202              gnus-agent-file-coding-system
3203              (point-min) (point-max) file nil 'silent)
3204
3205             ;; Update the group's article alist to include the newly
3206             ;; fetched articles.
3207             (gnus-agent-load-alist group)
3208             (gnus-agent-save-alist group uncached-articles nil)
3209             )
3210
3211         ;; Copy the temp buffer to the nntp-server-buffer
3212         (set-buffer nntp-server-buffer)
3213         (erase-buffer)
3214         (insert-buffer-substring gnus-agent-overview-buffer)))
3215
3216     (if (and fetch-old
3217              (not (numberp fetch-old)))
3218         t                               ; Don't remove anything.
3219       (nnheader-nov-delete-outside-range
3220        (if fetch-old (max 1 (- (car articles) fetch-old))
3221          (car articles))
3222        (car (last articles)))
3223       t)
3224
3225     'nov))
3226
3227 (defun gnus-agent-request-article (article group)
3228   "Retrieve ARTICLE in GROUP from the agent cache."
3229   (when (and gnus-agent
3230              (or gnus-agent-cache
3231                  (not gnus-plugged))
3232              (numberp article))
3233     (let* ((gnus-command-method (gnus-find-method-for-group group))
3234            (file (gnus-agent-article-name (number-to-string article) group))
3235            (buffer-read-only nil))
3236       (when (and (file-exists-p file)
3237                  (> (nth 7 (file-attributes file)) 0))
3238         (erase-buffer)
3239         (gnus-kill-all-overlays)
3240         (insert-file-contents-as-coding-system gnus-cache-coding-system file)
3241         t))))
3242
3243 (defun gnus-agent-regenerate-group (group &optional reread)
3244   "Regenerate GROUP.
3245 If REREAD is t, all articles in the .overview are marked as unread.
3246 If REREAD is not nil, downloaded articles are marked as unread."
3247   (interactive
3248    (list (let ((def (or (gnus-group-group-name)
3249                         gnus-newsgroup-name)))
3250            (let ((select (read-string (if def
3251                                           (concat "Group Name ("
3252                                                   def "): ")
3253                                         "Group Name: "))))
3254              (if (and (equal "" select)
3255                       def)
3256                  def
3257                select)))
3258          (catch 'mark
3259            (while (let ((c (read-char-exclusive 
3260                             "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n)"
3261                             )))
3262                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3263                            (throw 'mark nil))
3264                           ((or (eq c ?a) (eq c ?A))
3265                            (throw 'mark t))
3266                           ((or (eq c ?d) (eq c ?D))
3267                            (throw 'mark 'some)))
3268                     (message "Ignoring unexpected input")
3269                     (sit-for 1)
3270                     t)))))
3271   (gnus-message 5 "Regenerating in %s" group)
3272   (let* ((gnus-command-method (or gnus-command-method
3273                                   (gnus-find-method-for-group group)))
3274          (file (gnus-agent-article-name ".overview" group))
3275          (dir (file-name-directory file))
3276          point
3277          (downloaded (if (file-exists-p dir)
3278                          (sort (mapcar (lambda (name) (string-to-int name))
3279                                        (directory-files dir nil "^[0-9]+$" t))
3280                                '>)
3281                        (progn (gnus-make-directory dir) nil)))
3282          dl nov-arts
3283          alist header
3284          regenerated)
3285
3286     (mm-with-unibyte-buffer
3287      (if (file-exists-p file)
3288          (let ((nnheader-file-coding-system
3289                 gnus-agent-file-coding-system))
3290            (nnheader-insert-file-contents file)))
3291      (set-buffer-modified-p nil)
3292
3293      ;; Load the article IDs found in the overview file.  As a
3294      ;; side-effect, validate the file contents.
3295      (let ((load t))
3296        (while load
3297          (setq load nil)
3298          (goto-char (point-min))
3299          (while (< (point) (point-max))
3300            (cond ((and (looking-at "[0-9]+\t")
3301                        (<= (- (match-end 0) (match-beginning 0)) 9))
3302                   (push (read (current-buffer)) nov-arts)
3303                   (forward-line 1)
3304                   (let ((l1 (car nov-arts))
3305                         (l2 (cadr nov-arts)))
3306                     (cond ((not l2)
3307                            nil)
3308                           ((< l1 l2)
3309                            (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3310  entries are NOT in ascending order.")
3311                            ;; Don't sort now as I haven't verified
3312                            ;; that every line begins with a number
3313                            (setq load t))
3314                           ((= l1 l2)
3315                            (forward-line -1)
3316                            (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3317  entries contained duplicate of article %s.      Duplicate deleted." l1)
3318                            (gnus-delete-line)
3319                            (setq nov-arts (cdr nov-arts))))))
3320                  (t
3321                   (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3322  entries contained line that did not begin with an article number.  Deleted\
3323  line.")
3324                   (gnus-delete-line))))
3325          (if load
3326              (progn
3327                (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3328  entries into ascending order.")
3329                (sort-numeric-fields 1 (point-min) (point-max))
3330                     (setq nov-arts nil)))))
3331      (gnus-agent-check-overview-buffer)
3332
3333      ;; Construct a new article alist whose nodes match every header
3334      ;; in the .overview file.  As a side-effect, missing headers are
3335      ;; reconstructed from the downloaded article file.
3336      (while (or downloaded nov-arts)
3337        (cond ((and downloaded
3338                    (or (not nov-arts)
3339                        (> (car downloaded) (car nov-arts))))
3340               ;; This entry is missing from the overview file
3341               (gnus-message 3 "Regenerating NOV %s %d..." group
3342                             (car downloaded))
3343               (let ((file (concat dir (number-to-string (car downloaded)))))
3344                 (mm-with-unibyte-buffer
3345                  (nnheader-insert-file-contents file)
3346                  (nnheader-remove-body)
3347                  (setq header (nnheader-parse-naked-head)))
3348                 (mail-header-set-number header (car downloaded))
3349                 (if nov-arts
3350                     (let ((key (concat "^" (int-to-string (car nov-arts))
3351                                        "\t")))
3352                       (or (re-search-backward key nil t)
3353                           (re-search-forward key))
3354                       (forward-line 1))
3355                   (goto-char (point-min)))
3356                 (nnheader-insert-nov header))
3357               (setq nov-arts (cons (car downloaded) nov-arts)))
3358              ((eq (car downloaded) (car nov-arts))
3359               ;; This entry in the overview has been downloaded
3360               (push (cons (car downloaded)
3361                           (time-to-days
3362                            (nth 5 (file-attributes
3363                                    (concat dir (number-to-string
3364                                                 (car downloaded))))))) alist)
3365               (setq downloaded (cdr downloaded))
3366               (setq nov-arts (cdr nov-arts)))
3367              (t
3368               ;; This entry in the overview has not been downloaded
3369               (push (cons (car nov-arts) nil) alist)
3370               (setq nov-arts (cdr nov-arts)))))
3371
3372      ;; When gnus-agent-consider-all-articles is set,
3373      ;; gnus-agent-regenerate-group should NOT remove article IDs from
3374      ;; the alist.  Those IDs serve as markers to indicate that an
3375      ;; attempt has been made to fetch that article's header.
3376
3377      ;; When gnus-agent-consider-all-articles is NOT set,
3378      ;; gnus-agent-regenerate-group can remove the article ID of every
3379      ;; article (with the exception of the last ID in the list - it's
3380      ;; special) that no longer appears in the overview.  In this
3381      ;; situtation, the last article ID in the list implies that it,
3382      ;; and every article ID preceeding it, have been fetched from the
3383      ;; server.
3384      (if gnus-agent-consider-all-articles
3385          ;; Restore all article IDs that were not found in the overview file.
3386          (let* ((n (cons nil alist))
3387                 (merged n)
3388                 (o (gnus-agent-load-alist group)))
3389            (while o
3390              (let ((nID (caadr n))
3391                    (oID (caar o)))
3392                (cond ((not nID)
3393                       (setq n (setcdr n (list (list oID))))
3394                       (setq o (cdr o)))
3395                      ((< oID nID)
3396                       (setcdr n (cons (list oID) (cdr n)))
3397                       (setq o (cdr o)))
3398                      ((= oID nID)
3399                       (setq o (cdr o))
3400                       (setq n (cdr n)))
3401                      (t
3402                       (setq n (cdr n))))))
3403            (setq alist (cdr merged)))
3404        ;; Restore the last article ID if it is not already in the new alist
3405        (let ((n (last alist))
3406              (o (last (gnus-agent-load-alist group))))
3407          (cond ((not o)
3408                 nil)
3409                ((not n)
3410                 (push (cons (caar o) nil) alist))
3411                ((< (caar n) (caar o))
3412                 (setcdr n (list (car o)))))))
3413
3414      (let ((inhibit-quit t))
3415      (if (setq regenerated (buffer-modified-p))
3416          (write-region-as-coding-system
3417           gnus-agent-file-coding-system
3418           (point-min) (point-max) file nil 'silent))
3419
3420     (setq regenerated (or regenerated
3421                           (and reread gnus-agent-article-alist)
3422                           (not (equal alist gnus-agent-article-alist)))
3423           )
3424
3425     (setq gnus-agent-article-alist alist)
3426
3427     (when regenerated
3428          (gnus-agent-save-alist group)))
3429      )
3430
3431     (when (and reread gnus-agent-article-alist)
3432       (gnus-make-ascending-articles-unread
3433        group
3434        (delq nil (mapcar (function (lambda (c)
3435                                      (cond ((eq reread t)
3436                                             (car c))
3437                                            ((cdr c)
3438                                             (car c)))))
3439                          gnus-agent-article-alist)))
3440
3441       (when (gnus-buffer-live-p gnus-group-buffer)
3442         (gnus-group-update-group group t)
3443         (sit-for 0))
3444       )
3445
3446     (gnus-message 5 nil)
3447     regenerated))
3448
3449 ;;;###autoload
3450 (defun gnus-agent-regenerate (&optional clean reread)
3451   "Regenerate all agent covered files.
3452 If CLEAN, don't read existing active files."
3453   (interactive "P")
3454   (let (regenerated)
3455     (gnus-message 4 "Regenerating Gnus agent files...")
3456     (dolist (gnus-command-method (gnus-agent-covered-methods))
3457       (let ((active-file (gnus-agent-lib-file "active"))
3458             active-hashtb active-changed
3459             point)
3460         (gnus-make-directory (file-name-directory active-file))
3461         (if clean
3462             (setq active-hashtb (gnus-make-hashtable 1000))
3463           (mm-with-unibyte-buffer
3464            (if (file-exists-p active-file)
3465                (let ((nnheader-file-coding-system
3466                       gnus-agent-file-coding-system))
3467                  (nnheader-insert-file-contents active-file))
3468              (setq active-changed t))
3469            (gnus-active-to-gnus-format
3470             nil (setq active-hashtb
3471                       (gnus-make-hashtable
3472                        (count-lines (point-min) (point-max)))))))
3473         (dolist (group (gnus-groups-from-server gnus-command-method))
3474           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3475                                 regenerated))
3476           (let ((min (or (caar gnus-agent-article-alist) 1))
3477                 (max (or (caar (last gnus-agent-article-alist)) 0))
3478                 (active (gnus-gethash-safe (gnus-group-real-name group)
3479                                            active-hashtb))
3480                 (read (gnus-info-read (gnus-get-info group))))
3481             (if (not active)
3482                 (progn
3483                   (setq active (cons min max)
3484                         active-changed t)
3485                   (gnus-sethash group active active-hashtb))
3486               (when (> (car active) min)
3487                 (setcar active min)
3488                 (setq active-changed t))
3489               (when (< (cdr active) max)
3490                 (setcdr active max)
3491                 (setq active-changed t)))))
3492         (when active-changed
3493           (setq regenerated t)
3494           (gnus-message 4 "Regenerate %s" active-file)
3495           (let ((nnmail-active-file-coding-system
3496                  gnus-agent-file-coding-system))
3497             (gnus-write-active-file active-file active-hashtb)))))
3498     (gnus-message 4 "Regenerating Gnus agent files...done")
3499     regenerated))
3500
3501 (defun gnus-agent-go-online (&optional force)
3502   "Switch servers into online status."
3503   (interactive (list t))
3504   (dolist (server gnus-opened-servers)
3505     (when (eq (nth 1 server) 'offline)
3506       (if (if (eq force 'ask)
3507               (gnus-y-or-n-p
3508                (format "Switch %s:%s into online status? "
3509                        (caar server) (cadar server)))
3510             force)
3511           (setcar (nthcdr 1 server) 'close)))))
3512
3513 (defun gnus-agent-toggle-group-plugged (group)
3514   "Toggle the status of the server of the current group."
3515   (interactive (list (gnus-group-group-name)))
3516   (let* ((method (gnus-find-method-for-group group))
3517          (status (cadr (assoc method gnus-opened-servers))))
3518     (if (eq status 'offline)
3519         (gnus-server-set-status method 'closed)
3520       (gnus-close-server method)
3521       (gnus-server-set-status method 'offline))
3522     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3523              (if (eq status 'offline) 'offline 'online)
3524              (if (eq status 'offline) 'online 'offline))))
3525
3526 (defun gnus-agent-group-covered-p (group)
3527   (gnus-agent-method-p (gnus-group-method group)))
3528
3529 (add-hook 'gnus-group-prepare-hook
3530           (lambda ()
3531             'gnus-agent-do-once
3532
3533             (when (listp gnus-agent-expire-days)
3534               (beep)
3535               (beep)
3536               (gnus-message 1 "WARNING: gnus-agent-expire-days no longer\
3537  supports being set to a list.")(sleep-for 3)
3538               (gnus-message 1 "Change your configuration to set it to an\
3539  integer.")(sleep-for 3)
3540               (gnus-message 1 "I am now setting group parameters on each\
3541  group to match the configuration that the list offered.")
3542
3543               (save-excursion
3544                 (let ((groups (gnus-group-listed-groups)))
3545                   (while groups
3546                     (let* ((group (pop groups))
3547                            (days gnus-agent-expire-days)
3548                            (day (catch 'found
3549                                   (while days
3550                                     (when (eq 0 (string-match
3551                                                  (caar days)
3552                                                  group))
3553                                       (throw 'found (cadar days)))
3554                                     (setq days (cdr days)))
3555                                   nil)))
3556                       (when day
3557                         (gnus-group-set-parameter group 'agent-days-until-old
3558                                                   day))))))
3559
3560               (let ((h gnus-group-prepare-hook))
3561                 (while h
3562                   (let ((func (pop h)))
3563                     (when (and (listp func)
3564                                (eq (cadr (caddr func)) 'gnus-agent-do-once))
3565                       (remove-hook 'gnus-group-prepare-hook func)
3566                       (setq h nil)))))
3567
3568               (gnus-message 1 "I have finished setting group parameters on\
3569  each group. You may now customize your groups and/or topics to control the\
3570  agent."))))
3571
3572 (provide 'gnus-agent)
3573
3574 ;;; gnus-agent.el ends here