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