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