Synch to Gnus 200311250226.
[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 ()
805   "Enroll SERVER in the agent program."
806   (interactive)
807   (let* ((server       (gnus-server-server-name))
808          (named-server (gnus-server-named-server))
809          (method       (and server
810                             (gnus-server-get-method nil server))))
811     (unless server
812       (error "No server on the current line"))
813
814     (when (gnus-agent-method-p method)
815       (error "Server already in the agent program"))
816
817     (push named-server gnus-agent-covered-methods)
818
819     (setq gnus-agent-method-p-cache nil)
820     (gnus-server-update-server server)
821     (gnus-agent-write-servers)
822     (gnus-message 1 "Entered %s into the Agent" server)))
823
824 (defun gnus-agent-remove-server ()
825   "Remove SERVER from the agent program."
826   (interactive)
827   (let* ((server       (gnus-server-server-name))
828          (named-server (gnus-server-named-server)))
829     (unless server
830       (error "No server on the current line"))
831
832     (unless (member named-server gnus-agent-covered-methods)
833       (error "Server not in the agent program"))
834
835     (setq gnus-agent-covered-methods 
836           (delete named-server gnus-agent-covered-methods)
837           gnus-agent-method-p-cache nil)
838
839     (gnus-server-update-server server)
840     (gnus-agent-write-servers)
841     (gnus-message 1 "Removed %s from the agent" server)))
842
843 (defun gnus-agent-read-servers ()
844   "Read the alist of covered servers."
845   (setq gnus-agent-covered-methods 
846         (gnus-agent-read-file
847          (nnheader-concat gnus-agent-directory "lib/servers"))
848         gnus-agent-method-p-cache nil)
849
850   ;; I am called so early in start-up that I can not validate server
851   ;; names.  When that is the case, I skip the validation.  That is
852   ;; alright as the gnus startup code calls the validate methods
853   ;; directly.
854   (if gnus-server-alist
855       (gnus-agent-read-servers-validate)))
856
857 (defun gnus-agent-read-servers-validate ()
858   (mapcar (lambda (server-or-method)
859             (let* ((server (if (stringp server-or-method)
860                                server-or-method
861                              (gnus-method-to-server server-or-method)))
862                    (method (gnus-server-to-method server)))
863               (if method
864                   (unless (member server gnus-agent-covered-methods)
865                     (push server gnus-agent-covered-methods)
866                     (setq gnus-agent-method-p-cache nil))
867                 (gnus-message 1 "Ignoring disappeared server `%s'" server))))
868           (prog1 gnus-agent-covered-methods
869             (setq gnus-agent-covered-methods nil))))
870
871 (defun gnus-agent-read-servers-validate-native (native-method)
872   (setq gnus-agent-covered-methods
873         (mapcar (lambda (method)
874                   (if (or (not method)
875                           (equal method native-method))
876                       "native"
877                     method)) gnus-agent-covered-methods)))
878
879 (defun gnus-agent-write-servers ()
880   "Write the alist of covered servers."
881   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
882   (let ((coding-system-for-write nnheader-file-coding-system)
883         (output-coding-system nnheader-file-coding-system)
884         (file-name-coding-system nnmail-pathname-coding-system)
885         (pathname-coding-system nnmail-pathname-coding-system))
886     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
887       (prin1 gnus-agent-covered-methods
888              (current-buffer)))))
889
890 ;;;
891 ;;; Summary commands
892 ;;;
893
894 (defun gnus-agent-mark-article (n &optional unmark)
895   "Mark the next N articles as downloadable.
896 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
897 the mark instead.  The difference between N and the actual number of
898 articles marked is returned."
899   (interactive "p")
900   (let ((backward (< n 0))
901         (n (abs n)))
902     (while (and
903             (> n 0)
904             (progn
905               (gnus-summary-set-agent-mark
906                (gnus-summary-article-number) unmark)
907               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
908       (setq n (1- n)))
909     (when (/= 0 n)
910       (gnus-message 7 "No more articles"))
911     (gnus-summary-recenter)
912     (gnus-summary-position-point)
913     n))
914
915 (defun gnus-agent-unmark-article (n)
916   "Remove the downloadable mark from the next N articles.
917 If N is negative, unmark backward instead.  The difference between N and
918 the actual number of articles unmarked is returned."
919   (interactive "p")
920   (gnus-agent-mark-article n t))
921
922 (defun gnus-agent-toggle-mark (n)
923   "Toggle the downloadable mark from the next N articles.
924 If N is negative, toggle backward instead.  The difference between N and
925 the actual number of articles toggled is returned."
926   (interactive "p")
927   (gnus-agent-mark-article n 'toggle))
928
929 (defun gnus-summary-set-agent-mark (article &optional unmark)
930   "Mark ARTICLE as downloadable.  If UNMARK is nil, article is marked.
931 When UNMARK is t, the article is unmarked.  For any other value, the
932 article's mark is toggled."
933   (let ((unmark (cond ((eq nil unmark)
934                        nil)
935                       ((eq t unmark)
936                        t)
937                       (t
938                        (memq article gnus-newsgroup-downloadable)))))
939     (when (gnus-summary-goto-subject article nil t)
940       (gnus-summary-update-mark
941        (if unmark
942            (progn
943              (setq gnus-newsgroup-downloadable
944                    (delq article gnus-newsgroup-downloadable))
945              (gnus-article-mark article))
946          (progn
947            (setq gnus-newsgroup-downloadable
948                  (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
949            gnus-downloadable-mark)
950          )
951        'unread))))
952
953 (defun gnus-agent-get-undownloaded-list ()
954   "Construct list of articles that have not been downloaded."
955   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
956     (when (set (make-local-variable 'gnus-newsgroup-agentized)
957                (gnus-agent-method-p gnus-command-method))
958       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
959              (headers (sort (mapcar (lambda (h)
960                                       (mail-header-number h))
961                                     gnus-newsgroup-headers) '<))
962              (cached (and gnus-use-cache gnus-newsgroup-cached))
963              (undownloaded (list nil))
964              (tail-undownloaded undownloaded)
965              (unfetched (list nil))
966              (tail-unfetched unfetched))
967         (while (and alist headers)
968           (let ((a (caar alist))
969                 (h (car headers)))
970             (cond ((< a h)
971                    ;; Ignore IDs in the alist that are not being
972                    ;; displayed in the summary.
973                    (setq alist (cdr alist)))
974                   ((> a h)
975                    ;; Headers that are not in the alist should be
976                    ;; fictious (see nnagent-retrieve-headers); they
977                    ;; imply that this article isn't in the agent.
978                    (gnus-agent-append-to-list tail-undownloaded h)
979                    (gnus-agent-append-to-list tail-unfetched    h)
980                    (setq headers (cdr headers))) 
981                   ((cdar alist)
982                    (setq alist (cdr alist))
983                    (setq headers (cdr headers))
984                    nil                  ; ignore already downloaded
985                    )
986                   (t
987                    (setq alist (cdr alist))
988                    (setq headers (cdr headers))
989                    
990                    ;; This article isn't in the agent.  Check to see
991                    ;; if it is in the cache.  If it is, it's been
992                    ;; downloaded.
993                    (while (and cached (< (car cached) a))
994                      (setq cached (cdr cached)))
995                    (unless (equal a (car cached))
996                      (gnus-agent-append-to-list tail-undownloaded a))))))
997
998         (while headers
999           (let ((num (pop headers)))
1000             (gnus-agent-append-to-list tail-undownloaded num)
1001             (gnus-agent-append-to-list tail-unfetched    num)))
1002
1003         (setq gnus-newsgroup-undownloaded (cdr undownloaded)
1004               gnus-newsgroup-unfetched    (cdr unfetched))))))
1005
1006 (defun gnus-agent-catchup ()
1007   "Mark as read all unhandled articles.
1008 An article is unhandled if it is neither cached, nor downloaded, nor
1009 downloadable."
1010   (interactive)
1011   (save-excursion
1012     (let ((articles gnus-newsgroup-undownloaded))
1013       (when (or gnus-newsgroup-downloadable
1014                 gnus-newsgroup-cached)
1015         (setq articles (gnus-sorted-ndifference
1016                         (gnus-sorted-ndifference
1017                          (gnus-copy-sequence articles)
1018                          gnus-newsgroup-downloadable)
1019                         gnus-newsgroup-cached)))
1020
1021       (while articles
1022         (gnus-summary-mark-article
1023          (pop articles) gnus-catchup-mark)))
1024     (gnus-summary-position-point)))
1025
1026 (defun gnus-agent-summary-fetch-series ()
1027   (interactive)
1028   (when gnus-newsgroup-processable
1029     (setq gnus-newsgroup-downloadable
1030           (let* ((dl gnus-newsgroup-downloadable)
1031                  (gnus-newsgroup-downloadable
1032                   (sort (gnus-copy-sequence gnus-newsgroup-processable) '<))
1033                  (fetched-articles (gnus-agent-summary-fetch-group)))
1034             ;; The preceeding call to (gnus-agent-summary-fetch-group)
1035             ;; updated gnus-newsgroup-downloadable to remove each
1036             ;; article successfully fetched.
1037
1038             ;; For each article that I processed, remove its
1039             ;; processable mark IF the article is no longer
1040             ;; downloadable (i.e. it's already downloaded)
1041             (dolist (article gnus-newsgroup-processable)
1042               (unless (memq article gnus-newsgroup-downloadable)
1043                 (gnus-summary-remove-process-mark article)))
1044             (gnus-sorted-ndifference dl fetched-articles)))))
1045
1046 (defun gnus-agent-summary-fetch-group (&optional all)
1047   "Fetch the downloadable articles in the group.
1048 Optional arg ALL, if non-nil, means to fetch all articles."
1049   (interactive "P")
1050   (let ((articles
1051          (if all gnus-newsgroup-articles
1052            gnus-newsgroup-downloadable))
1053         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
1054         fetched-articles)
1055     (gnus-agent-while-plugged
1056       (unless articles
1057         (error "No articles to download"))
1058       (gnus-agent-with-fetch
1059         (setq gnus-newsgroup-undownloaded
1060               (gnus-sorted-ndifference
1061                gnus-newsgroup-undownloaded
1062                (setq fetched-articles
1063                      (gnus-agent-fetch-articles
1064                       gnus-newsgroup-name articles)))))
1065       (save-excursion
1066         (dolist (article articles)
1067           (let ((was-marked-downloadable 
1068                  (memq article gnus-newsgroup-downloadable)))
1069             (cond (gnus-agent-mark-unread-after-downloaded
1070                    (setq gnus-newsgroup-downloadable
1071                          (delq article gnus-newsgroup-downloadable))
1072
1073                    ;; The downloadable mark is implemented as a
1074                    ;; type of read mark.  Therefore, marking the
1075                    ;; article as unread is sufficient to clear
1076                    ;; its downloadable flag.  
1077                    (gnus-summary-mark-article article gnus-unread-mark))
1078                   (was-marked-downloadable
1079                    (gnus-summary-set-agent-mark article t)))
1080             (when (gnus-summary-goto-subject article nil t)
1081               (gnus-summary-update-download-mark article))))))
1082     fetched-articles))
1083
1084 (defun gnus-agent-fetch-selected-article ()
1085   "Fetch the current article as it is selected.
1086 This can be added to `gnus-select-article-hook' or
1087 `gnus-mark-article-hook'."
1088   (let ((gnus-command-method gnus-current-select-method))
1089     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
1090       (when (gnus-agent-fetch-articles
1091              gnus-newsgroup-name
1092              (list gnus-current-article))
1093         (setq gnus-newsgroup-undownloaded
1094               (delq gnus-current-article gnus-newsgroup-undownloaded))
1095         (gnus-summary-update-download-mark gnus-current-article)))))
1096
1097 ;;;
1098 ;;; Internal functions
1099 ;;;
1100
1101 ;;; NOTES:
1102 ;;; The agent's active range is defined as follows:
1103 ;;;  If the agent has no record of the group, use the actual active
1104 ;;;    range.
1105 ;;;  If the agent has a record, set the agent's active range to
1106 ;;;    include the max limit of the actual active range.
1107 ;;;  When expiring, update the min limit to match the smallest of the
1108 ;;;    min article not expired or the min actual active range.
1109
1110 (defun gnus-agent-save-active (method)
1111   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
1112
1113 (defun gnus-agent-save-active-1 (method function)
1114   (when (gnus-agent-method-p method)
1115     (let* ((gnus-command-method method)
1116            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
1117            (file (gnus-agent-lib-file "active")))
1118       (funcall function nil new)
1119       (gnus-agent-write-active file new)
1120       (erase-buffer)
1121       (nnheader-insert-file-contents file))))
1122
1123 (defun gnus-agent-write-active (file new &optional literal-replacement)
1124   (let ((old new))
1125     (when (and (not literal-replacement)
1126                (file-exists-p file))
1127       (setq old (gnus-make-hashtable (count-lines (point-min) (point-max))))
1128       (with-temp-buffer
1129         (nnheader-insert-file-contents file)
1130         (gnus-active-to-gnus-format nil old))
1131       ;; Iterate over the current active groups, the current active
1132       ;; range may expand, but NOT CONTRACT, the agent's active range.
1133       (mapatoms
1134        (lambda (nsym)
1135          (let ((new-active (and nsym (boundp nsym) (symbol-value nsym))))
1136            (when new-active
1137              (let* ((osym       (intern (symbol-name nsym) old))
1138                     (old-active (and (boundp osym) (symbol-value osym))))
1139                (if old-active
1140                    (let ((new-min (car new-active))
1141                          (old-min (car old-active))
1142                          (new-max (cdr new-active))
1143                          (old-max (cdr old-active)))
1144                      (if (and (integerp new-min)
1145                               (< new-min old-min))
1146                          (setcar old-active new-min))
1147                      (if (and (integerp new-max)
1148                               (> new-max old-max))
1149                          (setcdr old-active new-max)))
1150                  (set osym new-active))))))
1151        new))
1152     (gnus-make-directory (file-name-directory file))
1153     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
1154       ;; The hashtable contains real names of groups.  However, do NOT
1155       ;; add the foreign server prefix as gnus-active-to-gnus-format
1156       ;; will add it while reading the file.
1157       (gnus-write-active-file file old nil))))
1158
1159 (defun gnus-agent-save-groups (method)
1160   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
1161
1162 (defun gnus-agent-save-group-info (method group active)
1163   (when (gnus-agent-method-p method)
1164     (let* ((gnus-command-method method)
1165            (coding-system-for-write nnheader-file-coding-system)
1166            (output-coding-system nnheader-file-coding-system)
1167            (file-name-coding-system nnmail-pathname-coding-system)
1168            (pathname-coding-system nnmail-pathname-coding-system)
1169            (file (gnus-agent-lib-file "active"))
1170            oactive-min oactive-max)
1171       (gnus-make-directory (file-name-directory file))
1172       (with-temp-file file
1173         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
1174         (set-buffer-multibyte nil)
1175         (when (file-exists-p file)
1176           (nnheader-insert-file-contents file)
1177
1178           (goto-char (point-min))
1179           (when (re-search-forward
1180                  (concat "^" (regexp-quote group) " ") nil t)
1181             (save-excursion
1182               (setq oactive-max (read (current-buffer)) ;; max
1183                     oactive-min (read (current-buffer)))) ;; min
1184             (gnus-delete-line)))
1185         (insert (format "%S %d %d y\n" (intern group)
1186                         (max (or oactive-max (cdr active)) (cdr active))
1187                         (min (or oactive-min (car active)) (car active))))
1188         (goto-char (point-max))
1189         (while (search-backward "\\." nil t)
1190           (delete-char 1))))))
1191
1192 (defun gnus-agent-group-path (group)
1193   "Translate GROUP into a file name."
1194
1195   ;; NOTE: This is what nnmail-group-pathname does as of Apr 2003.
1196   ;; The two methods must be kept synchronized, which is why
1197   ;; gnus-agent-group-pathname was added.
1198
1199   (setq group
1200         (nnheader-translate-file-chars
1201          (nnheader-replace-duplicate-chars-in-string
1202           (nnheader-replace-chars-in-string 
1203            (gnus-group-real-name group)
1204            ?/ ?_)
1205           ?. ?_)))
1206   (if (or nnmail-use-long-file-names
1207           (file-directory-p (expand-file-name group (gnus-agent-directory))))
1208       group
1209     (mm-encode-coding-string
1210      (nnheader-replace-chars-in-string group ?. ?/)
1211      nnmail-pathname-coding-system)))
1212
1213 (defun gnus-agent-group-pathname (group)
1214   "Translate GROUP into a file name."
1215   ;; nnagent uses nnmail-group-pathname to read articles while
1216   ;; unplugged.  The agent must, therefore, use the same directory
1217   ;; while plugged.
1218   (let ((gnus-command-method (or gnus-command-method
1219                                  (gnus-find-method-for-group group))))
1220     (nnmail-group-pathname (gnus-group-real-name group) (gnus-agent-directory))))
1221
1222 (defun gnus-agent-get-function (method)
1223   (if (gnus-online method)
1224       (car method)
1225     (require 'nnagent)
1226     'nnagent))
1227
1228 (defun gnus-agent-covered-methods ()
1229   "Return the subset of methods that are covered by the agent."
1230   (mapcar #'gnus-server-to-method gnus-agent-covered-methods))
1231
1232 ;;; History functions
1233
1234 (defun gnus-agent-history-buffer ()
1235   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1236
1237 (defun gnus-agent-open-history ()
1238   (save-excursion
1239     (push (cons (gnus-agent-method)
1240                 (set-buffer (gnus-get-buffer-create
1241                              (format " *Gnus agent %s history*"
1242                                      (gnus-agent-method)))))
1243           gnus-agent-history-buffers)
1244     (set-buffer-multibyte nil) ;; everything is binary
1245     (erase-buffer)
1246     (insert "\n")
1247     (let ((file (gnus-agent-lib-file "history")))
1248       (when (file-exists-p file)
1249         (nnheader-insert-file-contents file))
1250       (set (make-local-variable 'gnus-agent-file-name) file))))
1251
1252 (defun gnus-agent-close-history ()
1253   (when (gnus-buffer-live-p gnus-agent-current-history)
1254     (kill-buffer gnus-agent-current-history)
1255     (setq gnus-agent-history-buffers
1256           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1257                 gnus-agent-history-buffers))))
1258
1259 ;;;
1260 ;;; Fetching
1261 ;;;
1262
1263 (defun gnus-agent-fetch-articles (group articles)
1264   "Fetch ARTICLES from GROUP and put them into the Agent."
1265   (when articles
1266     (gnus-agent-load-alist group)
1267     (let* ((alist   gnus-agent-article-alist)
1268            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1269            (selected-sets (list nil))
1270            (current-set-size 0)
1271            article
1272            header-number)
1273       ;; Check each article
1274       (while (setq article (pop articles))
1275         ;; Skip alist entries preceeding this article
1276         (while (> article (or (caar alist) (1+ article)))
1277           (setq alist (cdr alist)))
1278
1279         ;; Prune off articles that we have already fetched.
1280         (unless (and (eq article (caar alist))
1281                      (cdar alist))
1282           ;; Skip headers preceeding this article
1283           (while (> article 
1284                     (setq header-number
1285                           (let* ((header (car headers)))
1286                             (if header
1287                                 (mail-header-number header)
1288                               (1+ article)))))
1289             (setq headers (cdr headers)))
1290
1291           ;; Add this article to the current set
1292           (setcar selected-sets (cons article (car selected-sets)))
1293
1294           ;; Update the set size, when the set is too large start a
1295           ;; new one.  I do this after adding the article as I want at
1296           ;; least one article in each set.
1297           (when (< gnus-agent-max-fetch-size
1298                    (setq current-set-size
1299                          (+ current-set-size
1300                             (if (= header-number article)
1301                                 (let ((char-size (mail-header-chars
1302                                                   (car headers))))
1303                                   (if (<= char-size 0)
1304                                       ;; The char size was missing/invalid,
1305                                       ;; assume a worst-case situation of
1306                                       ;; 65 char/line.  If the line count
1307                                       ;; is missing, arbitrarily assume a
1308                                       ;; size of 1000 characters.
1309                                     (max (* 65 (mail-header-lines
1310                                                 (car headers)))
1311                                          1000)
1312                                     char-size))
1313                               0))))
1314             (setcar selected-sets (nreverse (car selected-sets)))
1315             (setq selected-sets (cons nil selected-sets)
1316                   current-set-size 0))))
1317
1318       (when (or (cdr selected-sets) (car selected-sets))
1319         (let* ((fetched-articles (list nil))
1320                (tail-fetched-articles fetched-articles)
1321                (dir (gnus-agent-group-pathname group))
1322                (date (time-to-days (current-time)))
1323                (case-fold-search t)
1324                pos crosses id)
1325
1326           (setcar selected-sets (nreverse (car selected-sets)))
1327           (setq selected-sets (nreverse selected-sets))
1328
1329           (gnus-make-directory dir)
1330           (gnus-message 7 "Fetching articles for %s..." group)
1331
1332           (unwind-protect
1333               (while (setq articles (pop selected-sets))
1334                 ;; Fetch the articles from the backend.
1335                 (if (gnus-check-backend-function 'retrieve-articles group)
1336                     (setq pos (gnus-retrieve-articles articles group))
1337                   (with-temp-buffer
1338                     (let (article)
1339                       (while (setq article (pop articles))
1340                         (gnus-message 10 "Fetching article %s for %s..."
1341                                       article group)
1342                         (when (or
1343                                (gnus-backlog-request-article group article
1344                                                              nntp-server-buffer)
1345                                (gnus-request-article article group))
1346                           (goto-char (point-max))
1347                           (push (cons article (point)) pos)
1348                           (insert-buffer-substring nntp-server-buffer)))
1349                       (copy-to-buffer
1350                        nntp-server-buffer (point-min) (point-max))
1351                       (setq pos (nreverse pos)))))
1352                 ;; Then save these articles into the Agent.
1353                 (save-excursion
1354                   (set-buffer nntp-server-buffer)
1355                   (while pos
1356                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1357                     (goto-char (point-min))
1358                     (unless (eobp) ;; Don't save empty articles.
1359                       (when (search-forward "\n\n" nil t)
1360                         (when (search-backward "\nXrefs: " nil t)
1361                           ;; Handle cross posting.
1362                           (goto-char (match-end 0)) ; move to end of header name
1363                           (skip-chars-forward "^ ") ; skip server name
1364                           (skip-chars-forward " ")
1365                           (setq crosses nil)
1366                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1367                             (push (cons (buffer-substring (match-beginning 1)
1368                                                           (match-end 1))
1369                                         (string-to-int
1370                                          (buffer-substring (match-beginning 2)
1371                                                            (match-end 2))))
1372                                   crosses)
1373                             (goto-char (match-end 0)))
1374                           (gnus-agent-crosspost crosses (caar pos) date)))
1375                       (goto-char (point-min))
1376                       (if (not (re-search-forward
1377                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1378                           (setq id "No-Message-ID-in-article")
1379                         (setq id (buffer-substring
1380                                   (match-beginning 1) (match-end 1))))
1381                       (write-region-as-coding-system
1382                        gnus-agent-file-coding-system (point-min) (point-max)
1383                        (concat dir (number-to-string (caar pos))) nil 'silent)
1384
1385                       (gnus-agent-append-to-list
1386                        tail-fetched-articles (caar pos)))
1387                     (widen)
1388                     (setq pos (cdr pos)))))
1389
1390             (gnus-agent-save-alist group (cdr fetched-articles) date)
1391             (gnus-message 7 ""))
1392           (cdr fetched-articles))))))
1393
1394 (defun gnus-agent-crosspost (crosses article &optional date)
1395   (setq date (or date t))
1396
1397   (let (gnus-agent-article-alist group alist beg end)
1398     (save-excursion
1399       (set-buffer gnus-agent-overview-buffer)
1400       (when (nnheader-find-nov-line article)
1401         (forward-word 1)
1402         (setq beg (point))
1403         (setq end (progn (forward-line 1) (point)))))
1404     (while crosses
1405       (setq group (caar crosses))
1406       (unless (setq alist (assoc group gnus-agent-group-alist))
1407         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1408               gnus-agent-group-alist))
1409       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1410       (save-excursion
1411         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1412                                                     group)))
1413         (when (= (point-max) (point-min))
1414           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1415           (ignore-errors
1416             (nnheader-insert-file-contents
1417              (gnus-agent-article-name ".overview" group))))
1418         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1419         (insert (string-to-number (cdar crosses)))
1420         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1421         (gnus-agent-check-overview-buffer))
1422       (setq crosses (cdr crosses)))))
1423
1424 (defun gnus-agent-backup-overview-buffer ()
1425   (when gnus-newsgroup-name
1426     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1427           (cnt 0)
1428           name)
1429       (while (file-exists-p
1430               (setq name (concat root "~"
1431                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1432       (write-region (point-min) (point-max) name nil 'no-msg)
1433       (gnus-message 1 "Created backup copy of overview in %s." name)))
1434   t)
1435
1436 (defun gnus-agent-check-overview-buffer (&optional buffer)
1437   "Check the overview file given for sanity.
1438 In particular, checks that the file is sorted by article number
1439 and that there are no duplicates."
1440   (let ((prev-num -1)
1441         (backed-up nil))
1442     (save-excursion
1443       (when buffer
1444         (set-buffer buffer))
1445       (save-restriction
1446         (widen)
1447         (goto-char (point-min))
1448
1449         (while (< (point) (point-max))
1450           (let ((p (point))
1451                 (cur (condition-case nil
1452                          (read (current-buffer))
1453                        (error nil))))
1454             (cond
1455              ((or (not (integerp cur))
1456                   (not (eq (char-after) ?\t)))
1457               (or backed-up
1458                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1459               (gnus-message 1
1460                             "Overview buffer contains garbage '%s'."
1461                             (buffer-substring
1462                              p (gnus-point-at-eol))))
1463              ((= cur prev-num)
1464               (or backed-up
1465                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1466               (gnus-message 1
1467                             "Duplicate overview line for %d" cur)
1468               (delete-region (point) (progn (forward-line 1) (point))))
1469              ((< cur prev-num)
1470               (or backed-up
1471                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1472               (gnus-message 1 "Overview buffer not sorted!")
1473               (sort-numeric-fields 1 (point-min) (point-max))
1474               (goto-char (point-min))
1475               (setq prev-num -1))
1476              (t
1477               (setq prev-num cur)))
1478             (forward-line 1)))))))
1479
1480 (defun gnus-agent-flush-cache ()
1481   (save-excursion
1482     (while gnus-agent-buffer-alist
1483       (set-buffer (cdar gnus-agent-buffer-alist))
1484       (write-region-as-coding-system
1485        gnus-agent-file-coding-system
1486        (point-min) (point-max)
1487        (gnus-agent-article-name ".overview"
1488                                 (caar gnus-agent-buffer-alist))
1489        nil 'silent)
1490       (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1491     (while gnus-agent-group-alist
1492       (with-temp-file (gnus-agent-article-name
1493                        ".agentview" (caar gnus-agent-group-alist))
1494         (princ (cdar gnus-agent-group-alist))
1495         (insert "\n")
1496         (princ 1 (current-buffer))
1497         (insert "\n"))
1498       (setq gnus-agent-group-alist (cdr gnus-agent-group-alist)))))
1499
1500 (defun gnus-agent-find-parameter (group symbol)
1501   "Search for GROUPs SYMBOL in the group's parameters, the group's
1502 topic parameters, the group's category, or the customizable
1503 variables.  Returns the first non-nil value found."
1504   (or (gnus-group-find-parameter group symbol t)
1505       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1506       (symbol-value
1507        (cdr
1508         (assq symbol
1509               '((agent-short-article . gnus-agent-short-article)
1510                 (agent-long-article . gnus-agent-long-article)
1511                 (agent-low-score . gnus-agent-low-score)
1512                 (agent-high-score . gnus-agent-high-score)
1513                 (agent-days-until-old . gnus-agent-expire-days)
1514                 (agent-enable-expiration
1515                  . gnus-agent-enable-expiration)
1516                 (agent-predicate . gnus-agent-predicate)))))))
1517
1518 (defun gnus-agent-fetch-headers (group &optional force)
1519   "Fetch interesting headers into the agent.  The group's overview
1520 file will be updated to include the headers while a list of available
1521 article numbers will be returned."
1522   (let* ((fetch-all (and gnus-agent-consider-all-articles
1523                          ;; Do not fetch all headers if the predicate
1524                          ;; implies that we only consider unread articles.
1525                          (not (gnus-predicate-implies-unread
1526                                (gnus-agent-find-parameter group
1527                                                           'agent-predicate)))))
1528          (articles (if fetch-all
1529                        (gnus-uncompress-range (gnus-active group))
1530                      (gnus-list-of-unread-articles group)))
1531          (gnus-decode-encoded-word-function 'identity)
1532          (file (gnus-agent-article-name ".overview" group)))
1533     ;; Check whether the number of articles is not too large.
1534     (when (and (integerp gnus-agent-large-newsgroup)
1535                (> gnus-agent-large-newsgroup 0))
1536       (setq articles (nthcdr (max (- (length articles)
1537                                      gnus-agent-large-newsgroup)
1538                                   0)
1539                              articles)))
1540     (unless fetch-all
1541       ;; Add articles with marks to the list of article headers we want to
1542       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1543       ;; mark, but do fetch recent or seen articles if they have other, more
1544       ;; interesting marks.  (We have to fetch articles with boring marks
1545       ;; because otherwise the agent will remove their marks.)
1546       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1547         (unless (memq (car arts) '(seen recent killed cache))
1548           (setq articles (gnus-range-add articles (cdr arts)))))
1549       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1550
1551     ;; At this point, I have the list of articles to consider for
1552     ;; fetching.  This is the list that I'll return to my caller. Some
1553     ;; of these articles may have already been fetched.  That's OK as
1554     ;; the fetch article code will filter those out.  Internally, I'll
1555     ;; filter this list to just those articles whose headers need to
1556     ;; be fetched.
1557     (let ((articles articles))
1558       ;; Remove known articles.
1559       (when (and (or gnus-agent-cache
1560                      (not gnus-plugged))
1561                  (gnus-agent-load-alist group))
1562         ;; Remove articles marked as downloaded.
1563         (if fetch-all
1564             ;; I want to fetch all headers in the active range.
1565             ;; Therefore, exclude only those headers that are in the
1566             ;; article alist.
1567             ;; NOTE: This is probably NOT what I want to do after
1568             ;; agent expiration in this group.
1569             (setq articles (gnus-agent-uncached-articles articles group))
1570
1571           ;; I want to only fetch those headers that have never been
1572           ;; fetched.  Therefore, exclude all headers that are, or
1573           ;; WERE, in the article alist.
1574           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1575                 (high (cdr (gnus-active group))))
1576             ;; Low can be greater than High when the same group is
1577             ;; fetched twice in the same session {The first fetch will
1578             ;; fill the article alist such that (last
1579             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1580             ;; group))}.  The addition of one(the 1+ above) then
1581             ;; forces Low to be greater than High.  When this happens,
1582             ;; gnus-list-range-intersection returns nil which
1583             ;; indicates that no headers need to be fetched. -- Kevin
1584             (setq articles (gnus-list-range-intersection
1585                             articles (list (cons low high)))))))
1586
1587       (gnus-message
1588        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1589        (gnus-compress-sequence articles t))
1590
1591       (save-excursion
1592         (set-buffer nntp-server-buffer)
1593
1594         (if articles
1595             (progn
1596               (gnus-message 7 "Fetching headers for %s..." group)
1597
1598               ;; Fetch them.
1599               (gnus-make-directory (nnheader-translate-file-chars
1600                                     (file-name-directory file) t))
1601
1602               (unless (eq 'nov (gnus-retrieve-headers articles group))
1603                 (nnvirtual-convert-headers))
1604               (gnus-agent-check-overview-buffer)
1605               ;; Move these headers to the overview buffer so that
1606               ;; gnus-agent-braid-nov can merge them with the contents
1607               ;; of FILE.
1608               (copy-to-buffer
1609                gnus-agent-overview-buffer (point-min) (point-max))
1610               (when (file-exists-p file)
1611                 (gnus-agent-braid-nov group articles file))
1612               (gnus-agent-check-overview-buffer)
1613               (write-region-as-coding-system
1614                gnus-agent-file-coding-system
1615                (point-min) (point-max) file nil 'silent)
1616               (gnus-agent-save-alist group articles nil)
1617               articles)
1618           (ignore-errors
1619             (erase-buffer)
1620             (nnheader-insert-file-contents file)))))
1621     articles))
1622
1623 (defsubst gnus-agent-copy-nov-line (article)
1624   (let (art b e)
1625     (set-buffer gnus-agent-overview-buffer)
1626     (while (and (not (eobp))
1627                 (< (setq art (read (current-buffer))) article))
1628       (forward-line 1))
1629     (beginning-of-line)
1630     (if (or (eobp)
1631             (not (eq article art)))
1632         (set-buffer nntp-server-buffer)
1633       (setq b (point))
1634       (setq e (progn (forward-line 1) (point)))
1635       (set-buffer nntp-server-buffer)
1636       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1637
1638 (defun gnus-agent-braid-nov (group articles file)
1639   "Merge agent overview data with given file.
1640 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1641 FILE and places the combined headers into `nntp-server-buffer'."
1642   (let (start last)
1643     (set-buffer gnus-agent-overview-buffer)
1644     (goto-char (point-min))
1645     (set-buffer nntp-server-buffer)
1646     (erase-buffer)
1647     (nnheader-insert-file-contents file)
1648     (goto-char (point-max))
1649     (forward-line -1)
1650     (unless (looking-at "[0-9]+\t")
1651       ;; Remove corrupted lines
1652       (gnus-message
1653        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1654       (goto-char (point-min))
1655       (while (not (eobp))
1656         (if (looking-at "[0-9]+\t")
1657             (forward-line 1)
1658           (delete-region (point) (progn (forward-line 1) (point)))))
1659       (forward-line -1))
1660     (unless (or (= (point-min) (point-max))
1661                 (< (setq last (read (current-buffer))) (car articles)))
1662       ;; We do it the hard way.
1663       (when (nnheader-find-nov-line (car articles))
1664         ;; Replacing existing NOV entry
1665         (delete-region (point) (progn (forward-line 1) (point))))
1666       (gnus-agent-copy-nov-line (pop articles))
1667
1668       (ignore-errors
1669         (while articles
1670           (while (let ((art (read (current-buffer))))
1671                    (cond ((< art (car articles))
1672                           (forward-line 1)
1673                           t)
1674                          ((= art (car articles))
1675                           (beginning-of-line)
1676                           (delete-region
1677                            (point) (progn (forward-line 1) (point)))
1678                           nil)
1679                          (t
1680                           (beginning-of-line)
1681                           nil))))
1682
1683           (gnus-agent-copy-nov-line (pop articles)))))
1684
1685     ;; Copy the rest lines
1686     (set-buffer nntp-server-buffer)
1687     (goto-char (point-max))
1688     (when articles
1689       (when last
1690         (set-buffer gnus-agent-overview-buffer)
1691         (ignore-errors
1692           (while (<= (read (current-buffer)) last)
1693             (forward-line 1)))
1694         (beginning-of-line)
1695         (setq start (point))
1696         (set-buffer nntp-server-buffer))
1697       (insert-buffer-substring gnus-agent-overview-buffer start))))
1698
1699 ;; Keeps the compiler from warning about the free variable in
1700 ;; gnus-agent-read-agentview.
1701 (eval-when-compile
1702   (defvar gnus-agent-read-agentview))
1703
1704 (defun gnus-agent-load-alist (group)
1705   "Load the article-state alist for GROUP."
1706   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1707   (let ((gnus-agent-read-agentview group))
1708     (setq gnus-agent-article-alist
1709           (gnus-cache-file-contents
1710            (gnus-agent-article-name ".agentview" group)
1711            'gnus-agent-file-loading-cache
1712            'gnus-agent-read-agentview))))
1713
1714 ;; Save format may be either 1 or 2.  Two is the new, compressed
1715 ;; format that is still being tested.  Format 1 is uncompressed but
1716 ;; known to be reliable.
1717 (defconst gnus-agent-article-alist-save-format 2)
1718
1719 (defun gnus-agent-read-agentview (file)
1720   "Load FILE and do a `read' there."
1721   (with-temp-buffer
1722     (ignore-errors
1723       (nnheader-insert-file-contents file)
1724       (goto-char (point-min))
1725       (let ((alist (read (current-buffer)))
1726             (version (condition-case nil (read (current-buffer))
1727                        (end-of-file 0)))
1728             changed-version)
1729
1730         (cond
1731          ((= version 0)
1732           (let ((inhibit-quit t)
1733                 entry)
1734             (gnus-agent-open-history)
1735             (set-buffer (gnus-agent-history-buffer))
1736             (goto-char (point-min))
1737             (while (not (eobp))
1738               (if (and (looking-at
1739                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1740                        (string= (match-string 2)
1741                                 gnus-agent-read-agentview)
1742                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1743                   (setcdr entry (string-to-number (match-string 1))))
1744               (forward-line 1))
1745             (gnus-agent-close-history)
1746             (setq changed-version t)))
1747          ((= version 1)
1748           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1749          ((= version 2)
1750           (let (uncomp)
1751             (mapcar
1752              (lambda (comp-list)
1753                (let ((state (car comp-list))
1754                      (sequence (gnus-uncompress-sequence
1755                                 (cdr comp-list))))
1756                  (mapcar (lambda (article-id)
1757                            (setq uncomp (cons (cons article-id state) uncomp)))
1758                          sequence)))
1759              alist)
1760             (setq alist (sort uncomp
1761                               (lambda (first second)
1762                                 (< (car first) (car second))))))))
1763         (when changed-version
1764           (let ((gnus-agent-article-alist alist))
1765             (gnus-agent-save-alist gnus-agent-read-agentview)))
1766         alist))))
1767
1768 (defun gnus-agent-save-alist (group &optional articles state dir)
1769   "Save the article-state alist for GROUP."
1770   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1771          (pathname-coding-system nnmail-pathname-coding-system)
1772          (prev (cons nil gnus-agent-article-alist))
1773          (all prev)
1774          print-level print-length item article)
1775     (while (setq article (pop articles))
1776       (while (and (cdr prev)
1777                   (< (caadr prev) article))
1778         (setq prev (cdr prev)))
1779       (cond
1780        ((not (cdr prev))
1781         (setcdr prev (list (cons article state))))
1782        ((> (caadr prev) article)
1783         (setcdr prev (cons (cons article state) (cdr prev))))
1784        ((= (caadr prev) article)
1785         (setcdr (cadr prev) state)))
1786       (setq prev (cdr prev)))
1787     (setq gnus-agent-article-alist (cdr all))
1788     (if dir
1789         (gnus-make-directory dir)
1790       (gnus-make-directory (gnus-agent-article-name "" group)))
1791     (with-temp-file (if dir
1792                         (expand-file-name ".agentview" dir)
1793                       (gnus-agent-article-name ".agentview" group))
1794       (cond ((eq gnus-agent-article-alist-save-format 1)
1795              (princ gnus-agent-article-alist (current-buffer)))
1796             ((eq gnus-agent-article-alist-save-format 2)
1797              (let ((compressed nil))
1798                (mapcar (lambda (pair)
1799                          (let* ((article-id (car pair))
1800                                 (day-of-download (cdr pair))
1801                                 (comp-list (assq day-of-download compressed)))
1802                            (if comp-list
1803                                (setcdr comp-list
1804                                        (cons article-id (cdr comp-list)))
1805                              (setq compressed
1806                                    (cons (list day-of-download article-id)
1807                                          compressed)))
1808                            nil)) gnus-agent-article-alist)
1809                (mapcar (lambda (comp-list)
1810                          (setcdr comp-list
1811                                  (gnus-compress-sequence
1812                                   (nreverse (cdr comp-list)))))
1813                        compressed)
1814                (princ compressed (current-buffer)))))
1815       (insert "\n")
1816       (princ gnus-agent-article-alist-save-format (current-buffer))
1817       (insert "\n"))))
1818
1819 (defun gnus-agent-article-name (article group)
1820   (expand-file-name article
1821                     (file-name-as-directory
1822                      (gnus-agent-group-pathname group))))
1823
1824 (defun gnus-agent-batch-confirmation (msg)
1825   "Show error message and return t."
1826   (gnus-message 1 msg)
1827   t)
1828
1829 ;;;###autoload
1830 (defun gnus-agent-batch-fetch ()
1831   "Start Gnus and fetch session."
1832   (interactive)
1833   (gnus)
1834   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1835     (gnus-agent-fetch-session))
1836   (gnus-group-exit))
1837
1838 (defun gnus-agent-fetch-session ()
1839   "Fetch all articles and headers that are eligible for fetching."
1840   (interactive)
1841   (unless gnus-agent-covered-methods
1842     (error "No servers are covered by the Gnus agent"))
1843   (unless gnus-plugged
1844     (error "Can't fetch articles while Gnus is unplugged"))
1845   (let ((methods (gnus-agent-covered-methods))
1846         groups group gnus-command-method)
1847     (save-excursion
1848       (while methods
1849         (setq gnus-command-method (car methods))
1850         (when (and (or (gnus-server-opened gnus-command-method)
1851                        (gnus-open-server gnus-command-method))
1852                    (gnus-online gnus-command-method))
1853           (setq groups (gnus-groups-from-server (car methods)))
1854           (gnus-agent-with-fetch
1855             (while (setq group (pop groups))
1856               (when (<= (gnus-group-level group)
1857                         gnus-agent-handle-level)
1858                 (if (or debug-on-error debug-on-quit)
1859                     (gnus-agent-fetch-group-1
1860                      group gnus-command-method)
1861                   (condition-case err
1862                       (gnus-agent-fetch-group-1
1863                        group gnus-command-method)
1864                     (error
1865                      (unless (funcall gnus-agent-confirmation-function
1866                                       (format "Error %s.  Continue? "
1867                                               (error-message-string err)))
1868                        (error "Cannot fetch articles into the Gnus agent")))
1869                     (quit
1870                      (unless (funcall gnus-agent-confirmation-function
1871                                       (format
1872                                        "Quit fetching session %s.  Continue? "
1873                                        (error-message-string err)))
1874                        (signal 'quit
1875                                "Cannot fetch articles into the Gnus agent")))))))))
1876         (setq methods (cdr methods)))
1877       (gnus-run-hooks 'gnus-agent-fetched-hook)
1878       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1879
1880 (defun gnus-agent-fetch-group-1 (group method)
1881   "Fetch GROUP."
1882   (let ((gnus-command-method method)
1883         (gnus-newsgroup-name group)
1884         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1885         (gnus-newsgroup-headers gnus-newsgroup-headers)
1886         (gnus-newsgroup-scored gnus-newsgroup-scored)
1887         (gnus-use-cache gnus-use-cache)
1888         (gnus-summary-expunge-below gnus-summary-expunge-below)
1889         (gnus-summary-mark-below gnus-summary-mark-below)
1890         (gnus-orphan-score gnus-orphan-score)
1891         ;; Maybe some other gnus-summary local variables should also
1892         ;; be put here.
1893
1894         gnus-headers
1895         gnus-score
1896         articles arts
1897         category predicate info marks score-param
1898         )
1899     (unless (gnus-check-group group)
1900       (error "Can't open server for %s" group))
1901
1902     ;; Fetch headers.
1903     (when (or gnus-newsgroup-active
1904               (gnus-active group)
1905               (gnus-activate-group group))
1906       (let ((marked-articles gnus-newsgroup-downloadable))
1907         ;; Identify the articles marked for download
1908         (unless gnus-newsgroup-active
1909           ;; The variable gnus-newsgroup-active was selected as I need
1910           ;; a gnus-summary local variable that is NOT bound to any
1911           ;; value (its global value should default to nil).
1912           (dolist (mark gnus-agent-download-marks)
1913             (let ((arts (cdr (assq mark (gnus-info-marks
1914                                          (setq info (gnus-get-info group)))))))
1915               (when arts
1916                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1917                                              marked-articles))
1918                 ))))
1919         (setq marked-articles (sort marked-articles '<))
1920
1921         ;; Fetch any new articles from the server
1922         (setq articles (gnus-agent-fetch-headers group))
1923
1924         ;; Merge new articles with marked
1925         (setq articles (sort (append marked-articles articles) '<))
1926
1927         (when articles
1928           ;; Parse them and see which articles we want to fetch.
1929           (setq gnus-newsgroup-dependencies
1930                 (or gnus-newsgroup-dependencies
1931                     (make-vector (length articles) 0)))
1932           (setq gnus-newsgroup-headers
1933                 (or gnus-newsgroup-headers
1934                     (gnus-get-newsgroup-headers-xover articles nil nil
1935                                                       group)))
1936           ;; `gnus-agent-overview-buffer' may be killed for
1937           ;; timeout reason.  If so, recreate it.
1938           (gnus-agent-create-buffer)
1939
1940           ;; Figure out how to select articles in this group
1941           (setq category (gnus-group-category group))
1942
1943           (setq predicate
1944                 (gnus-get-predicate
1945                  (gnus-agent-find-parameter group 'agent-predicate)))
1946
1947           ;; If the selection predicate requires scoring, score each header
1948           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1949             (let ((score-param
1950                    (gnus-agent-find-parameter group 'agent-score-file)))
1951               ;; Translate score-param into real one
1952               (cond
1953                ((not score-param))
1954                ((eq score-param 'file)
1955                 (setq score-param (gnus-all-score-files group)))
1956                ((stringp (car score-param)))
1957                (t
1958                 (setq score-param (list (list score-param)))))
1959               (when score-param
1960                 (gnus-score-headers score-param))))
1961
1962           (unless (and (eq predicate 'gnus-agent-false)
1963                        (not marked-articles))
1964             (let ((arts (list nil)))
1965               (let ((arts-tail arts)
1966                     (alist (gnus-agent-load-alist group))
1967                     (marked-articles marked-articles)
1968                     (gnus-newsgroup-headers gnus-newsgroup-headers))
1969                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
1970                   (let ((num (mail-header-number gnus-headers)))
1971                     ;; Determine if this article is already in the cache
1972                     (while (and alist
1973                                 (> num (caar alist)))
1974                       (setq alist (cdr alist)))
1975
1976                     (unless (and (eq num (caar alist))
1977                                  (cdar alist))
1978
1979                       ;; Determine if this article was marked for download.
1980                       (while (and marked-articles
1981                                   (> num (car marked-articles)))
1982                         (setq marked-articles
1983                               (cdr marked-articles)))
1984
1985                       ;; When this article is marked, or selected by the
1986                       ;; predicate, add it to the download list
1987                       (when (or (eq num (car marked-articles))
1988                                 (let ((gnus-score
1989                                        (or (cdr
1990                                             (assq num gnus-newsgroup-scored))
1991                                            gnus-summary-default-score))
1992                                       (gnus-agent-long-article
1993                                        (gnus-agent-find-parameter
1994                                         group 'agent-long-article))
1995                                       (gnus-agent-short-article
1996                                        (gnus-agent-find-parameter
1997                                         group 'agent-short-article))
1998                                       (gnus-agent-low-score
1999                                        (gnus-agent-find-parameter
2000                                         group 'agent-low-score))
2001                                       (gnus-agent-high-score
2002                                        (gnus-agent-find-parameter
2003                                         group 'agent-high-score))
2004                                       (gnus-agent-expire-days
2005                                        (gnus-agent-find-parameter
2006                                         group 'agent-days-until-old)))
2007                                   (funcall predicate)))
2008                         (gnus-agent-append-to-list arts-tail num))))))
2009
2010               (let (fetched-articles)
2011                 ;; Fetch all selected articles
2012                 (setq gnus-newsgroup-undownloaded
2013                       (gnus-sorted-ndifference
2014                        gnus-newsgroup-undownloaded
2015                        (setq fetched-articles
2016                              (if (cdr arts)
2017                                  (gnus-agent-fetch-articles group (cdr arts))
2018                                nil))))
2019
2020                 (let ((unfetched-articles
2021                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2022                   (if gnus-newsgroup-active
2023                       ;; Update the summary buffer
2024                       (progn
2025                         (dolist (article marked-articles)
2026                           (gnus-summary-set-agent-mark article t))
2027                         (dolist (article fetched-articles)
2028                           (if gnus-agent-mark-unread-after-downloaded
2029                               (gnus-summary-mark-article
2030                                article gnus-unread-mark))
2031                           (when (gnus-summary-goto-subject article nil t)
2032                             (gnus-summary-update-download-mark article)))
2033                         (dolist (article unfetched-articles)
2034                           (gnus-summary-mark-article
2035                            article gnus-canceled-mark)))
2036
2037                     ;; Update the group buffer.
2038
2039                     ;; When some, or all, of the marked articles came
2040                     ;; from the download mark.  Remove that mark.  I
2041                     ;; didn't do this earlier as I only want to remove
2042                     ;; the marks after the fetch is completed.
2043
2044                     (dolist (mark gnus-agent-download-marks)
2045                       (when (eq mark 'download)
2046                         (let ((marked-arts
2047                                (assq mark (gnus-info-marks
2048                                            (setq info (gnus-get-info group))))))
2049                           (when (cdr marked-arts)
2050                             (setq marks
2051                                   (delq marked-arts (gnus-info-marks info)))
2052                             (gnus-info-set-marks info marks)))))
2053                     (let ((read (gnus-info-read
2054                                  (or info (setq info (gnus-get-info group))))))
2055                       (gnus-info-set-read
2056                        info (gnus-add-to-range read unfetched-articles)))
2057
2058                     (gnus-group-update-group group t)
2059                     (sit-for 0)
2060
2061                     (gnus-dribble-enter
2062                      (concat "(gnus-group-set-info '"
2063                              (gnus-prin1-to-string info)
2064                              ")"))))))))))))
2065
2066 ;;;
2067 ;;; Agent Category Mode
2068 ;;;
2069
2070 (defvar gnus-category-mode-hook nil
2071   "Hook run in `gnus-category-mode' buffers.")
2072
2073 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2074   "Format of category lines.
2075
2076 Valid specifiers include:
2077 %c  Topic name (string)
2078 %g  The number of groups in the topic (integer)
2079
2080 General format specifiers can also be used.  See Info node
2081 `(gnus)Formatting Variables'.")
2082
2083 (defvar gnus-category-mode-line-format "Gnus: %%b"
2084   "The format specification for the category mode line.")
2085
2086 (defvar gnus-agent-predicate 'false
2087   "The selection predicate used when no other source is available.")
2088
2089 (defvar gnus-agent-short-article 100
2090   "Articles that have fewer lines than this are short.")
2091
2092 (defvar gnus-agent-long-article 200
2093   "Articles that have more lines than this are long.")
2094
2095 (defvar gnus-agent-low-score 0
2096   "Articles that have a score lower than this have a low score.")
2097
2098 (defvar gnus-agent-high-score 0
2099   "Articles that have a score higher than this have a high score.")
2100
2101
2102 ;;; Internal variables.
2103
2104 (defvar gnus-category-buffer "*Agent Category*")
2105
2106 (defvar gnus-category-line-format-alist
2107   `((?c gnus-tmp-name ?s)
2108     (?g gnus-tmp-groups ?d)))
2109
2110 (defvar gnus-category-mode-line-format-alist
2111   `((?u user-defined ?s)))
2112
2113 (defvar gnus-category-line-format-spec nil)
2114 (defvar gnus-category-mode-line-format-spec nil)
2115
2116 (defvar gnus-category-mode-map nil)
2117 (put 'gnus-category-mode 'mode-class 'special)
2118
2119 (unless gnus-category-mode-map
2120   (setq gnus-category-mode-map (make-sparse-keymap))
2121   (suppress-keymap gnus-category-mode-map)
2122
2123   (gnus-define-keys gnus-category-mode-map
2124     "q" gnus-category-exit
2125     "k" gnus-category-kill
2126     "c" gnus-category-copy
2127     "a" gnus-category-add
2128     "e" gnus-agent-customize-category
2129     "p" gnus-category-edit-predicate
2130     "g" gnus-category-edit-groups
2131     "s" gnus-category-edit-score
2132     "l" gnus-category-list
2133
2134     "\C-c\C-i" gnus-info-find-node
2135     "\C-c\C-b" gnus-bug))
2136
2137 (defvar gnus-category-menu-hook nil
2138   "*Hook run after the creation of the menu.")
2139
2140 (defun gnus-category-make-menu-bar ()
2141   (gnus-turn-off-edit-menu 'category)
2142   (unless (boundp 'gnus-category-menu)
2143     (easy-menu-define
2144      gnus-category-menu gnus-category-mode-map ""
2145      '("Categories"
2146        ["Add" gnus-category-add t]
2147        ["Kill" gnus-category-kill t]
2148        ["Copy" gnus-category-copy t]
2149        ["Edit category" gnus-agent-customize-category t]
2150        ["Edit predicate" gnus-category-edit-predicate t]
2151        ["Edit score" gnus-category-edit-score t]
2152        ["Edit groups" gnus-category-edit-groups t]
2153        ["Exit" gnus-category-exit t]))
2154
2155     (gnus-run-hooks 'gnus-category-menu-hook)))
2156
2157 (defun gnus-category-mode ()
2158   "Major mode for listing and editing agent categories.
2159
2160 All normal editing commands are switched off.
2161 \\<gnus-category-mode-map>
2162 For more in-depth information on this mode, read the manual
2163 \(`\\[gnus-info-find-node]').
2164
2165 The following commands are available:
2166
2167 \\{gnus-category-mode-map}"
2168   (interactive)
2169   (when (gnus-visual-p 'category-menu 'menu)
2170     (gnus-category-make-menu-bar))
2171   (kill-all-local-variables)
2172   (gnus-simplify-mode-line)
2173   (setq major-mode 'gnus-category-mode)
2174   (setq mode-name "Category")
2175   (gnus-set-default-directory)
2176   (setq mode-line-process nil)
2177   (use-local-map gnus-category-mode-map)
2178   (buffer-disable-undo)
2179   (setq truncate-lines t)
2180   (setq buffer-read-only t)
2181   (gnus-run-hooks 'gnus-category-mode-hook))
2182
2183 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2184
2185 (defun gnus-category-insert-line (category)
2186   (let* ((gnus-tmp-name (format "%s" (car category)))
2187          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2188     (beginning-of-line)
2189     (gnus-add-text-properties
2190      (point)
2191      (prog1 (1+ (point))
2192        ;; Insert the text.
2193        (eval gnus-category-line-format-spec))
2194      (list 'gnus-category gnus-tmp-name))))
2195
2196 (defun gnus-enter-category-buffer ()
2197   "Go to the Category buffer."
2198   (interactive)
2199   (gnus-category-setup-buffer)
2200   (gnus-configure-windows 'category)
2201   (gnus-category-prepare))
2202
2203 (defun gnus-category-setup-buffer ()
2204   (unless (get-buffer gnus-category-buffer)
2205     (save-excursion
2206       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2207       (gnus-category-mode))))
2208
2209 (defun gnus-category-prepare ()
2210   (gnus-set-format 'category-mode)
2211   (gnus-set-format 'category t)
2212   (let ((alist gnus-category-alist)
2213         (buffer-read-only nil))
2214     (erase-buffer)
2215     (while alist
2216       (gnus-category-insert-line (pop alist)))
2217     (goto-char (point-min))
2218     (gnus-category-position-point)))
2219
2220 (defun gnus-category-name ()
2221   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
2222       (error "No category on the current line")))
2223
2224 (defun gnus-category-read ()
2225   "Read the category alist."
2226   (setq gnus-category-alist
2227         (or
2228          (with-temp-buffer
2229            (ignore-errors
2230             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2231             (goto-char (point-min))
2232             ;; This code isn't temp, it will be needed so long as
2233             ;; anyone may be migrating from an older version.
2234
2235             ;; Once we're certain that people will not revert to an
2236             ;; earlier version, we can take out the old-list code in
2237             ;; gnus-category-write.
2238             (let* ((old-list (read (current-buffer)))
2239                    (new-list (ignore-errors (read (current-buffer)))))
2240               (if new-list
2241                   new-list
2242                 ;; Convert from a positional list to an alist.
2243                 (mapcar
2244                  (lambda (c)
2245                    (setcdr c
2246                            (delq nil
2247                                  (gnus-mapcar
2248                                   (lambda (valu symb)
2249                                     (if valu
2250                                         (cons symb valu)))
2251                                   (cdr c)
2252                                   '(agent-predicate agent-score-file agent-groups))))
2253                    c)
2254                  old-list)))))
2255          (list (gnus-agent-cat-make 'default 'short)))))
2256
2257 (defun gnus-category-write ()
2258   "Write the category alist."
2259   (setq gnus-category-predicate-cache nil
2260         gnus-category-group-cache nil)
2261   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2262   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2263     ;; This prin1 is temporary.  It exists so that people can revert
2264     ;; to an earlier version of gnus-agent.
2265     (prin1 (mapcar (lambda (c)
2266               (list (car c)
2267                     (cdr (assoc 'agent-predicate c))
2268                     (cdr (assoc 'agent-score-file c))
2269                     (cdr (assoc 'agent-groups c))))
2270                    gnus-category-alist)
2271            (current-buffer))
2272     (newline)
2273     (prin1 gnus-category-alist (current-buffer))))
2274
2275 (defun gnus-category-edit-predicate (category)
2276   "Edit the predicate for CATEGORY."
2277   (interactive (list (gnus-category-name)))
2278   (let ((info (assq category gnus-category-alist)))
2279     (gnus-edit-form
2280      (gnus-agent-cat-predicate info)
2281      (format "Editing the select predicate for category %s" category)
2282      `(lambda (predicate)
2283         ;; Avoid run-time execution of setf form
2284         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2285         ;;       predicate)
2286         ;; use its expansion instead:
2287         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2288                                      'agent-predicate predicate)
2289
2290         (gnus-category-write)
2291         (gnus-category-list)))))
2292
2293 (defun gnus-category-edit-score (category)
2294   "Edit the score expression for CATEGORY."
2295   (interactive (list (gnus-category-name)))
2296   (let ((info (assq category gnus-category-alist)))
2297     (gnus-edit-form
2298      (gnus-agent-cat-score-file info)
2299      (format "Editing the score expression for category %s" category)
2300      `(lambda (score-file)
2301         ;; Avoid run-time execution of setf form
2302         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2303         ;;       score-file)
2304         ;; use its expansion instead:
2305         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2306                                      'agent-score-file score-file)
2307
2308         (gnus-category-write)
2309         (gnus-category-list)))))
2310
2311 (defun gnus-category-edit-groups (category)
2312   "Edit the group list for CATEGORY."
2313   (interactive (list (gnus-category-name)))
2314   (let ((info (assq category gnus-category-alist)))
2315     (gnus-edit-form
2316      (gnus-agent-cat-groups info)
2317      (format "Editing the group list for category %s" category)
2318      `(lambda (groups)
2319         ;; Avoid run-time execution of setf form
2320         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2321         ;;       groups)
2322         ;; use its expansion instead:
2323         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2324                                    groups)
2325
2326         (gnus-category-write)
2327         (gnus-category-list)))))
2328
2329 (defun gnus-category-kill (category)
2330   "Kill the current category."
2331   (interactive (list (gnus-category-name)))
2332   (let ((info (assq category gnus-category-alist))
2333         (buffer-read-only nil))
2334     (gnus-delete-line)
2335     (setq gnus-category-alist (delq info gnus-category-alist))
2336     (gnus-category-write)))
2337
2338 (defun gnus-category-copy (category to)
2339   "Copy the current category."
2340   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2341   (let ((info (assq category gnus-category-alist)))
2342     (push (let ((newcat (gnus-copy-sequence info)))
2343             (setf (gnus-agent-cat-name newcat) to)
2344             (setf (gnus-agent-cat-groups newcat) nil)
2345             newcat)
2346           gnus-category-alist)
2347     (gnus-category-write)
2348     (gnus-category-list)))
2349
2350 (defun gnus-category-add (category)
2351   "Create a new category."
2352   (interactive "SCategory name: ")
2353   (when (assq category gnus-category-alist)
2354     (error "Category %s already exists" category))
2355   (push (gnus-agent-cat-make category)
2356         gnus-category-alist)
2357   (gnus-category-write)
2358   (gnus-category-list))
2359
2360 (defun gnus-category-list ()
2361   "List all categories."
2362   (interactive)
2363   (gnus-category-prepare))
2364
2365 (defun gnus-category-exit ()
2366   "Return to the group buffer."
2367   (interactive)
2368   (kill-buffer (current-buffer))
2369   (gnus-configure-windows 'group t))
2370
2371 ;; To avoid having 8-bit characters in the source file.
2372 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2373
2374 (defvar gnus-category-predicate-alist
2375   '((spam . gnus-agent-spam-p)
2376     (short . gnus-agent-short-p)
2377     (long . gnus-agent-long-p)
2378     (low . gnus-agent-low-scored-p)
2379     (high . gnus-agent-high-scored-p)
2380     (read . gnus-agent-read-p)
2381     (true . gnus-agent-true)
2382     (false . gnus-agent-false))
2383   "Mapping from short score predicate symbols to predicate functions.")
2384
2385 (defun gnus-agent-spam-p ()
2386   "Say whether an article is spam or not."
2387   (unless gnus-agent-spam-hashtb
2388     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2389   (if (not (equal (mail-header-references gnus-headers) ""))
2390       nil
2391     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2392       (prog1
2393           (gnus-gethash string gnus-agent-spam-hashtb)
2394         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2395
2396 (defun gnus-agent-short-p ()
2397   "Say whether an article is short or not."
2398   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2399
2400 (defun gnus-agent-long-p ()
2401   "Say whether an article is long or not."
2402   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2403
2404 (defun gnus-agent-low-scored-p ()
2405   "Say whether an article has a low score or not."
2406   (< gnus-score gnus-agent-low-score))
2407
2408 (defun gnus-agent-high-scored-p ()
2409   "Say whether an article has a high score or not."
2410   (> gnus-score gnus-agent-high-score))
2411
2412 (defun gnus-agent-read-p ()
2413   "Say whether an article is read or not."
2414   (gnus-member-of-range (mail-header-number gnus-headers)
2415                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2416
2417 (defun gnus-category-make-function (predicate)
2418   "Make a function from PREDICATE."
2419   (let ((func (gnus-category-make-function-1 predicate)))
2420     (if (and (= (length func) 1)
2421              (symbolp (car func)))
2422         (car func)
2423       (gnus-byte-compile `(lambda () ,func)))))
2424
2425 (defun gnus-agent-true ()
2426   "Return t."
2427   t)
2428
2429 (defun gnus-agent-false ()
2430   "Return nil."
2431   nil)
2432
2433 (defun gnus-category-make-function-1 (predicate)
2434   "Make a function from PREDICATE."
2435   (cond
2436    ;; Functions are just returned as is.
2437    ((or (symbolp predicate)
2438         (functionp predicate))
2439     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2440            predicate)))
2441    ;; More complex predicate.
2442    ((consp predicate)
2443     `(,(cond
2444         ((memq (car predicate) '(& and))
2445          'and)
2446         ((memq (car predicate) '(| or))
2447          'or)
2448         ((memq (car predicate) gnus-category-not)
2449          'not))
2450       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2451    (t
2452     (error "Unknown predicate type: %s" predicate))))
2453
2454 (defun gnus-get-predicate (predicate)
2455   "Return the function implementing PREDICATE."
2456   (or (cdr (assoc predicate gnus-category-predicate-cache))
2457       (let ((func (gnus-category-make-function predicate)))
2458         (setq gnus-category-predicate-cache
2459               (nconc gnus-category-predicate-cache
2460                      (list (cons predicate func))))
2461         func)))
2462
2463 (defun gnus-predicate-implies-unread (predicate)
2464   "Say whether PREDICATE implies unread articles only.
2465 It is okay to miss some cases, but there must be no false positives.
2466 That is, if this function returns true, then indeed the predicate must
2467 return only unread articles."
2468   (gnus-function-implies-unread-1 (gnus-category-make-function predicate)))
2469
2470 (defun gnus-function-implies-unread-1 (function)
2471   (cond ((eq function (symbol-function 'gnus-agent-read-p))
2472          nil)
2473         ((not function)
2474          nil)
2475         ((functionp function)
2476          'ignore)
2477         ((memq (car function) '(or and not))
2478          (apply (car function)
2479                 (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2480         (t
2481          (error "Unknown function: %s" function))))
2482
2483 (defun gnus-group-category (group)
2484   "Return the category GROUP belongs to."
2485   (unless gnus-category-group-cache
2486     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2487     (let ((cs gnus-category-alist)
2488           groups cat)
2489       (while (setq cat (pop cs))
2490         (setq groups (gnus-agent-cat-groups cat))
2491         (while groups
2492           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2493   (or (gnus-gethash group gnus-category-group-cache)
2494       (assq 'default gnus-category-alist)))
2495
2496 (defun gnus-agent-expire-group (group &optional articles force)
2497   "Expire all old articles in GROUP.
2498 If you want to force expiring of certain articles, this function can
2499 take ARTICLES, and FORCE parameters as well.
2500
2501 The articles on which the expiration process runs are selected as follows:
2502   if ARTICLES is null, all read and unmarked articles.
2503   if ARTICLES is t, all articles.
2504   if ARTICLES is a list, just those articles.
2505 FORCE is equivalent to setting the expiration predicates to true."
2506   (interactive
2507    (list (let ((def (or (gnus-group-group-name)
2508                         gnus-newsgroup-name)))
2509            (let ((select (read-string (if def
2510                                           (concat "Group Name ("
2511                                                   def "): ")
2512                                         "Group Name: "))))
2513              (if (and (equal "" select)
2514                       def)
2515                  def
2516                select)))))
2517
2518   (if (not group)
2519       (gnus-agent-expire articles group force)
2520     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2521            ;; expiration statistics of this single group
2522           (gnus-agent-expire-stats (list 0 0 0.0)))
2523       (if (or (not (eq articles t))
2524               (yes-or-no-p
2525                (concat "Are you sure that you want to "
2526                        "expire all articles in " group ".")))
2527           (let ((gnus-command-method (gnus-find-method-for-group group))
2528                 (overview (gnus-get-buffer-create " *expire overview*"))
2529                 orig)
2530             (unwind-protect
2531                 (let ((active-file (gnus-agent-lib-file "active")))
2532                   (when (file-exists-p active-file)
2533                     (with-temp-buffer
2534                       (nnheader-insert-file-contents active-file)
2535                       (gnus-active-to-gnus-format
2536                        gnus-command-method
2537                        (setq orig (gnus-make-hashtable
2538                                    (count-lines (point-min) (point-max))))))
2539                     (save-excursion
2540                       (gnus-agent-expire-group-1
2541                        group overview (gnus-gethash-safe group orig)
2542                        articles force))
2543                     (gnus-agent-write-active active-file orig t)))
2544               (kill-buffer overview))))
2545       (gnus-message 4 (gnus-agent-expire-done-message)))))
2546
2547 (defun gnus-agent-expire-group-1 (group overview active articles force)
2548   ;; Internal function - requires caller to have set
2549   ;; gnus-command-method, initialized overview buffer, and to have
2550   ;; provided a non-nil active
2551
2552   (let ((dir (gnus-agent-group-pathname group)))
2553     (when (boundp 'gnus-agent-expire-current-dirs)
2554       (set 'gnus-agent-expire-current-dirs 
2555            (cons dir 
2556                  (symbol-value 'gnus-agent-expire-current-dirs))))
2557
2558     (if (and (not force)
2559              (eq 'DISABLE (gnus-agent-find-parameter group 
2560                                                      'agent-enable-expiration)))
2561         (gnus-message 5 "Expiry skipping over %s" group)
2562       (gnus-message 5 "Expiring articles in %s" group)
2563       (gnus-agent-load-alist group)
2564       (let* ((stats (if (boundp 'gnus-agent-expire-stats)
2565                         ;; Use the list provided by my caller
2566                         (symbol-value 'gnus-agent-expire-stats)
2567                       ;; otherwise use my own temporary list
2568                       (list 0 0 0.0)))
2569              (info (gnus-get-info group))
2570              (alist gnus-agent-article-alist)
2571              (day (- (time-to-days (current-time))
2572                      (gnus-agent-find-parameter group 'agent-days-until-old)))
2573              (specials (if (and alist
2574                                 (not force))
2575                            ;; This could be a bit of a problem.  I need to
2576                            ;; keep the last article to avoid refetching
2577                            ;; headers when using nntp in the backend.  At
2578                            ;; the same time, if someone uses a backend
2579                            ;; that supports article moving then I may have
2580                            ;; to remove the last article to complete the
2581                            ;; move.  Right now, I'm going to assume that
2582                            ;; FORCE overrides specials.
2583                            (list (caar (last alist)))))
2584              (unreads ;; Articles that are excluded from the
2585               ;; expiration process
2586               (cond (gnus-agent-expire-all
2587                      ;; All articles are marked read by global decree
2588                      nil)
2589                     ((eq articles t)
2590                      ;; All articles are marked read by function
2591                      ;; parameter
2592                      nil)
2593                     ((not articles)
2594                      ;; Unread articles are marked protected from
2595                      ;; expiration Don't call
2596                      ;; gnus-list-of-unread-articles as it returns
2597                      ;; articles that have not been fetched into the
2598                      ;; agent.
2599                      (ignore-errors
2600                        (gnus-agent-unread-articles group)))
2601                     (t
2602                      ;; All articles EXCEPT those named by the caller
2603                      ;; are protected from expiration
2604                      (gnus-sorted-difference
2605                       (gnus-uncompress-range
2606                        (cons (caar alist)
2607                              (caar (last alist))))
2608                       (sort articles '<)))))
2609              (marked ;; More articles that are excluded from the
2610               ;; expiration process
2611               (cond (gnus-agent-expire-all
2612                      ;; All articles are unmarked by global decree
2613                      nil)
2614                     ((eq articles t)
2615                      ;; All articles are unmarked by function
2616                      ;; parameter
2617                      nil)
2618                     (articles
2619                      ;; All articles may as well be unmarked as the
2620                      ;; unreads list already names the articles we are
2621                      ;; going to keep
2622                      nil)
2623                     (t
2624                      ;; Ticked and/or dormant articles are excluded
2625                      ;; from expiration
2626                      (nconc
2627                       (gnus-uncompress-range
2628                        (cdr (assq 'tick (gnus-info-marks info))))
2629                       (gnus-uncompress-range
2630                        (cdr (assq 'dormant
2631                                   (gnus-info-marks info))))))))
2632              (nov-file (concat dir ".overview"))
2633              (cnt 0)
2634              (completed -1)
2635              dlist
2636              type)
2637
2638         ;; The normal article alist contains elements that look like
2639         ;; (article# .  fetch_date) I need to combine other
2640         ;; information with this list.  For example, a flag indicating
2641         ;; that a particular article MUST BE KEPT.  To do this, I'm
2642         ;; going to transform the elements to look like (article#
2643         ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2644         ;; the process to generate the expired article alist.
2645
2646         ;; Convert the alist elements to (article# fetch_date nil
2647         ;; nil).
2648         (setq dlist (mapcar (lambda (e)
2649                               (list (car e) (cdr e) nil nil)) alist))
2650
2651         ;; Convert the keep lists to elements that look like (article#
2652         ;; nil keep_flag nil) then append it to the expanded dlist
2653         ;; These statements are sorted by ascending precidence of the
2654         ;; keep_flag.
2655         (setq dlist (nconc dlist
2656                            (mapcar (lambda (e)
2657                                      (list e nil 'unread  nil))
2658                                    unreads)))
2659         (setq dlist (nconc dlist
2660                            (mapcar (lambda (e)
2661                                      (list e nil 'marked  nil))
2662                                    marked)))
2663         (setq dlist (nconc dlist
2664                            (mapcar (lambda (e)
2665                                      (list e nil 'special nil))
2666                                    specials)))
2667
2668         (set-buffer overview)
2669         (erase-buffer)
2670         (buffer-disable-undo)
2671         (when (file-exists-p nov-file)
2672           (gnus-message 7 "gnus-agent-expire: Loading overview...")
2673           (nnheader-insert-file-contents nov-file)
2674           (goto-char (point-min))
2675
2676           (let (p)
2677             (while (< (setq p (point)) (point-max))
2678               (condition-case nil
2679                   ;; If I successfully read an integer (the plus zero
2680                   ;; ensures a numeric type), prepend a marker entry
2681                   ;; to the list
2682                   (push (list (+ 0 (read (current-buffer))) nil nil
2683                               (set-marker (make-marker) p))
2684                         dlist)
2685                 (error
2686                  (gnus-message 1 "gnus-agent-expire: read error \
2687 occurred when reading expression at %s in %s.  Skipping to next \
2688 line." (point) nov-file)))
2689               ;; Whether I succeeded, or failed, it doesn't matter.
2690               ;; Move to the next line then try again.
2691               (forward-line 1)))
2692
2693           (gnus-message
2694            7 "gnus-agent-expire: Loading overview... Done"))
2695         (set-buffer-modified-p nil)
2696
2697         ;; At this point, all of the information is in dlist.  The
2698         ;; only problem is that much of it is spread across multiple
2699         ;; entries.  Sort then MERGE!!
2700         (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2701         ;; If two entries have the same article-number then sort by
2702         ;; ascending keep_flag.
2703         (let ((special 0)
2704               (marked 1)
2705               (unread 2))
2706           (setq dlist
2707                 (sort dlist
2708                       (lambda (a b)
2709                         (cond ((< (nth 0 a) (nth 0 b))
2710                                t)
2711                               ((> (nth 0 a) (nth 0 b))
2712                                nil)
2713                               (t
2714                                (let ((a (or (symbol-value (nth 2 a))
2715                                             3))
2716                                      (b (or (symbol-value (nth 2 b))
2717                                             3)))
2718                                  (<= a b))))))))
2719         (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2720         (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2721         (let ((dlist dlist))
2722           (while (cdr dlist)            ; I'm not at the end-of-list
2723             (if (eq (caar dlist) (caadr dlist))
2724                 (let ((first (cdr (car dlist)))
2725                       (secnd (cdr (cadr dlist))))
2726                   (setcar first (or (car first)
2727                                     (car secnd))) ; fetch_date
2728                   (setq first (cdr first)
2729                         secnd (cdr secnd))
2730                   (setcar first (or (car first)
2731                                     (car secnd))) ; Keep_flag
2732                   (setq first (cdr first)
2733                         secnd (cdr secnd))
2734                   (setcar first (or (car first)
2735                                     (car secnd))) ; NOV_entry_marker
2736
2737                   (setcdr dlist (cddr dlist)))
2738               (setq dlist (cdr dlist)))))
2739         (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2740
2741         (let* ((len (float (length dlist)))
2742                (alist (list nil))
2743                (tail-alist alist))
2744           (while dlist
2745             (let ((new-completed (truncate (* 100.0
2746                                               (/ (setq cnt (1+ cnt))
2747                                                  len)))))
2748               (when (> new-completed completed)
2749                 (setq completed new-completed)
2750                 (gnus-message 7 "%3d%% completed..."  completed)))
2751             (let* ((entry          (car dlist))
2752                    (article-number (nth 0 entry))
2753                    (fetch-date     (nth 1 entry))
2754                    (keep           (nth 2 entry))
2755                    (marker         (nth 3 entry)))
2756
2757               (cond
2758                ;; Kept articles are unread, marked, or special.
2759                (keep
2760                 (gnus-agent-message 10
2761                                     "gnus-agent-expire: Article %d: Kept %s article%s."
2762                                     article-number keep (if fetch-date " and file" ""))
2763                 (when fetch-date
2764                   (unless (file-exists-p
2765                            (concat dir (number-to-string
2766                                         article-number)))
2767                     (setf (nth 1 entry) nil)
2768                     (gnus-agent-message 3 "gnus-agent-expire cleared \
2769 download flag on article %d as the cached article file is missing."
2770                                         (caar dlist)))
2771                   (unless marker
2772                     (gnus-message 1 "gnus-agent-expire detected a \
2773 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2774                 (gnus-agent-append-to-list
2775                  tail-alist
2776                  (cons article-number fetch-date)))
2777
2778                ;; The following articles are READ, UNMARKED, and
2779                ;; ORDINARY.  See if they can be EXPIRED!!!
2780                ((setq type
2781                       (cond
2782                        ((not (integerp fetch-date))
2783                         'read) ;; never fetched article (may expire
2784                        ;; right now)
2785                        ((not (file-exists-p
2786                               (concat dir (number-to-string
2787                                            article-number))))
2788                         (setf (nth 1 entry) nil)
2789                         'externally-expired) ;; Can't find the cached
2790                        ;; article.  Handle case
2791                        ;; as though this article
2792                        ;; was never fetched.
2793
2794                        ;; We now have the arrival day, so we see
2795                        ;; whether it's old enough to be expired.
2796                        ((< fetch-date day)
2797                         'expired)
2798                        (force
2799                         'forced)))
2800
2801                 ;; I found some reason to expire this entry.
2802
2803                 (let ((actions nil))
2804                   (when (memq type '(forced expired))
2805                     (ignore-errors      ; Just being paranoid.
2806                       (let ((file-name (concat dir (number-to-string
2807                                                 article-number))))
2808                         (incf (nth 2 stats) (nth 7 (file-attributes file-name)))
2809                         (incf (nth 1 stats))
2810                         (delete-file file-name))
2811                       (push "expired cached article" actions))
2812                     (setf (nth 1 entry) nil)
2813                     )
2814
2815                   (when marker
2816                     (push "NOV entry removed" actions)
2817                     (goto-char marker)
2818
2819                     (incf (nth 0 stats))
2820
2821                     (let ((from (gnus-point-at-bol))
2822                           (to (progn (forward-line 1) (point))))
2823                       (incf (nth 2 stats) (- to from))
2824                       (delete-region from to)))
2825
2826                   ;; If considering all articles is set, I can only
2827                   ;; expire article IDs that are no longer in the
2828                   ;; active range (That is, articles that preceed the
2829                   ;; first article in the new alist).
2830                   (if (and gnus-agent-consider-all-articles
2831                            (>= article-number (car active)))
2832                       ;; I have to keep this ID in the alist
2833                       (gnus-agent-append-to-list
2834                        tail-alist (cons article-number fetch-date))
2835                     (push (format "Removed %s article number from \
2836 article alist" type) actions))
2837
2838                   (gnus-agent-message 8 "gnus-agent-expire: Article %d: %s"
2839                                       article-number
2840                                       (mapconcat 'identity actions ", "))))
2841                (t
2842                 (gnus-agent-message
2843                  10 "gnus-agent-expire: Article %d: Article kept as \
2844 expiration tests failed." article-number)
2845                 (gnus-agent-append-to-list
2846                  tail-alist (cons article-number fetch-date)))
2847                )
2848
2849               ;; Clean up markers as I want to recycle this buffer
2850               ;; over several groups.
2851               (when marker
2852                 (set-marker marker nil))
2853
2854               (setq dlist (cdr dlist))))
2855
2856           (setq alist (cdr alist))
2857
2858           (let ((inhibit-quit t))
2859             (unless (equal alist gnus-agent-article-alist)
2860               (setq gnus-agent-article-alist alist)
2861               (gnus-agent-save-alist group)
2862
2863               ;; The active list changed, set the agent's active range
2864               ;; to match the beginning of the list.
2865               (if alist
2866                   (setcar active (caar alist))))
2867
2868             (when (buffer-modified-p)
2869               (gnus-make-directory dir)
2870               (write-region-as-coding-system gnus-agent-file-coding-system
2871                                              (point-min) (point-max) nov-file
2872                                              nil 'silent)
2873               ;; clear the modified flag as that I'm not confused by
2874               ;; its status on the next pass through this routine.
2875               (set-buffer-modified-p nil))
2876
2877             (when (eq articles t)
2878               (gnus-summary-update-info))))))))
2879
2880 (defun gnus-agent-expire (&optional articles group force)
2881   "Expire all old articles.
2882 If you want to force expiring of certain articles, this function can
2883 take ARTICLES, GROUP and FORCE parameters as well.
2884
2885 The articles on which the expiration process runs are selected as follows:
2886   if ARTICLES is null, all read and unmarked articles.
2887   if ARTICLES is t, all articles.
2888   if ARTICLES is a list, just those articles.
2889 Setting GROUP will limit expiration to that group.
2890 FORCE is equivalent to setting the expiration predicates to true."
2891   (interactive)
2892   
2893   (if group
2894       (gnus-agent-expire-group group articles force)
2895     (if (or (not (eq articles t))
2896             (yes-or-no-p "Are you sure that you want to expire all \
2897 articles in every agentized group."))
2898         (let ((methods (gnus-agent-covered-methods))
2899               ;; Bind gnus-agent-expire-current-dirs to enable tracking
2900               ;; of agent directories.
2901               (gnus-agent-expire-current-dirs nil)
2902               ;; Bind gnus-agent-expire-stats to enable tracking of
2903               ;; expiration statistics across all groups
2904               (gnus-agent-expire-stats (list 0 0 0.0))
2905               gnus-command-method overview orig)
2906           (setq overview (gnus-get-buffer-create " *expire overview*"))
2907           (unwind-protect
2908               (while (setq gnus-command-method (pop methods))
2909                 (let ((active-file (gnus-agent-lib-file "active")))
2910                   (when (file-exists-p active-file)
2911                     (with-temp-buffer
2912                       (nnheader-insert-file-contents active-file)
2913                       (gnus-active-to-gnus-format
2914                        gnus-command-method
2915                        (setq orig (gnus-make-hashtable
2916                                    (count-lines (point-min) (point-max))))))
2917                     (dolist (expiring-group (gnus-groups-from-server
2918                                              gnus-command-method))
2919                       (let* ((active
2920                               (gnus-gethash-safe expiring-group orig)))
2921                                         
2922                         (when active
2923                           (save-excursion
2924                             (gnus-agent-expire-group-1
2925                              expiring-group overview active articles force)))))
2926                     (gnus-agent-write-active active-file orig t))))
2927             (kill-buffer overview))
2928           (gnus-agent-expire-unagentized-dirs)
2929           (gnus-message 4 (gnus-agent-expire-done-message))))))
2930
2931 (defun gnus-agent-expire-done-message ()
2932   (if (and (> gnus-verbose 4)
2933            (boundp 'gnus-agent-expire-stats))
2934       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
2935              (size (nth 2 stats))
2936             (units '(B KB MB GB)))
2937         (while (and (> size 1024.0)
2938                     (cdr units))
2939           (setq size (/ size 1024.0)
2940                 units (cdr units)))
2941
2942         (format "Expiry recovered %d NOV entries, deleted %d files,\
2943  and freed %f %s." 
2944                 (nth 0 stats) 
2945                 (nth 1 stats) 
2946                 size (car units)))
2947     "Expiry...done"))
2948
2949 (defun gnus-agent-expire-unagentized-dirs ()
2950   (when (and gnus-agent-expire-unagentized-dirs
2951              (boundp 'gnus-agent-expire-current-dirs))
2952     (let* ((keep (gnus-make-hashtable))
2953            ;; Formally bind gnus-agent-expire-current-dirs so that the
2954            ;; compiler will not complain about free references.
2955            (gnus-agent-expire-current-dirs
2956             (symbol-value 'gnus-agent-expire-current-dirs))
2957            dir)
2958
2959       (gnus-sethash gnus-agent-directory t keep)
2960       (while gnus-agent-expire-current-dirs
2961         (setq dir (pop gnus-agent-expire-current-dirs))
2962         (when (and (stringp dir)
2963                    (file-directory-p dir))
2964           (while (not (gnus-gethash dir keep))
2965             (gnus-sethash dir t keep)
2966             (setq dir (file-name-directory (directory-file-name dir))))))
2967
2968       (let* (to-remove
2969              checker
2970              (checker
2971               (function
2972                (lambda (d)
2973                  "Given a directory, check it and its subdirectories for 
2974               membership in the keep hash.  If it isn't found, add 
2975               it to to-remove." 
2976                  (let ((files (directory-files d))
2977                        file)
2978                    (while (setq file (pop files))
2979                      (cond ((equal file ".") ; Ignore self
2980                             nil)
2981                            ((equal file "..") ; Ignore parent
2982                             nil)
2983                            ((equal file ".overview") 
2984                             ;; Directory must contain .overview to be
2985                             ;; agent's cache of a group.
2986                             (let ((d (file-name-as-directory d))
2987                                   r)
2988                               ;; Search ancestor's for last directory NOT
2989                               ;; found in keep hash.
2990                               (while (not (gnus-gethash
2991                                            (setq d (file-name-directory d)) keep))
2992                                 (setq r d
2993                                       d (directory-file-name d)))
2994                               ;; if ANY ancestor was NOT in keep hash and
2995                               ;; it it's already in to-remove, add it to
2996                               ;; to-remove.                          
2997                               (if (and r
2998                                        (not (member r to-remove)))
2999                                   (push r to-remove))))
3000                            ((file-directory-p (setq file (nnheader-concat d file)))
3001                             (funcall checker file)))))))))
3002         (funcall checker (expand-file-name gnus-agent-directory))
3003
3004         (when (and to-remove
3005                    (or gnus-expert-user
3006                        (gnus-y-or-n-p
3007                         "gnus-agent-expire has identified local directories that are\
3008  not currently required by any agentized group.  Do you wish to consider\
3009  deleting them?")))
3010           (while to-remove
3011             (let ((dir (pop to-remove)))
3012               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3013                   (let* (delete-recursive
3014                          (delete-recursive
3015                           (function
3016                            (lambda (f-or-d)
3017                              (ignore-errors
3018                                (if (file-directory-p f-or-d)
3019                                    (condition-case nil
3020                                        (delete-directory f-or-d)
3021                                      (file-error
3022                                       (mapcar (lambda (f)
3023                                                 (or (member f '("." ".."))
3024                                                     (funcall delete-recursive
3025                                                              (nnheader-concat
3026                                                               f-or-d f))))
3027                                               (directory-files f-or-d))
3028                                       (delete-directory f-or-d)))
3029                                  (delete-file f-or-d)))))))
3030                     (funcall delete-recursive dir))))))))))
3031
3032 ;;;###autoload
3033 (defun gnus-agent-batch ()
3034   "Start Gnus, send queue and fetch session."
3035   (interactive)
3036   (let ((init-file-user "")
3037         (gnus-always-read-dribble-file t))
3038     (gnus))
3039   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3040     (gnus-group-send-queue)
3041     (gnus-agent-fetch-session)))
3042
3043 (defun gnus-agent-unread-articles (group)
3044   (let* ((read (gnus-info-read (gnus-get-info group)))
3045          (known (gnus-agent-load-alist group))
3046          (unread (list nil))
3047          (tail-unread unread))
3048     (while (and known read)
3049       (let ((candidate (car (pop known))))
3050         (while (let* ((range (car read))
3051                       (min   (if (numberp range) range (car range)))
3052                       (max   (if (numberp range) range (cdr range))))
3053                  (cond ((or (not min)
3054                             (< candidate min))
3055                         (gnus-agent-append-to-list tail-unread candidate)
3056                         nil)
3057                        ((> candidate max)
3058                         (setq read (cdr read))
3059                         ;; return t so that I always loop one more
3060                         ;; time.  If I just iterated off the end of
3061                         ;; read, min will become nil and the current
3062                         ;; candidate will be added to the unread list.
3063                         t))))))
3064     (while known
3065       (gnus-agent-append-to-list tail-unread (car (pop known))))
3066     (cdr unread)))
3067
3068 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3069   "Restrict ARTICLES to numbers already fetched.
3070 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3071 that have already been fetched.
3072 If CACHED-HEADER is nil, articles are only excluded if the article itself
3073 has been fetched."
3074
3075   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3076   ;; 'car gnus-agent-article-alist))
3077
3078   ;; Functionally, I don't need to construct a temp list using mapcar.
3079
3080   (if (and (or gnus-agent-cache (not gnus-plugged))
3081            (gnus-agent-load-alist group))
3082     (let* ((ref gnus-agent-article-alist)
3083            (arts articles)
3084            (uncached (list nil))
3085            (tail-uncached uncached))
3086       (while (and ref arts)
3087         (let ((v1 (car arts))
3088               (v2 (caar ref)))
3089           (cond ((< v1 v2) ; v1 does not appear in the reference list
3090                  (gnus-agent-append-to-list tail-uncached v1)
3091                  (setq arts (cdr arts)))
3092                 ((= v1 v2)
3093                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3094                    (gnus-agent-append-to-list tail-uncached v1))
3095                  (setq arts (cdr arts))
3096                  (setq ref (cdr ref)))
3097                 (t ; reference article (v2) preceeds the list being filtered
3098                  (setq ref (cdr ref))))))
3099       (while arts
3100         (gnus-agent-append-to-list tail-uncached (pop arts)))
3101       (cdr uncached))
3102     ;; if gnus-agent-load-alist fails, no articles are cached.
3103     articles))
3104
3105 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3106   (save-excursion
3107     (gnus-agent-create-buffer)
3108     (let ((gnus-decode-encoded-word-function 'identity)
3109           (file (gnus-agent-article-name ".overview" group))
3110           cached-articles uncached-articles)
3111       (gnus-make-directory (nnheader-translate-file-chars
3112                             (file-name-directory file) t))
3113
3114       ;; Populate temp buffer with known headers
3115       (when (file-exists-p file)
3116         (with-current-buffer gnus-agent-overview-buffer
3117           (erase-buffer)
3118           (let ((nnheader-file-coding-system
3119                  gnus-agent-file-coding-system))
3120             (nnheader-insert-nov-file file (car articles)))))
3121
3122       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3123                                                                 t))
3124           (progn
3125             ;; Populate nntp-server-buffer with uncached headers
3126             (set-buffer nntp-server-buffer)
3127             (erase-buffer)
3128             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3129                                    (gnus-retrieve-headers
3130                                     uncached-articles group fetch-old))))
3131                    (nnvirtual-convert-headers))
3132                   ((eq 'nntp (car gnus-current-select-method))
3133                    ;; The author of gnus-get-newsgroup-headers-xover
3134                    ;; reports that the XOVER command is commonly
3135                    ;; unreliable. The problem is that recently
3136                    ;; posted articles may not be entered into the
3137                    ;; NOV database in time to respond to my XOVER
3138                    ;; query.
3139                    ;;
3140                    ;; I'm going to use his assumption that the NOV
3141                    ;; database is updated in order of ascending
3142                    ;; article ID.  Therefore, a response containing
3143                    ;; article ID N implies that all articles from 1
3144                    ;; to N-1 are up-to-date.  Therefore, missing
3145                    ;; articles in that range have expired.
3146
3147                    (set-buffer nntp-server-buffer)
3148                    (let* ((fetched-articles (list nil))
3149                           (tail-fetched-articles fetched-articles)
3150                           (min (cond ((numberp fetch-old)
3151                                       (max 1 (- (car articles) fetch-old)))
3152                                      (fetch-old
3153                                       1)
3154                                      (t
3155                                       (car articles))))
3156                           (max (car (last articles))))
3157
3158                      ;; Get the list of articles that were fetched
3159                      (goto-char (point-min))
3160                      (let ((pm (point-max)))
3161                        (while (< (point) pm)
3162                          (when (looking-at "[0-9]+\t")
3163                            (gnus-agent-append-to-list
3164                             tail-fetched-articles
3165                             (read (current-buffer))))
3166                          (forward-line 1)))
3167
3168                      ;; Clip this list to the headers that will
3169                      ;; actually be returned
3170                      (setq fetched-articles (gnus-list-range-intersection
3171                                              (cdr fetched-articles)
3172                                              (cons min max)))
3173
3174                      ;; Clip the uncached articles list to exclude
3175                      ;; IDs after the last FETCHED header.  The
3176                      ;; excluded IDs may be fetchable using HEAD.
3177                      (if (car tail-fetched-articles)
3178                          (setq uncached-articles
3179                                (gnus-list-range-intersection
3180                                 uncached-articles
3181                                 (cons (car uncached-articles)
3182                                       (car tail-fetched-articles)))))
3183
3184                      ;; Create the list of articles that were
3185                      ;; "successfully" fetched.  Success, in this
3186                      ;; case, means that the ID should not be
3187                      ;; fetched again.  In the case of an expired
3188                      ;; article, the header will not be fetched.
3189                      (setq uncached-articles
3190                            (gnus-sorted-nunion fetched-articles
3191                                                uncached-articles))
3192                      )))
3193
3194             ;; Erase the temp buffer
3195             (set-buffer gnus-agent-overview-buffer)
3196             (erase-buffer)
3197
3198             ;; Copy the nntp-server-buffer to the temp buffer
3199             (set-buffer nntp-server-buffer)
3200             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3201
3202             ;; Merge the temp buffer with the known headers (found on
3203             ;; disk in FILE) into the nntp-server-buffer
3204             (when (and uncached-articles (file-exists-p file))
3205               (gnus-agent-braid-nov group uncached-articles file))
3206
3207             ;; Save the new set of known headers to FILE
3208             (set-buffer nntp-server-buffer)
3209             (gnus-agent-check-overview-buffer)
3210             (write-region-as-coding-system
3211              gnus-agent-file-coding-system
3212              (point-min) (point-max) file nil 'silent)
3213
3214             ;; Update the group's article alist to include the newly
3215             ;; fetched articles.
3216             (gnus-agent-load-alist group)
3217             (gnus-agent-save-alist group uncached-articles nil)
3218             )
3219
3220         ;; Copy the temp buffer to the nntp-server-buffer
3221         (set-buffer nntp-server-buffer)
3222         (erase-buffer)
3223         (insert-buffer-substring gnus-agent-overview-buffer)))
3224
3225     (if (and fetch-old
3226              (not (numberp fetch-old)))
3227         t                               ; Don't remove anything.
3228       (nnheader-nov-delete-outside-range
3229        (if fetch-old (max 1 (- (car articles) fetch-old))
3230          (car articles))
3231        (car (last articles)))
3232       t)
3233
3234     'nov))
3235
3236 (defun gnus-agent-request-article (article group)
3237   "Retrieve ARTICLE in GROUP from the agent cache."
3238   (when (and gnus-agent
3239              (or gnus-agent-cache
3240                  (not gnus-plugged))
3241              (numberp article))
3242     (let* ((gnus-command-method (gnus-find-method-for-group group))
3243            (file (gnus-agent-article-name (number-to-string article) group))
3244            (buffer-read-only nil))
3245       (when (and (file-exists-p file)
3246                  (> (nth 7 (file-attributes file)) 0))
3247         (erase-buffer)
3248         (gnus-kill-all-overlays)
3249         (insert-file-contents-as-coding-system gnus-cache-coding-system file)
3250         t))))
3251
3252 (defun gnus-agent-regenerate-group (group &optional reread)
3253   "Regenerate GROUP.
3254 If REREAD is t, all articles in the .overview are marked as unread.
3255 If REREAD is not nil, downloaded articles are marked as unread."
3256   (interactive
3257    (list (let ((def (or (gnus-group-group-name)
3258                         gnus-newsgroup-name)))
3259            (let ((select (read-string (if def
3260                                           (concat "Group Name ("
3261                                                   def "): ")
3262                                         "Group Name: "))))
3263              (if (and (equal "" select)
3264                       def)
3265                  def
3266                select)))
3267          (catch 'mark
3268            (while (let ((c (read-char-exclusive 
3269                             "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n)"
3270                             )))
3271                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3272                            (throw 'mark nil))
3273                           ((or (eq c ?a) (eq c ?A))
3274                            (throw 'mark t))
3275                           ((or (eq c ?d) (eq c ?D))
3276                            (throw 'mark 'some)))
3277                     (message "Ignoring unexpected input")
3278                     (sit-for 1)
3279                     t)))))
3280   (gnus-message 5 "Regenerating in %s" group)
3281   (let* ((gnus-command-method (or gnus-command-method
3282                                   (gnus-find-method-for-group group)))
3283          (file (gnus-agent-article-name ".overview" group))
3284          (dir (file-name-directory file))
3285          point
3286          (downloaded (if (file-exists-p dir)
3287                          (sort (mapcar (lambda (name) (string-to-int name))
3288                                        (directory-files dir nil "^[0-9]+$" t))
3289                                '>)
3290                        (progn (gnus-make-directory dir) nil)))
3291          dl nov-arts
3292          alist header
3293          regenerated)
3294
3295     (mm-with-unibyte-buffer
3296      (if (file-exists-p file)
3297          (let ((nnheader-file-coding-system
3298                 gnus-agent-file-coding-system))
3299            (nnheader-insert-file-contents file)))
3300      (set-buffer-modified-p nil)
3301
3302      ;; Load the article IDs found in the overview file.  As a
3303      ;; side-effect, validate the file contents.
3304      (let ((load t))
3305        (while load
3306          (setq load nil)
3307          (goto-char (point-min))
3308          (while (< (point) (point-max))
3309            (cond ((and (looking-at "[0-9]+\t")
3310                        (<= (- (match-end 0) (match-beginning 0)) 9))
3311                   (push (read (current-buffer)) nov-arts)
3312                   (forward-line 1)
3313                   (let ((l1 (car nov-arts))
3314                         (l2 (cadr nov-arts)))
3315                     (cond ((not l2)
3316                            nil)
3317                           ((< l1 l2)
3318                            (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3319  entries are NOT in ascending order.")
3320                            ;; Don't sort now as I haven't verified
3321                            ;; that every line begins with a number
3322                            (setq load t))
3323                           ((= l1 l2)
3324                            (forward-line -1)
3325                            (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3326  entries contained duplicate of article %s.      Duplicate deleted." l1)
3327                            (gnus-delete-line)
3328                            (setq nov-arts (cdr nov-arts))))))
3329                  (t
3330                   (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3331  entries contained line that did not begin with an article number.  Deleted\
3332  line.")
3333                   (gnus-delete-line))))
3334          (if load
3335              (progn
3336                (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3337  entries into ascending order.")
3338                (sort-numeric-fields 1 (point-min) (point-max))
3339                     (setq nov-arts nil)))))
3340      (gnus-agent-check-overview-buffer)
3341
3342      ;; Construct a new article alist whose nodes match every header
3343      ;; in the .overview file.  As a side-effect, missing headers are
3344      ;; reconstructed from the downloaded article file.
3345      (while (or downloaded nov-arts)
3346        (cond ((and downloaded
3347                    (or (not nov-arts)
3348                        (> (car downloaded) (car nov-arts))))
3349               ;; This entry is missing from the overview file
3350               (gnus-message 3 "Regenerating NOV %s %d..." group
3351                             (car downloaded))
3352               (let ((file (concat dir (number-to-string (car downloaded)))))
3353                 (mm-with-unibyte-buffer
3354                  (nnheader-insert-file-contents file)
3355                  (nnheader-remove-body)
3356                  (setq header (nnheader-parse-naked-head)))
3357                 (mail-header-set-number header (car downloaded))
3358                 (if nov-arts
3359                     (let ((key (concat "^" (int-to-string (car nov-arts))
3360                                        "\t")))
3361                       (or (re-search-backward key nil t)
3362                           (re-search-forward key))
3363                       (forward-line 1))
3364                   (goto-char (point-min)))
3365                 (nnheader-insert-nov header))
3366               (setq nov-arts (cons (car downloaded) nov-arts)))
3367              ((eq (car downloaded) (car nov-arts))
3368               ;; This entry in the overview has been downloaded
3369               (push (cons (car downloaded)
3370                           (time-to-days
3371                            (nth 5 (file-attributes
3372                                    (concat dir (number-to-string
3373                                                 (car downloaded))))))) alist)
3374               (setq downloaded (cdr downloaded))
3375               (setq nov-arts (cdr nov-arts)))
3376              (t
3377               ;; This entry in the overview has not been downloaded
3378               (push (cons (car nov-arts) nil) alist)
3379               (setq nov-arts (cdr nov-arts)))))
3380
3381      ;; When gnus-agent-consider-all-articles is set,
3382      ;; gnus-agent-regenerate-group should NOT remove article IDs from
3383      ;; the alist.  Those IDs serve as markers to indicate that an
3384      ;; attempt has been made to fetch that article's header.
3385
3386      ;; When gnus-agent-consider-all-articles is NOT set,
3387      ;; gnus-agent-regenerate-group can remove the article ID of every
3388      ;; article (with the exception of the last ID in the list - it's
3389      ;; special) that no longer appears in the overview.  In this
3390      ;; situtation, the last article ID in the list implies that it,
3391      ;; and every article ID preceeding it, have been fetched from the
3392      ;; server.
3393      (if gnus-agent-consider-all-articles
3394          ;; Restore all article IDs that were not found in the overview file.
3395          (let* ((n (cons nil alist))
3396                 (merged n)
3397                 (o (gnus-agent-load-alist group)))
3398            (while o
3399              (let ((nID (caadr n))
3400                    (oID (caar o)))
3401                (cond ((not nID)
3402                       (setq n (setcdr n (list (list oID))))
3403                       (setq o (cdr o)))
3404                      ((< oID nID)
3405                       (setcdr n (cons (list oID) (cdr n)))
3406                       (setq o (cdr o)))
3407                      ((= oID nID)
3408                       (setq o (cdr o))
3409                       (setq n (cdr n)))
3410                      (t
3411                       (setq n (cdr n))))))
3412            (setq alist (cdr merged)))
3413        ;; Restore the last article ID if it is not already in the new alist
3414        (let ((n (last alist))
3415              (o (last (gnus-agent-load-alist group))))
3416          (cond ((not o)
3417                 nil)
3418                ((not n)
3419                 (push (cons (caar o) nil) alist))
3420                ((< (caar n) (caar o))
3421                 (setcdr n (list (car o)))))))
3422
3423      (let ((inhibit-quit t))
3424      (if (setq regenerated (buffer-modified-p))
3425          (write-region-as-coding-system
3426           gnus-agent-file-coding-system
3427           (point-min) (point-max) file nil 'silent))
3428
3429     (setq regenerated (or regenerated
3430                           (and reread gnus-agent-article-alist)
3431                           (not (equal alist gnus-agent-article-alist)))
3432           )
3433
3434     (setq gnus-agent-article-alist alist)
3435
3436     (when regenerated
3437          (gnus-agent-save-alist group)))
3438      )
3439
3440     (when (and reread gnus-agent-article-alist)
3441       (gnus-make-ascending-articles-unread
3442        group
3443        (delq nil (mapcar (function (lambda (c)
3444                                      (cond ((eq reread t)
3445                                             (car c))
3446                                            ((cdr c)
3447                                             (car c)))))
3448                          gnus-agent-article-alist)))
3449
3450       (when (gnus-buffer-live-p gnus-group-buffer)
3451         (gnus-group-update-group group t)
3452         (sit-for 0))
3453       )
3454
3455     (gnus-message 5 nil)
3456     regenerated))
3457
3458 ;;;###autoload
3459 (defun gnus-agent-regenerate (&optional clean reread)
3460   "Regenerate all agent covered files.
3461 If CLEAN, don't read existing active files."
3462   (interactive "P")
3463   (let (regenerated)
3464     (gnus-message 4 "Regenerating Gnus agent files...")
3465     (dolist (gnus-command-method (gnus-agent-covered-methods))
3466       (let ((active-file (gnus-agent-lib-file "active"))
3467             active-hashtb active-changed
3468             point)
3469         (gnus-make-directory (file-name-directory active-file))
3470         (if clean
3471             (setq active-hashtb (gnus-make-hashtable 1000))
3472           (mm-with-unibyte-buffer
3473            (if (file-exists-p active-file)
3474                (let ((nnheader-file-coding-system
3475                       gnus-agent-file-coding-system))
3476                  (nnheader-insert-file-contents active-file))
3477              (setq active-changed t))
3478            (gnus-active-to-gnus-format
3479             nil (setq active-hashtb
3480                       (gnus-make-hashtable
3481                        (count-lines (point-min) (point-max)))))))
3482         (dolist (group (gnus-groups-from-server gnus-command-method))
3483           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3484                                 regenerated))
3485           (let ((min (or (caar gnus-agent-article-alist) 1))
3486                 (max (or (caar (last gnus-agent-article-alist)) 0))
3487                 (active (gnus-gethash-safe (gnus-group-real-name group)
3488                                            active-hashtb))
3489                 (read (gnus-info-read (gnus-get-info group))))
3490             (if (not active)
3491                 (progn
3492                   (setq active (cons min max)
3493                         active-changed t)
3494                   (gnus-sethash group active active-hashtb))
3495               (when (> (car active) min)
3496                 (setcar active min)
3497                 (setq active-changed t))
3498               (when (< (cdr active) max)
3499                 (setcdr active max)
3500                 (setq active-changed t)))))
3501         (when active-changed
3502           (setq regenerated t)
3503           (gnus-message 4 "Regenerate %s" active-file)
3504           (let ((nnmail-active-file-coding-system
3505                  gnus-agent-file-coding-system))
3506             (gnus-write-active-file active-file active-hashtb)))))
3507     (gnus-message 4 "Regenerating Gnus agent files...done")
3508     regenerated))
3509
3510 (defun gnus-agent-go-online (&optional force)
3511   "Switch servers into online status."
3512   (interactive (list t))
3513   (dolist (server gnus-opened-servers)
3514     (when (eq (nth 1 server) 'offline)
3515       (if (if (eq force 'ask)
3516               (gnus-y-or-n-p
3517                (format "Switch %s:%s into online status? "
3518                        (caar server) (cadar server)))
3519             force)
3520           (setcar (nthcdr 1 server) 'close)))))
3521
3522 (defun gnus-agent-toggle-group-plugged (group)
3523   "Toggle the status of the server of the current group."
3524   (interactive (list (gnus-group-group-name)))
3525   (let* ((method (gnus-find-method-for-group group))
3526          (status (cadr (assoc method gnus-opened-servers))))
3527     (if (eq status 'offline)
3528         (gnus-server-set-status method 'closed)
3529       (gnus-close-server method)
3530       (gnus-server-set-status method 'offline))
3531     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3532              (if (eq status 'offline) 'offline 'online)
3533              (if (eq status 'offline) 'online 'offline))))
3534
3535 (defun gnus-agent-group-covered-p (group)
3536   (gnus-agent-method-p (gnus-group-method group)))
3537
3538 (add-hook 'gnus-group-prepare-hook
3539           (lambda ()
3540             'gnus-agent-do-once
3541
3542             (when (listp gnus-agent-expire-days)
3543               (beep)
3544               (beep)
3545               (gnus-message 1 "WARNING: gnus-agent-expire-days no longer\
3546  supports being set to a list.")(sleep-for 3)
3547               (gnus-message 1 "Change your configuration to set it to an\
3548  integer.")(sleep-for 3)
3549               (gnus-message 1 "I am now setting group parameters on each\
3550  group to match the configuration that the list offered.")
3551
3552               (save-excursion
3553                 (let ((groups (gnus-group-listed-groups)))
3554                   (while groups
3555                     (let* ((group (pop groups))
3556                            (days gnus-agent-expire-days)
3557                            (day (catch 'found
3558                                   (while days
3559                                     (when (eq 0 (string-match
3560                                                  (caar days)
3561                                                  group))
3562                                       (throw 'found (cadar days)))
3563                                     (setq days (cdr days)))
3564                                   nil)))
3565                       (when day
3566                         (gnus-group-set-parameter group 'agent-days-until-old
3567                                                   day))))))
3568
3569               (let ((h gnus-group-prepare-hook))
3570                 (while h
3571                   (let ((func (pop h)))
3572                     (when (and (listp func)
3573                                (eq (cadr (caddr func)) 'gnus-agent-do-once))
3574                       (remove-hook 'gnus-group-prepare-hook func)
3575                       (setq h nil)))))
3576
3577               (gnus-message 1 "I have finished setting group parameters on\
3578  each group. You may now customize your groups and/or topics to control the\
3579  agent."))))
3580
3581 (provide 'gnus-agent)
3582
3583 ;;; gnus-agent.el ends here