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