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