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