c19695d7704adfd5e1c853343abf586821bf74f2
[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-possibly-alter-active (group active)
1155   "Possibly expand a group's active range to include articles
1156 downloaded into the agent."
1157
1158 ;; I can't use the agent's active file here as there is no practical
1159 ;; mechanism to update the active ranges in that file as the oldest
1160 ;; articles are removed from the agent.
1161   (let* ((gnus-command-method (or gnus-command-method
1162                                   (gnus-find-method-for-group group)))
1163          (alist (gnus-agent-load-alist group)))
1164
1165     (let ((new-min (or (caar gnus-agent-article-alist)
1166                        (car active)))
1167           (new-max (or (caar (last gnus-agent-article-alist))
1168                        (cdr active))))
1169
1170         (when (< new-min (car active))
1171           (setcar active new-min))
1172         (when (> new-max (cdr active))
1173           (setcdr active new-max)))))
1174
1175 (defun gnus-agent-save-groups (method)
1176   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
1177
1178 (defun gnus-agent-save-group-info (method group active)
1179   (when (gnus-agent-method-p method)
1180     (let* ((gnus-command-method method)
1181            (coding-system-for-write nnheader-file-coding-system)
1182            (file-name-coding-system nnmail-pathname-coding-system)
1183            (file (gnus-agent-lib-file "active"))
1184            oactive-min oactive-max)
1185       (gnus-make-directory (file-name-directory file))
1186       (with-temp-file file
1187         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
1188         (mm-disable-multibyte)
1189         (when (file-exists-p file)
1190           (nnheader-insert-file-contents file)
1191
1192           (goto-char (point-min))
1193           (when (re-search-forward
1194                  (concat "^" (regexp-quote group) " ") nil t)
1195             (save-excursion
1196               (setq oactive-max (read (current-buffer)) ;; max
1197                     oactive-min (read (current-buffer)))) ;; min
1198             (gnus-delete-line)))
1199         (insert (format "%S %d %d y\n" (intern group)
1200                         (max (or oactive-max (cdr active)) (cdr active))
1201                         (min (or oactive-min (car active)) (car active))))
1202         (goto-char (point-max))
1203         (while (search-backward "\\." nil t)
1204           (delete-char 1))))))
1205
1206 (defun gnus-agent-group-path (group)
1207   "Translate GROUP into a file name."
1208
1209   ;; NOTE: This is what nnmail-group-pathname does as of Apr 2003.
1210   ;; The two methods must be kept synchronized, which is why
1211   ;; gnus-agent-group-pathname was added.
1212
1213   (setq group
1214         (nnheader-translate-file-chars
1215          (nnheader-replace-duplicate-chars-in-string
1216           (nnheader-replace-chars-in-string 
1217            (gnus-group-real-name group)
1218            ?/ ?_)
1219           ?. ?_)))
1220   (if (or nnmail-use-long-file-names
1221           (file-directory-p (expand-file-name group (gnus-agent-directory))))
1222       group
1223     (mm-encode-coding-string
1224      (nnheader-replace-chars-in-string group ?. ?/)
1225      nnmail-pathname-coding-system)))
1226
1227 (defun gnus-agent-group-pathname (group)
1228   "Translate GROUP into a file name."
1229   ;; nnagent uses nnmail-group-pathname to read articles while
1230   ;; unplugged.  The agent must, therefore, use the same directory
1231   ;; while plugged.
1232   (let ((gnus-command-method (or gnus-command-method
1233                                  (gnus-find-method-for-group group))))
1234     (nnmail-group-pathname (gnus-group-real-name group) (gnus-agent-directory))))
1235
1236 (defun gnus-agent-get-function (method)
1237   (if (gnus-online method)
1238       (car method)
1239     (require 'nnagent)
1240     'nnagent))
1241
1242 (defun gnus-agent-covered-methods ()
1243   "Return the subset of methods that are covered by the agent."
1244   (delq nil (mapcar #'gnus-server-to-method gnus-agent-covered-methods)))
1245
1246 ;;; History functions
1247
1248 (defun gnus-agent-history-buffer ()
1249   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1250
1251 (defun gnus-agent-open-history ()
1252   (save-excursion
1253     (push (cons (gnus-agent-method)
1254                 (set-buffer (gnus-get-buffer-create
1255                              (format " *Gnus agent %s history*"
1256                                      (gnus-agent-method)))))
1257           gnus-agent-history-buffers)
1258     (mm-disable-multibyte) ;; everything is binary
1259     (erase-buffer)
1260     (insert "\n")
1261     (let ((file (gnus-agent-lib-file "history")))
1262       (when (file-exists-p file)
1263         (nnheader-insert-file-contents file))
1264       (set (make-local-variable 'gnus-agent-file-name) file))))
1265
1266 (defun gnus-agent-close-history ()
1267   (when (gnus-buffer-live-p gnus-agent-current-history)
1268     (kill-buffer gnus-agent-current-history)
1269     (setq gnus-agent-history-buffers
1270           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1271                 gnus-agent-history-buffers))))
1272
1273 ;;;
1274 ;;; Fetching
1275 ;;;
1276
1277 (defun gnus-agent-fetch-articles (group articles)
1278   "Fetch ARTICLES from GROUP and put them into the Agent."
1279   (when articles
1280     (gnus-agent-load-alist group)
1281     (let* ((alist   gnus-agent-article-alist)
1282            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1283            (selected-sets (list nil))
1284            (current-set-size 0)
1285            article
1286            header-number)
1287       ;; Check each article
1288       (while (setq article (pop articles))
1289         ;; Skip alist entries preceeding this article
1290         (while (> article (or (caar alist) (1+ article)))
1291           (setq alist (cdr alist)))
1292
1293         ;; Prune off articles that we have already fetched.
1294         (unless (and (eq article (caar alist))
1295                      (cdar alist))
1296           ;; Skip headers preceeding this article
1297           (while (> article 
1298                     (setq header-number
1299                           (let* ((header (car headers)))
1300                             (if header
1301                                 (mail-header-number header)
1302                               (1+ article)))))
1303             (setq headers (cdr headers)))
1304
1305           ;; Add this article to the current set
1306           (setcar selected-sets (cons article (car selected-sets)))
1307
1308           ;; Update the set size, when the set is too large start a
1309           ;; new one.  I do this after adding the article as I want at
1310           ;; least one article in each set.
1311           (when (< gnus-agent-max-fetch-size
1312                    (setq current-set-size
1313                          (+ current-set-size
1314                             (if (= header-number article)
1315                                 (let ((char-size (mail-header-chars
1316                                                   (car headers))))
1317                                   (if (<= char-size 0)
1318                                       ;; The char size was missing/invalid,
1319                                       ;; assume a worst-case situation of
1320                                       ;; 65 char/line.  If the line count
1321                                       ;; is missing, arbitrarily assume a
1322                                       ;; size of 1000 characters.
1323                                     (max (* 65 (mail-header-lines
1324                                                 (car headers)))
1325                                          1000)
1326                                     char-size))
1327                               0))))
1328             (setcar selected-sets (nreverse (car selected-sets)))
1329             (setq selected-sets (cons nil selected-sets)
1330                   current-set-size 0))))
1331
1332       (when (or (cdr selected-sets) (car selected-sets))
1333         (let* ((fetched-articles (list nil))
1334                (tail-fetched-articles fetched-articles)
1335                (dir (gnus-agent-group-pathname group))
1336                (date (time-to-days (current-time)))
1337                (case-fold-search t)
1338                pos crosses id)
1339
1340           (setcar selected-sets (nreverse (car selected-sets)))
1341           (setq selected-sets (nreverse selected-sets))
1342
1343           (gnus-make-directory dir)
1344           (gnus-message 7 "Fetching articles for %s..." group)
1345
1346           (unwind-protect
1347               (while (setq articles (pop selected-sets))
1348                 ;; Fetch the articles from the backend.
1349                 (if (gnus-check-backend-function 'retrieve-articles group)
1350                     (setq pos (gnus-retrieve-articles articles group))
1351                   (with-temp-buffer
1352                     (let (article)
1353                       (while (setq article (pop articles))
1354                         (gnus-message 10 "Fetching article %s for %s..."
1355                                       article group)
1356                         (when (or
1357                                (gnus-backlog-request-article group article
1358                                                              nntp-server-buffer)
1359                                (gnus-request-article article group))
1360                           (goto-char (point-max))
1361                           (push (cons article (point)) pos)
1362                           (insert-buffer-substring nntp-server-buffer)))
1363                       (copy-to-buffer
1364                        nntp-server-buffer (point-min) (point-max))
1365                       (setq pos (nreverse pos)))))
1366                 ;; Then save these articles into the Agent.
1367                 (save-excursion
1368                   (set-buffer nntp-server-buffer)
1369                   (while pos
1370                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1371                     (goto-char (point-min))
1372                     (unless (eobp) ;; Don't save empty articles.
1373                       (when (search-forward "\n\n" nil t)
1374                         (when (search-backward "\nXrefs: " nil t)
1375                           ;; Handle cross posting.
1376                           (goto-char (match-end 0)) ; move to end of header name
1377                           (skip-chars-forward "^ ") ; skip server name
1378                           (skip-chars-forward " ")
1379                           (setq crosses nil)
1380                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1381                             (push (cons (buffer-substring (match-beginning 1)
1382                                                           (match-end 1))
1383                                         (string-to-int
1384                                          (buffer-substring (match-beginning 2)
1385                                                            (match-end 2))))
1386                                   crosses)
1387                             (goto-char (match-end 0)))
1388                           (gnus-agent-crosspost crosses (caar pos) date)))
1389                       (goto-char (point-min))
1390                       (if (not (re-search-forward
1391                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1392                           (setq id "No-Message-ID-in-article")
1393                         (setq id (buffer-substring
1394                                   (match-beginning 1) (match-end 1))))
1395                       (let ((coding-system-for-write
1396                              gnus-agent-file-coding-system))
1397                         (write-region (point-min) (point-max)
1398                                       (concat dir (number-to-string (caar pos)))
1399                                       nil 'silent))
1400
1401                       (gnus-agent-append-to-list
1402                        tail-fetched-articles (caar pos)))
1403                     (widen)
1404                     (setq pos (cdr pos)))))
1405
1406             (gnus-agent-save-alist group (cdr fetched-articles) date)
1407             (gnus-message 7 ""))
1408           (cdr fetched-articles))))))
1409
1410 (defun gnus-agent-crosspost (crosses article &optional date)
1411   (setq date (or date t))
1412
1413   (let (gnus-agent-article-alist group alist beg end)
1414     (save-excursion
1415       (set-buffer gnus-agent-overview-buffer)
1416       (when (nnheader-find-nov-line article)
1417         (forward-word 1)
1418         (setq beg (point))
1419         (setq end (progn (forward-line 1) (point)))))
1420     (while crosses
1421       (setq group (caar crosses))
1422       (unless (setq alist (assoc group gnus-agent-group-alist))
1423         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1424               gnus-agent-group-alist))
1425       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1426       (save-excursion
1427         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1428                                                     group)))
1429         (when (= (point-max) (point-min))
1430           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1431           (ignore-errors
1432             (nnheader-insert-file-contents
1433              (gnus-agent-article-name ".overview" group))))
1434         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1435         (insert (string-to-number (cdar crosses)))
1436         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1437         (gnus-agent-check-overview-buffer))
1438       (setq crosses (cdr crosses)))))
1439
1440 (defun gnus-agent-backup-overview-buffer ()
1441   (when gnus-newsgroup-name
1442     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1443           (cnt 0)
1444           name)
1445       (while (file-exists-p
1446               (setq name (concat root "~"
1447                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1448       (write-region (point-min) (point-max) name nil 'no-msg)
1449       (gnus-message 1 "Created backup copy of overview in %s." name)))
1450   t)
1451
1452 (defun gnus-agent-check-overview-buffer (&optional buffer)
1453   "Check the overview file given for sanity.
1454 In particular, checks that the file is sorted by article number
1455 and that there are no duplicates."
1456   (let ((prev-num -1)
1457         (backed-up nil))
1458     (save-excursion
1459       (when buffer
1460         (set-buffer buffer))
1461       (save-restriction
1462         (widen)
1463         (goto-char (point-min))
1464
1465         (while (< (point) (point-max))
1466           (let ((p (point))
1467                 (cur (condition-case nil
1468                          (read (current-buffer))
1469                        (error nil))))
1470             (cond
1471              ((or (not (integerp cur))
1472                   (not (eq (char-after) ?\t)))
1473               (or backed-up
1474                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1475               (gnus-message 1
1476                             "Overview buffer contains garbage '%s'."
1477                             (buffer-substring
1478                              p (gnus-point-at-eol))))
1479              ((= cur prev-num)
1480               (or backed-up
1481                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1482               (gnus-message 1
1483                             "Duplicate overview line for %d" cur)
1484               (delete-region (point) (progn (forward-line 1) (point))))
1485              ((< cur prev-num)
1486               (or backed-up
1487                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1488               (gnus-message 1 "Overview buffer not sorted!")
1489               (sort-numeric-fields 1 (point-min) (point-max))
1490               (goto-char (point-min))
1491               (setq prev-num -1))
1492              (t
1493               (setq prev-num cur)))
1494             (forward-line 1)))))))
1495
1496 (defun gnus-agent-flush-cache ()
1497   (save-excursion
1498     (while gnus-agent-buffer-alist
1499       (set-buffer (cdar gnus-agent-buffer-alist))
1500       (let ((coding-system-for-write
1501              gnus-agent-file-coding-system))
1502         (write-region (point-min) (point-max)
1503                       (gnus-agent-article-name ".overview"
1504                                                (caar gnus-agent-buffer-alist))
1505                       nil 'silent))
1506       (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1507     (while gnus-agent-group-alist
1508       (with-temp-file (gnus-agent-article-name
1509                        ".agentview" (caar gnus-agent-group-alist))
1510         (princ (cdar gnus-agent-group-alist))
1511         (insert "\n")
1512         (princ 1 (current-buffer))
1513         (insert "\n"))
1514       (setq gnus-agent-group-alist (cdr gnus-agent-group-alist)))))
1515
1516 (defun gnus-agent-find-parameter (group symbol)
1517   "Search for GROUPs SYMBOL in the group's parameters, the group's
1518 topic parameters, the group's category, or the customizable
1519 variables.  Returns the first non-nil value found."
1520   (or (gnus-group-find-parameter group symbol t)
1521       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1522       (symbol-value
1523        (cdr
1524         (assq symbol
1525               '((agent-short-article . gnus-agent-short-article)
1526                 (agent-long-article . gnus-agent-long-article)
1527                 (agent-low-score . gnus-agent-low-score)
1528                 (agent-high-score . gnus-agent-high-score)
1529                 (agent-days-until-old . gnus-agent-expire-days)
1530                 (agent-enable-expiration
1531                  . gnus-agent-enable-expiration)
1532                 (agent-predicate . gnus-agent-predicate)))))))
1533
1534 (defun gnus-agent-fetch-headers (group &optional force)
1535   "Fetch interesting headers into the agent.  The group's overview
1536 file will be updated to include the headers while a list of available
1537 article numbers will be returned."
1538   (let* ((fetch-all (and gnus-agent-consider-all-articles
1539                          ;; Do not fetch all headers if the predicate
1540                          ;; implies that we only consider unread articles.
1541                          (not (gnus-predicate-implies-unread
1542                                (gnus-agent-find-parameter group
1543                                                           'agent-predicate)))))
1544          (articles (if fetch-all
1545                        (gnus-uncompress-range (gnus-active group))
1546                      (gnus-list-of-unread-articles group)))
1547          (gnus-decode-encoded-word-function 'identity)
1548          (file (gnus-agent-article-name ".overview" group)))
1549
1550     (unless fetch-all
1551       ;; Add articles with marks to the list of article headers we want to
1552       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1553       ;; mark, but do fetch recent or seen articles if they have other, more
1554       ;; interesting marks.  (We have to fetch articles with boring marks
1555       ;; because otherwise the agent will remove their marks.)
1556       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1557         (unless (memq (car arts) '(seen recent killed cache))
1558           (setq articles (gnus-range-add articles (cdr arts)))))
1559       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1560
1561     ;; At this point, I have the list of articles to consider for
1562     ;; fetching.  This is the list that I'll return to my caller. Some
1563     ;; of these articles may have already been fetched.  That's OK as
1564     ;; the fetch article code will filter those out.  Internally, I'll
1565     ;; filter this list to just those articles whose headers need to
1566     ;; be fetched.
1567     (let ((articles articles))
1568       ;; Remove known articles.
1569       (when (and (or gnus-agent-cache
1570                      (not gnus-plugged))
1571                  (gnus-agent-load-alist group))
1572         ;; Remove articles marked as downloaded.
1573         (if fetch-all
1574             ;; I want to fetch all headers in the active range.
1575             ;; Therefore, exclude only those headers that are in the
1576             ;; article alist.
1577             ;; NOTE: This is probably NOT what I want to do after
1578             ;; agent expiration in this group.
1579             (setq articles (gnus-agent-uncached-articles articles group))
1580
1581           ;; I want to only fetch those headers that have never been
1582           ;; fetched.  Therefore, exclude all headers that are, or
1583           ;; WERE, in the article alist.
1584           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1585                 (high (cdr (gnus-active group))))
1586             ;; Low can be greater than High when the same group is
1587             ;; fetched twice in the same session {The first fetch will
1588             ;; fill the article alist such that (last
1589             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1590             ;; group))}.  The addition of one(the 1+ above) then
1591             ;; forces Low to be greater than High.  When this happens,
1592             ;; gnus-list-range-intersection returns nil which
1593             ;; indicates that no headers need to be fetched. -- Kevin
1594             (setq articles (gnus-list-range-intersection
1595                             articles (list (cons low high)))))))
1596
1597       (gnus-message
1598        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1599        (gnus-compress-sequence articles t))
1600
1601       (save-excursion
1602         (set-buffer nntp-server-buffer)
1603
1604         (if articles
1605             (progn
1606               (gnus-message 7 "Fetching headers for %s..." group)
1607
1608               ;; Fetch them.
1609               (gnus-make-directory (nnheader-translate-file-chars
1610                                     (file-name-directory file) t))
1611
1612               (unless (eq 'nov (gnus-retrieve-headers articles group))
1613                 (nnvirtual-convert-headers))
1614               (gnus-agent-check-overview-buffer)
1615               ;; Move these headers to the overview buffer so that
1616               ;; gnus-agent-braid-nov can merge them with the contents
1617               ;; of FILE.
1618               (copy-to-buffer
1619                gnus-agent-overview-buffer (point-min) (point-max))
1620               (when (file-exists-p file)
1621                 (gnus-agent-braid-nov group articles file))
1622               (let ((coding-system-for-write
1623                      gnus-agent-file-coding-system))
1624                 (gnus-agent-check-overview-buffer)
1625                 (write-region (point-min) (point-max) file nil 'silent))
1626               (gnus-agent-save-alist group articles nil)
1627               articles)
1628           (ignore-errors
1629             (erase-buffer)
1630             (nnheader-insert-file-contents file)))))
1631     articles))
1632
1633 (defsubst gnus-agent-copy-nov-line (article)
1634   (let (art b e)
1635     (set-buffer gnus-agent-overview-buffer)
1636     (while (and (not (eobp))
1637                 (< (setq art (read (current-buffer))) article))
1638       (forward-line 1))
1639     (beginning-of-line)
1640     (if (or (eobp)
1641             (not (eq article art)))
1642         (set-buffer nntp-server-buffer)
1643       (setq b (point))
1644       (setq e (progn (forward-line 1) (point)))
1645       (set-buffer nntp-server-buffer)
1646       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1647
1648 (defun gnus-agent-braid-nov (group articles file)
1649   "Merge agent overview data with given file.
1650 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1651 FILE and places the combined headers into `nntp-server-buffer'."
1652   (let (start last)
1653     (set-buffer gnus-agent-overview-buffer)
1654     (goto-char (point-min))
1655     (set-buffer nntp-server-buffer)
1656     (erase-buffer)
1657     (nnheader-insert-file-contents file)
1658     (goto-char (point-max))
1659     (forward-line -1)
1660     (unless (looking-at "[0-9]+\t")
1661       ;; Remove corrupted lines
1662       (gnus-message
1663        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1664       (goto-char (point-min))
1665       (while (not (eobp))
1666         (if (looking-at "[0-9]+\t")
1667             (forward-line 1)
1668           (delete-region (point) (progn (forward-line 1) (point)))))
1669       (forward-line -1))
1670     (unless (or (= (point-min) (point-max))
1671                 (< (setq last (read (current-buffer))) (car articles)))
1672       ;; We do it the hard way.
1673       (when (nnheader-find-nov-line (car articles))
1674         ;; Replacing existing NOV entry
1675         (delete-region (point) (progn (forward-line 1) (point))))
1676       (gnus-agent-copy-nov-line (pop articles))
1677
1678       (ignore-errors
1679         (while articles
1680           (while (let ((art (read (current-buffer))))
1681                    (cond ((< art (car articles))
1682                           (forward-line 1)
1683                           t)
1684                          ((= art (car articles))
1685                           (beginning-of-line)
1686                           (delete-region
1687                            (point) (progn (forward-line 1) (point)))
1688                           nil)
1689                          (t
1690                           (beginning-of-line)
1691                           nil))))
1692
1693           (gnus-agent-copy-nov-line (pop articles)))))
1694
1695     ;; Copy the rest lines
1696     (set-buffer nntp-server-buffer)
1697     (goto-char (point-max))
1698     (when articles
1699       (when last
1700         (set-buffer gnus-agent-overview-buffer)
1701         (ignore-errors
1702           (while (<= (read (current-buffer)) last)
1703             (forward-line 1)))
1704         (beginning-of-line)
1705         (setq start (point))
1706         (set-buffer nntp-server-buffer))
1707       (insert-buffer-substring gnus-agent-overview-buffer start))))
1708
1709 ;; Keeps the compiler from warning about the free variable in
1710 ;; gnus-agent-read-agentview.
1711 (eval-when-compile
1712   (defvar gnus-agent-read-agentview))
1713
1714 (defun gnus-agent-load-alist (group)
1715   "Load the article-state alist for GROUP."
1716   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1717   (let ((gnus-agent-read-agentview group))
1718     (setq gnus-agent-article-alist
1719           (gnus-cache-file-contents
1720            (gnus-agent-article-name ".agentview" group)
1721            'gnus-agent-file-loading-cache
1722            'gnus-agent-read-agentview))))
1723
1724 ;; Save format may be either 1 or 2.  Two is the new, compressed
1725 ;; format that is still being tested.  Format 1 is uncompressed but
1726 ;; known to be reliable.
1727 (defconst gnus-agent-article-alist-save-format 2)
1728
1729 (defun gnus-agent-read-agentview (file)
1730   "Load FILE and do a `read' there."
1731   (with-temp-buffer
1732     (ignore-errors
1733       (nnheader-insert-file-contents file)
1734       (goto-char (point-min))
1735       (let ((alist (read (current-buffer)))
1736             (version (condition-case nil (read (current-buffer))
1737                        (end-of-file 0)))
1738             changed-version)
1739
1740         (cond
1741          ((= version 0)
1742           (let ((inhibit-quit t)
1743                 entry)
1744             (gnus-agent-open-history)
1745             (set-buffer (gnus-agent-history-buffer))
1746             (goto-char (point-min))
1747             (while (not (eobp))
1748               (if (and (looking-at
1749                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1750                        (string= (match-string 2)
1751                                 gnus-agent-read-agentview)
1752                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1753                   (setcdr entry (string-to-number (match-string 1))))
1754               (forward-line 1))
1755             (gnus-agent-close-history)
1756             (setq changed-version t)))
1757          ((= version 1)
1758           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1759          ((= version 2)
1760           (let (uncomp)
1761             (mapcar
1762              (lambda (comp-list)
1763                (let ((state (car comp-list))
1764                      (sequence (gnus-uncompress-sequence
1765                                 (cdr comp-list))))
1766                  (mapcar (lambda (article-id)
1767                            (setq uncomp (cons (cons article-id state) uncomp)))
1768                          sequence)))
1769              alist)
1770             (setq alist (sort uncomp
1771                               (lambda (first second)
1772                                 (< (car first) (car second))))))))
1773         (when changed-version
1774           (let ((gnus-agent-article-alist alist))
1775             (gnus-agent-save-alist gnus-agent-read-agentview)))
1776         alist))))
1777
1778 (defun gnus-agent-save-alist (group &optional articles state dir)
1779   "Save the article-state alist for GROUP."
1780   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1781          (prev (cons nil gnus-agent-article-alist))
1782          (all prev)
1783          print-level print-length item article)
1784     (while (setq article (pop articles))
1785       (while (and (cdr prev)
1786                   (< (caadr prev) article))
1787         (setq prev (cdr prev)))
1788       (cond
1789        ((not (cdr prev))
1790         (setcdr prev (list (cons article state))))
1791        ((> (caadr prev) article)
1792         (setcdr prev (cons (cons article state) (cdr prev))))
1793        ((= (caadr prev) article)
1794         (setcdr (cadr prev) state)))
1795       (setq prev (cdr prev)))
1796     (setq gnus-agent-article-alist (cdr all))
1797     (if dir
1798         (gnus-make-directory dir)
1799       (gnus-make-directory (gnus-agent-article-name "" group)))
1800     (with-temp-file (if dir
1801                         (expand-file-name ".agentview" dir)
1802                       (gnus-agent-article-name ".agentview" group))
1803       (cond ((eq gnus-agent-article-alist-save-format 1)
1804              (princ gnus-agent-article-alist (current-buffer)))
1805             ((eq gnus-agent-article-alist-save-format 2)
1806              (let ((compressed nil))
1807                (mapcar (lambda (pair)
1808                          (let* ((article-id (car pair))
1809                                 (day-of-download (cdr pair))
1810                                 (comp-list (assq day-of-download compressed)))
1811                            (if comp-list
1812                                (setcdr comp-list
1813                                        (cons article-id (cdr comp-list)))
1814                              (setq compressed
1815                                    (cons (list day-of-download article-id)
1816                                          compressed)))
1817                            nil)) gnus-agent-article-alist)
1818                (mapcar (lambda (comp-list)
1819                          (setcdr comp-list
1820                                  (gnus-compress-sequence
1821                                   (nreverse (cdr comp-list)))))
1822                        compressed)
1823                (princ compressed (current-buffer)))))
1824       (insert "\n")
1825       (princ gnus-agent-article-alist-save-format (current-buffer))
1826       (insert "\n"))))
1827
1828 (defun gnus-agent-article-name (article group)
1829   (expand-file-name article
1830                     (file-name-as-directory
1831                      (gnus-agent-group-pathname group))))
1832
1833 (defun gnus-agent-batch-confirmation (msg)
1834   "Show error message and return t."
1835   (gnus-message 1 msg)
1836   t)
1837
1838 ;;;###autoload
1839 (defun gnus-agent-batch-fetch ()
1840   "Start Gnus and fetch session."
1841   (interactive)
1842   (gnus)
1843   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1844     (gnus-agent-fetch-session))
1845   (gnus-group-exit))
1846
1847 (defun gnus-agent-fetch-session ()
1848   "Fetch all articles and headers that are eligible for fetching."
1849   (interactive)
1850   (unless gnus-agent-covered-methods
1851     (error "No servers are covered by the Gnus agent"))
1852   (unless gnus-plugged
1853     (error "Can't fetch articles while Gnus is unplugged"))
1854   (let ((methods (gnus-agent-covered-methods))
1855         groups group gnus-command-method)
1856     (save-excursion
1857       (while methods
1858         (setq gnus-command-method (car methods))
1859         (when (and (or (gnus-server-opened gnus-command-method)
1860                        (gnus-open-server gnus-command-method))
1861                    (gnus-online gnus-command-method))
1862           (setq groups (gnus-groups-from-server (car methods)))
1863           (gnus-agent-with-fetch
1864             (while (setq group (pop groups))
1865               (when (<= (gnus-group-level group)
1866                         gnus-agent-handle-level)
1867                 (if (or debug-on-error debug-on-quit)
1868                     (gnus-agent-fetch-group-1
1869                      group gnus-command-method)
1870                   (condition-case err
1871                       (gnus-agent-fetch-group-1
1872                        group gnus-command-method)
1873                     (error
1874                      (unless (funcall gnus-agent-confirmation-function
1875                                       (format "Error %s.  Continue? "
1876                                               (error-message-string err)))
1877                        (error "Cannot fetch articles into the Gnus agent")))
1878                     (quit
1879                      (unless (funcall gnus-agent-confirmation-function
1880                                       (format
1881                                        "Quit fetching session %s.  Continue? "
1882                                        (error-message-string err)))
1883                        (signal 'quit
1884                                "Cannot fetch articles into the Gnus agent")))))))))
1885         (setq methods (cdr methods)))
1886       (gnus-run-hooks 'gnus-agent-fetched-hook)
1887       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1888
1889 (defun gnus-agent-fetch-group-1 (group method)
1890   "Fetch GROUP."
1891   (let ((gnus-command-method method)
1892         (gnus-newsgroup-name group)
1893         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1894         (gnus-newsgroup-headers gnus-newsgroup-headers)
1895         (gnus-newsgroup-scored gnus-newsgroup-scored)
1896         (gnus-use-cache gnus-use-cache)
1897         (gnus-summary-expunge-below gnus-summary-expunge-below)
1898         (gnus-summary-mark-below gnus-summary-mark-below)
1899         (gnus-orphan-score gnus-orphan-score)
1900         ;; Maybe some other gnus-summary local variables should also
1901         ;; be put here.
1902
1903         gnus-headers
1904         gnus-score
1905         articles arts
1906         category predicate info marks score-param
1907         )
1908     (unless (gnus-check-group group)
1909       (error "Can't open server for %s" group))
1910
1911     ;; Fetch headers.
1912     (when (or gnus-newsgroup-active
1913               (gnus-active group)
1914               (gnus-activate-group group))
1915       (let ((marked-articles gnus-newsgroup-downloadable))
1916         ;; Identify the articles marked for download
1917         (unless gnus-newsgroup-active
1918           ;; The variable gnus-newsgroup-active was selected as I need
1919           ;; a gnus-summary local variable that is NOT bound to any
1920           ;; value (its global value should default to nil).
1921           (dolist (mark gnus-agent-download-marks)
1922             (let ((arts (cdr (assq mark (gnus-info-marks
1923                                          (setq info (gnus-get-info group)))))))
1924               (when arts
1925                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1926                                              marked-articles))
1927                 ))))
1928         (setq marked-articles (sort marked-articles '<))
1929
1930         ;; Fetch any new articles from the server
1931         (setq articles (gnus-agent-fetch-headers group))
1932
1933         ;; Merge new articles with marked
1934         (setq articles (sort (append marked-articles articles) '<))
1935
1936         (when articles
1937           ;; Parse them and see which articles we want to fetch.
1938           (setq gnus-newsgroup-dependencies
1939                 (or gnus-newsgroup-dependencies
1940                     (make-vector (length articles) 0)))
1941           (setq gnus-newsgroup-headers
1942                 (or gnus-newsgroup-headers
1943                     (gnus-get-newsgroup-headers-xover articles nil nil
1944                                                       group)))
1945           ;; `gnus-agent-overview-buffer' may be killed for
1946           ;; timeout reason.  If so, recreate it.
1947           (gnus-agent-create-buffer)
1948
1949           ;; Figure out how to select articles in this group
1950           (setq category (gnus-group-category group))
1951
1952           (setq predicate
1953                 (gnus-get-predicate
1954                  (gnus-agent-find-parameter group 'agent-predicate)))
1955
1956           ;; If the selection predicate requires scoring, score each header
1957           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1958             (let ((score-param
1959                    (gnus-agent-find-parameter group 'agent-score-file)))
1960               ;; Translate score-param into real one
1961               (cond
1962                ((not score-param))
1963                ((eq score-param 'file)
1964                 (setq score-param (gnus-all-score-files group)))
1965                ((stringp (car score-param)))
1966                (t
1967                 (setq score-param (list (list score-param)))))
1968               (when score-param
1969                 (gnus-score-headers score-param))))
1970
1971           (unless (and (eq predicate 'gnus-agent-false)
1972                        (not marked-articles))
1973             (let ((arts (list nil)))
1974               (let ((arts-tail arts)
1975                     (alist (gnus-agent-load-alist group))
1976                     (marked-articles marked-articles)
1977                     (gnus-newsgroup-headers gnus-newsgroup-headers))
1978                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
1979                   (let ((num (mail-header-number gnus-headers)))
1980                     ;; Determine if this article is already in the cache
1981                     (while (and alist
1982                                 (> num (caar alist)))
1983                       (setq alist (cdr alist)))
1984
1985                     (unless (and (eq num (caar alist))
1986                                  (cdar alist))
1987
1988                       ;; Determine if this article was marked for download.
1989                       (while (and marked-articles
1990                                   (> num (car marked-articles)))
1991                         (setq marked-articles
1992                               (cdr marked-articles)))
1993
1994                       ;; When this article is marked, or selected by the
1995                       ;; predicate, add it to the download list
1996                       (when (or (eq num (car marked-articles))
1997                                 (let ((gnus-score
1998                                        (or (cdr
1999                                             (assq num gnus-newsgroup-scored))
2000                                            gnus-summary-default-score))
2001                                       (gnus-agent-long-article
2002                                        (gnus-agent-find-parameter
2003                                         group 'agent-long-article))
2004                                       (gnus-agent-short-article
2005                                        (gnus-agent-find-parameter
2006                                         group 'agent-short-article))
2007                                       (gnus-agent-low-score
2008                                        (gnus-agent-find-parameter
2009                                         group 'agent-low-score))
2010                                       (gnus-agent-high-score
2011                                        (gnus-agent-find-parameter
2012                                         group 'agent-high-score))
2013                                       (gnus-agent-expire-days
2014                                        (gnus-agent-find-parameter
2015                                         group 'agent-days-until-old)))
2016                                   (funcall predicate)))
2017                         (gnus-agent-append-to-list arts-tail num))))))
2018
2019               (let (fetched-articles)
2020                 ;; Fetch all selected articles
2021                 (setq gnus-newsgroup-undownloaded
2022                       (gnus-sorted-ndifference
2023                        gnus-newsgroup-undownloaded
2024                        (setq fetched-articles
2025                              (if (cdr arts)
2026                                  (gnus-agent-fetch-articles group (cdr arts))
2027                                nil))))
2028
2029                 (let ((unfetched-articles
2030                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2031                   (if gnus-newsgroup-active
2032                       ;; Update the summary buffer
2033                       (progn
2034                         (dolist (article marked-articles)
2035                           (gnus-summary-set-agent-mark article t))
2036                         (dolist (article fetched-articles)
2037                           (if gnus-agent-mark-unread-after-downloaded
2038                               (gnus-summary-mark-article
2039                                article gnus-unread-mark))
2040                           (when (gnus-summary-goto-subject article nil t)
2041                             (gnus-summary-update-download-mark article)))
2042                         (dolist (article unfetched-articles)
2043                           (gnus-summary-mark-article
2044                            article gnus-canceled-mark)))
2045
2046                     ;; Update the group buffer.
2047
2048                     ;; When some, or all, of the marked articles came
2049                     ;; from the download mark.  Remove that mark.  I
2050                     ;; didn't do this earlier as I only want to remove
2051                     ;; the marks after the fetch is completed.
2052
2053                     (dolist (mark gnus-agent-download-marks)
2054                       (when (eq mark 'download)
2055                         (let ((marked-arts
2056                                (assq mark (gnus-info-marks
2057                                            (setq info (gnus-get-info group))))))
2058                           (when (cdr marked-arts)
2059                             (setq marks
2060                                   (delq marked-arts (gnus-info-marks info)))
2061                             (gnus-info-set-marks info marks)))))
2062                     (let ((read (gnus-info-read
2063                                  (or info (setq info (gnus-get-info group))))))
2064                       (gnus-info-set-read
2065                        info (gnus-add-to-range read unfetched-articles)))
2066
2067                     (gnus-group-update-group group t)
2068                     (sit-for 0)
2069
2070                     (gnus-dribble-enter
2071                      (concat "(gnus-group-set-info '"
2072                              (gnus-prin1-to-string info)
2073                              ")"))))))))))))
2074
2075 ;;;
2076 ;;; Agent Category Mode
2077 ;;;
2078
2079 (defvar gnus-category-mode-hook nil
2080   "Hook run in `gnus-category-mode' buffers.")
2081
2082 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2083   "Format of category lines.
2084
2085 Valid specifiers include:
2086 %c  Topic name (string)
2087 %g  The number of groups in the topic (integer)
2088
2089 General format specifiers can also be used.  See Info node
2090 `(gnus)Formatting Variables'.")
2091
2092 (defvar gnus-category-mode-line-format "Gnus: %%b"
2093   "The format specification for the category mode line.")
2094
2095 (defvar gnus-agent-predicate 'false
2096   "The selection predicate used when no other source is available.")
2097
2098 (defvar gnus-agent-short-article 100
2099   "Articles that have fewer lines than this are short.")
2100
2101 (defvar gnus-agent-long-article 200
2102   "Articles that have more lines than this are long.")
2103
2104 (defvar gnus-agent-low-score 0
2105   "Articles that have a score lower than this have a low score.")
2106
2107 (defvar gnus-agent-high-score 0
2108   "Articles that have a score higher than this have a high score.")
2109
2110
2111 ;;; Internal variables.
2112
2113 (defvar gnus-category-buffer "*Agent Category*")
2114
2115 (defvar gnus-category-line-format-alist
2116   `((?c gnus-tmp-name ?s)
2117     (?g gnus-tmp-groups ?d)))
2118
2119 (defvar gnus-category-mode-line-format-alist
2120   `((?u user-defined ?s)))
2121
2122 (defvar gnus-category-line-format-spec nil)
2123 (defvar gnus-category-mode-line-format-spec nil)
2124
2125 (defvar gnus-category-mode-map nil)
2126 (put 'gnus-category-mode 'mode-class 'special)
2127
2128 (unless gnus-category-mode-map
2129   (setq gnus-category-mode-map (make-sparse-keymap))
2130   (suppress-keymap gnus-category-mode-map)
2131
2132   (gnus-define-keys gnus-category-mode-map
2133     "q" gnus-category-exit
2134     "k" gnus-category-kill
2135     "c" gnus-category-copy
2136     "a" gnus-category-add
2137     "e" gnus-agent-customize-category
2138     "p" gnus-category-edit-predicate
2139     "g" gnus-category-edit-groups
2140     "s" gnus-category-edit-score
2141     "l" gnus-category-list
2142
2143     "\C-c\C-i" gnus-info-find-node
2144     "\C-c\C-b" gnus-bug))
2145
2146 (defvar gnus-category-menu-hook nil
2147   "*Hook run after the creation of the menu.")
2148
2149 (defun gnus-category-make-menu-bar ()
2150   (gnus-turn-off-edit-menu 'category)
2151   (unless (boundp 'gnus-category-menu)
2152     (easy-menu-define
2153      gnus-category-menu gnus-category-mode-map ""
2154      '("Categories"
2155        ["Add" gnus-category-add t]
2156        ["Kill" gnus-category-kill t]
2157        ["Copy" gnus-category-copy t]
2158        ["Edit category" gnus-agent-customize-category t]
2159        ["Edit predicate" gnus-category-edit-predicate t]
2160        ["Edit score" gnus-category-edit-score t]
2161        ["Edit groups" gnus-category-edit-groups t]
2162        ["Exit" gnus-category-exit t]))
2163
2164     (gnus-run-hooks 'gnus-category-menu-hook)))
2165
2166 (defun gnus-category-mode ()
2167   "Major mode for listing and editing agent categories.
2168
2169 All normal editing commands are switched off.
2170 \\<gnus-category-mode-map>
2171 For more in-depth information on this mode, read the manual
2172 \(`\\[gnus-info-find-node]').
2173
2174 The following commands are available:
2175
2176 \\{gnus-category-mode-map}"
2177   (interactive)
2178   (when (gnus-visual-p 'category-menu 'menu)
2179     (gnus-category-make-menu-bar))
2180   (kill-all-local-variables)
2181   (gnus-simplify-mode-line)
2182   (setq major-mode 'gnus-category-mode)
2183   (setq mode-name "Category")
2184   (gnus-set-default-directory)
2185   (setq mode-line-process nil)
2186   (use-local-map gnus-category-mode-map)
2187   (buffer-disable-undo)
2188   (setq truncate-lines t)
2189   (setq buffer-read-only t)
2190   (gnus-run-hooks 'gnus-category-mode-hook))
2191
2192 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2193
2194 (defun gnus-category-insert-line (category)
2195   (let* ((gnus-tmp-name (format "%s" (car category)))
2196          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2197     (beginning-of-line)
2198     (gnus-add-text-properties
2199      (point)
2200      (prog1 (1+ (point))
2201        ;; Insert the text.
2202        (eval gnus-category-line-format-spec))
2203      (list 'gnus-category gnus-tmp-name))))
2204
2205 (defun gnus-enter-category-buffer ()
2206   "Go to the Category buffer."
2207   (interactive)
2208   (gnus-category-setup-buffer)
2209   (gnus-configure-windows 'category)
2210   (gnus-category-prepare))
2211
2212 (defun gnus-category-setup-buffer ()
2213   (unless (get-buffer gnus-category-buffer)
2214     (save-excursion
2215       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2216       (gnus-category-mode))))
2217
2218 (defun gnus-category-prepare ()
2219   (gnus-set-format 'category-mode)
2220   (gnus-set-format 'category t)
2221   (let ((alist gnus-category-alist)
2222         (buffer-read-only nil))
2223     (erase-buffer)
2224     (while alist
2225       (gnus-category-insert-line (pop alist)))
2226     (goto-char (point-min))
2227     (gnus-category-position-point)))
2228
2229 (defun gnus-category-name ()
2230   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
2231       (error "No category on the current line")))
2232
2233 (defun gnus-category-read ()
2234   "Read the category alist."
2235   (setq gnus-category-alist
2236         (or
2237          (with-temp-buffer
2238            (ignore-errors
2239             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2240             (goto-char (point-min))
2241             ;; This code isn't temp, it will be needed so long as
2242             ;; anyone may be migrating from an older version.
2243
2244             ;; Once we're certain that people will not revert to an
2245             ;; earlier version, we can take out the old-list code in
2246             ;; gnus-category-write.
2247             (let* ((old-list (read (current-buffer)))
2248                    (new-list (ignore-errors (read (current-buffer)))))
2249               (if new-list
2250                   new-list
2251                 ;; Convert from a positional list to an alist.
2252                 (mapcar
2253                  (lambda (c)
2254                    (setcdr c
2255                            (delq nil
2256                                  (gnus-mapcar
2257                                   (lambda (valu symb)
2258                                     (if valu
2259                                         (cons symb valu)))
2260                                   (cdr c)
2261                                   '(agent-predicate agent-score-file agent-groups))))
2262                    c)
2263                  old-list)))))
2264          (list (gnus-agent-cat-make 'default 'short)))))
2265
2266 (defun gnus-category-write ()
2267   "Write the category alist."
2268   (setq gnus-category-predicate-cache nil
2269         gnus-category-group-cache nil)
2270   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2271   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2272     ;; This prin1 is temporary.  It exists so that people can revert
2273     ;; to an earlier version of gnus-agent.
2274     (prin1 (mapcar (lambda (c)
2275               (list (car c)
2276                     (cdr (assoc 'agent-predicate c))
2277                     (cdr (assoc 'agent-score-file c))
2278                     (cdr (assoc 'agent-groups c))))
2279                    gnus-category-alist)
2280            (current-buffer))
2281     (newline)
2282     (prin1 gnus-category-alist (current-buffer))))
2283
2284 (defun gnus-category-edit-predicate (category)
2285   "Edit the predicate for CATEGORY."
2286   (interactive (list (gnus-category-name)))
2287   (let ((info (assq category gnus-category-alist)))
2288     (gnus-edit-form
2289      (gnus-agent-cat-predicate info)
2290      (format "Editing the select predicate for category %s" category)
2291      `(lambda (predicate)
2292         ;; Avoid run-time execution of setf form
2293         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2294         ;;       predicate)
2295         ;; use its expansion instead:
2296         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2297                                      'agent-predicate predicate)
2298
2299         (gnus-category-write)
2300         (gnus-category-list)))))
2301
2302 (defun gnus-category-edit-score (category)
2303   "Edit the score expression for CATEGORY."
2304   (interactive (list (gnus-category-name)))
2305   (let ((info (assq category gnus-category-alist)))
2306     (gnus-edit-form
2307      (gnus-agent-cat-score-file info)
2308      (format "Editing the score expression for category %s" category)
2309      `(lambda (score-file)
2310         ;; Avoid run-time execution of setf form
2311         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2312         ;;       score-file)
2313         ;; use its expansion instead:
2314         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2315                                      'agent-score-file score-file)
2316
2317         (gnus-category-write)
2318         (gnus-category-list)))))
2319
2320 (defun gnus-category-edit-groups (category)
2321   "Edit the group list for CATEGORY."
2322   (interactive (list (gnus-category-name)))
2323   (let ((info (assq category gnus-category-alist)))
2324     (gnus-edit-form
2325      (gnus-agent-cat-groups info)
2326      (format "Editing the group list for category %s" category)
2327      `(lambda (groups)
2328         ;; Avoid run-time execution of setf form
2329         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2330         ;;       groups)
2331         ;; use its expansion instead:
2332         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2333                                    groups)
2334
2335         (gnus-category-write)
2336         (gnus-category-list)))))
2337
2338 (defun gnus-category-kill (category)
2339   "Kill the current category."
2340   (interactive (list (gnus-category-name)))
2341   (let ((info (assq category gnus-category-alist))
2342         (buffer-read-only nil))
2343     (gnus-delete-line)
2344     (setq gnus-category-alist (delq info gnus-category-alist))
2345     (gnus-category-write)))
2346
2347 (defun gnus-category-copy (category to)
2348   "Copy the current category."
2349   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2350   (let ((info (assq category gnus-category-alist)))
2351     (push (let ((newcat (gnus-copy-sequence info)))
2352             (setf (gnus-agent-cat-name newcat) to)
2353             (setf (gnus-agent-cat-groups newcat) nil)
2354             newcat)
2355           gnus-category-alist)
2356     (gnus-category-write)
2357     (gnus-category-list)))
2358
2359 (defun gnus-category-add (category)
2360   "Create a new category."
2361   (interactive "SCategory name: ")
2362   (when (assq category gnus-category-alist)
2363     (error "Category %s already exists" category))
2364   (push (gnus-agent-cat-make category)
2365         gnus-category-alist)
2366   (gnus-category-write)
2367   (gnus-category-list))
2368
2369 (defun gnus-category-list ()
2370   "List all categories."
2371   (interactive)
2372   (gnus-category-prepare))
2373
2374 (defun gnus-category-exit ()
2375   "Return to the group buffer."
2376   (interactive)
2377   (kill-buffer (current-buffer))
2378   (gnus-configure-windows 'group t))
2379
2380 ;; To avoid having 8-bit characters in the source file.
2381 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2382
2383 (defvar gnus-category-predicate-alist
2384   '((spam . gnus-agent-spam-p)
2385     (short . gnus-agent-short-p)
2386     (long . gnus-agent-long-p)
2387     (low . gnus-agent-low-scored-p)
2388     (high . gnus-agent-high-scored-p)
2389     (read . gnus-agent-read-p)
2390     (true . gnus-agent-true)
2391     (false . gnus-agent-false))
2392   "Mapping from short score predicate symbols to predicate functions.")
2393
2394 (defun gnus-agent-spam-p ()
2395   "Say whether an article is spam or not."
2396   (unless gnus-agent-spam-hashtb
2397     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2398   (if (not (equal (mail-header-references gnus-headers) ""))
2399       nil
2400     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2401       (prog1
2402           (gnus-gethash string gnus-agent-spam-hashtb)
2403         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2404
2405 (defun gnus-agent-short-p ()
2406   "Say whether an article is short or not."
2407   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2408
2409 (defun gnus-agent-long-p ()
2410   "Say whether an article is long or not."
2411   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2412
2413 (defun gnus-agent-low-scored-p ()
2414   "Say whether an article has a low score or not."
2415   (< gnus-score gnus-agent-low-score))
2416
2417 (defun gnus-agent-high-scored-p ()
2418   "Say whether an article has a high score or not."
2419   (> gnus-score gnus-agent-high-score))
2420
2421 (defun gnus-agent-read-p ()
2422   "Say whether an article is read or not."
2423   (gnus-member-of-range (mail-header-number gnus-headers)
2424                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2425
2426 (defun gnus-category-make-function (predicate)
2427   "Make a function from PREDICATE."
2428   (let ((func (gnus-category-make-function-1 predicate)))
2429     (if (and (= (length func) 1)
2430              (symbolp (car func)))
2431         (car func)
2432       (gnus-byte-compile `(lambda () ,func)))))
2433
2434 (defun gnus-agent-true ()
2435   "Return t."
2436   t)
2437
2438 (defun gnus-agent-false ()
2439   "Return nil."
2440   nil)
2441
2442 (defun gnus-category-make-function-1 (predicate)
2443   "Make a function from PREDICATE."
2444   (cond
2445    ;; Functions are just returned as is.
2446    ((or (symbolp predicate)
2447         (functionp predicate))
2448     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2449            predicate)))
2450    ;; More complex predicate.
2451    ((consp predicate)
2452     `(,(cond
2453         ((memq (car predicate) '(& and))
2454          'and)
2455         ((memq (car predicate) '(| or))
2456          'or)
2457         ((memq (car predicate) gnus-category-not)
2458          'not))
2459       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2460    (t
2461     (error "Unknown predicate type: %s" predicate))))
2462
2463 (defun gnus-get-predicate (predicate)
2464   "Return the function implementing PREDICATE."
2465   (or (cdr (assoc predicate gnus-category-predicate-cache))
2466       (let ((func (gnus-category-make-function predicate)))
2467         (setq gnus-category-predicate-cache
2468               (nconc gnus-category-predicate-cache
2469                      (list (cons predicate func))))
2470         func)))
2471
2472 (defun gnus-predicate-implies-unread (predicate)
2473   "Say whether PREDICATE implies unread articles only.
2474 It is okay to miss some cases, but there must be no false positives.
2475 That is, if this predicate returns true, then indeed the predicate must
2476 return only unread articles."
2477   (eq t (gnus-function-implies-unread-1 
2478          (gnus-category-make-function-1 predicate))))
2479
2480 (defun gnus-function-implies-unread-1 (function)
2481   "Recursively evaluate a predicate function to determine whether it can select
2482 any read articles.  Returns t if the function is known to never
2483 return read articles, nil when it is known to always return read
2484 articles, and t_nil when the function may return both read and unread
2485 articles."
2486   (let ((func (car function))
2487         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2488     (cond ((eq func 'and)
2489            (cond ((memq t args) ; if any argument returns only unread articles
2490                   ;; then that argument constrains the result to only unread articles.
2491                   t)
2492                  ((memq 't_nil args) ; if any argument is indeterminate
2493                   ;; then the result is indeterminate
2494                   't_nil)))
2495           ((eq func 'or)
2496            (cond ((memq nil args) ; if any argument returns read articles
2497                   ;; then that argument ensures that the results includes read articles.
2498                   nil)
2499                  ((memq 't_nil args) ; if any argument is indeterminate
2500                   ;; then that argument ensures that the results are indeterminate
2501                   't_nil)
2502                  (t ; if all arguments return only unread articles
2503                   ;; then the result returns only unread articles
2504                   t)))
2505           ((eq func 'not)
2506            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2507                   ; then the result is indeterminate
2508                   (car args))
2509                  (t ; otherwise
2510                   ; toggle the result to be the opposite of the argument
2511                   (not (car args)))))
2512           ((eq func 'gnus-agent-read-p)
2513            nil) ; The read predicate NEVER returns unread articles
2514           ((eq func 'gnus-agent-false)
2515            t) ; The false predicate returns t as the empty set excludes all read articles
2516           ((eq func 'gnus-agent-true)
2517            nil) ; The true predicate ALWAYS returns read articles
2518           ((catch 'found-match
2519              (let ((alist gnus-category-predicate-alist))
2520                (while alist
2521                  (if (eq func (cdar alist))
2522                      (throw 'found-match t)
2523                    (setq alist (cdr alist))))))
2524            't_nil) ; All other predicates return read and unread articles
2525           (t
2526            (error "Unknown predicate function: %s" function)))))
2527
2528 (defun gnus-group-category (group)
2529   "Return the category GROUP belongs to."
2530   (unless gnus-category-group-cache
2531     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2532     (let ((cs gnus-category-alist)
2533           groups cat)
2534       (while (setq cat (pop cs))
2535         (setq groups (gnus-agent-cat-groups cat))
2536         (while groups
2537           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2538   (or (gnus-gethash group gnus-category-group-cache)
2539       (assq 'default gnus-category-alist)))
2540
2541 (defun gnus-agent-expire-group (group &optional articles force)
2542   "Expire all old articles in GROUP.
2543 If you want to force expiring of certain articles, this function can
2544 take ARTICLES, and FORCE parameters as well.
2545
2546 The articles on which the expiration process runs are selected as follows:
2547   if ARTICLES is null, all read and unmarked articles.
2548   if ARTICLES is t, all articles.
2549   if ARTICLES is a list, just those articles.
2550 FORCE is equivalent to setting the expiration predicates to true."
2551   (interactive
2552    (list (let ((def (or (gnus-group-group-name)
2553                         gnus-newsgroup-name)))
2554            (let ((select (read-string (if def
2555                                           (concat "Group Name ("
2556                                                   def "): ")
2557                                         "Group Name: "))))
2558              (if (and (equal "" select)
2559                       def)
2560                  def
2561                select)))))
2562
2563   (if (not group)
2564       (gnus-agent-expire articles group force)
2565     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2566            ;; expiration statistics of this single group
2567           (gnus-agent-expire-stats (list 0 0 0.0)))
2568       (if (or (not (eq articles t))
2569               (yes-or-no-p
2570                (concat "Are you sure that you want to "
2571                        "expire all articles in " group ".")))
2572           (let ((gnus-command-method (gnus-find-method-for-group group))
2573                 (overview (gnus-get-buffer-create " *expire overview*"))
2574                 orig)
2575             (unwind-protect
2576                 (let ((active-file (gnus-agent-lib-file "active")))
2577                   (when (file-exists-p active-file)
2578                     (with-temp-buffer
2579                       (nnheader-insert-file-contents active-file)
2580                       (gnus-active-to-gnus-format
2581                        gnus-command-method
2582                        (setq orig (gnus-make-hashtable
2583                                    (count-lines (point-min) (point-max))))))
2584                     (save-excursion
2585                       (gnus-agent-expire-group-1
2586                        group overview (gnus-gethash-safe group orig)
2587                        articles force))
2588                     (gnus-agent-write-active active-file orig t)))
2589               (kill-buffer overview))))
2590       (gnus-message 4 (gnus-agent-expire-done-message)))))
2591
2592 (defun gnus-agent-expire-group-1 (group overview active articles force)
2593   ;; Internal function - requires caller to have set
2594   ;; gnus-command-method, initialized overview buffer, and to have
2595   ;; provided a non-nil active
2596
2597   (let ((dir (gnus-agent-group-pathname group)))
2598     (when (boundp 'gnus-agent-expire-current-dirs)
2599       (set 'gnus-agent-expire-current-dirs 
2600            (cons dir 
2601                  (symbol-value 'gnus-agent-expire-current-dirs))))
2602
2603     (if (and (not force)
2604              (eq 'DISABLE (gnus-agent-find-parameter group 
2605                                                      'agent-enable-expiration)))
2606         (gnus-message 5 "Expiry skipping over %s" group)
2607       (gnus-message 5 "Expiring articles in %s" group)
2608       (gnus-agent-load-alist group)
2609       (let* ((stats (if (boundp 'gnus-agent-expire-stats)
2610                         ;; Use the list provided by my caller
2611                         (symbol-value 'gnus-agent-expire-stats)
2612                       ;; otherwise use my own temporary list
2613                       (list 0 0 0.0)))
2614              (info (gnus-get-info group))
2615              (alist gnus-agent-article-alist)
2616              (day (- (time-to-days (current-time))
2617                      (gnus-agent-find-parameter group 'agent-days-until-old)))
2618              (specials (if (and alist
2619                                 (not force))
2620                            ;; This could be a bit of a problem.  I need to
2621                            ;; keep the last article to avoid refetching
2622                            ;; headers when using nntp in the backend.  At
2623                            ;; the same time, if someone uses a backend
2624                            ;; that supports article moving then I may have
2625                            ;; to remove the last article to complete the
2626                            ;; move.  Right now, I'm going to assume that
2627                            ;; FORCE overrides specials.
2628                            (list (caar (last alist)))))
2629              (unreads ;; Articles that are excluded from the
2630               ;; expiration process
2631               (cond (gnus-agent-expire-all
2632                      ;; All articles are marked read by global decree
2633                      nil)
2634                     ((eq articles t)
2635                      ;; All articles are marked read by function
2636                      ;; parameter
2637                      nil)
2638                     ((not articles)
2639                      ;; Unread articles are marked protected from
2640                      ;; expiration Don't call
2641                      ;; gnus-list-of-unread-articles as it returns
2642                      ;; articles that have not been fetched into the
2643                      ;; agent.
2644                      (ignore-errors
2645                        (gnus-agent-unread-articles group)))
2646                     (t
2647                      ;; All articles EXCEPT those named by the caller
2648                      ;; are protected from expiration
2649                      (gnus-sorted-difference
2650                       (gnus-uncompress-range
2651                        (cons (caar alist)
2652                              (caar (last alist))))
2653                       (sort articles '<)))))
2654              (marked ;; More articles that are excluded from the
2655               ;; expiration process
2656               (cond (gnus-agent-expire-all
2657                      ;; All articles are unmarked by global decree
2658                      nil)
2659                     ((eq articles t)
2660                      ;; All articles are unmarked by function
2661                      ;; parameter
2662                      nil)
2663                     (articles
2664                      ;; All articles may as well be unmarked as the
2665                      ;; unreads list already names the articles we are
2666                      ;; going to keep
2667                      nil)
2668                     (t
2669                      ;; Ticked and/or dormant articles are excluded
2670                      ;; from expiration
2671                      (nconc
2672                       (gnus-uncompress-range
2673                        (cdr (assq 'tick (gnus-info-marks info))))
2674                       (gnus-uncompress-range
2675                        (cdr (assq 'dormant
2676                                   (gnus-info-marks info))))))))
2677              (nov-file (concat dir ".overview"))
2678              (cnt 0)
2679              (completed -1)
2680              dlist
2681              type)
2682
2683         ;; The normal article alist contains elements that look like
2684         ;; (article# .  fetch_date) I need to combine other
2685         ;; information with this list.  For example, a flag indicating
2686         ;; that a particular article MUST BE KEPT.  To do this, I'm
2687         ;; going to transform the elements to look like (article#
2688         ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2689         ;; the process to generate the expired article alist.
2690
2691         ;; Convert the alist elements to (article# fetch_date nil
2692         ;; nil).
2693         (setq dlist (mapcar (lambda (e)
2694                               (list (car e) (cdr e) nil nil)) alist))
2695
2696         ;; Convert the keep lists to elements that look like (article#
2697         ;; nil keep_flag nil) then append it to the expanded dlist
2698         ;; These statements are sorted by ascending precidence of the
2699         ;; keep_flag.
2700         (setq dlist (nconc dlist
2701                            (mapcar (lambda (e)
2702                                      (list e nil 'unread  nil))
2703                                    unreads)))
2704         (setq dlist (nconc dlist
2705                            (mapcar (lambda (e)
2706                                      (list e nil 'marked  nil))
2707                                    marked)))
2708         (setq dlist (nconc dlist
2709                            (mapcar (lambda (e)
2710                                      (list e nil 'special nil))
2711                                    specials)))
2712
2713         (set-buffer overview)
2714         (erase-buffer)
2715         (buffer-disable-undo)
2716         (when (file-exists-p nov-file)
2717           (gnus-message 7 "gnus-agent-expire: Loading overview...")
2718           (nnheader-insert-file-contents nov-file)
2719           (goto-char (point-min))
2720
2721           (let (p)
2722             (while (< (setq p (point)) (point-max))
2723               (condition-case nil
2724                   ;; If I successfully read an integer (the plus zero
2725                   ;; ensures a numeric type), prepend a marker entry
2726                   ;; to the list
2727                   (push (list (+ 0 (read (current-buffer))) nil nil
2728                               (set-marker (make-marker) p))
2729                         dlist)
2730                 (error
2731                  (gnus-message 1 "gnus-agent-expire: read error \
2732 occurred when reading expression at %s in %s.  Skipping to next \
2733 line." (point) nov-file)))
2734               ;; Whether I succeeded, or failed, it doesn't matter.
2735               ;; Move to the next line then try again.
2736               (forward-line 1)))
2737
2738           (gnus-message
2739            7 "gnus-agent-expire: Loading overview... Done"))
2740         (set-buffer-modified-p nil)
2741
2742         ;; At this point, all of the information is in dlist.  The
2743         ;; only problem is that much of it is spread across multiple
2744         ;; entries.  Sort then MERGE!!
2745         (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2746         ;; If two entries have the same article-number then sort by
2747         ;; ascending keep_flag.
2748         (let ((special 0)
2749               (marked 1)
2750               (unread 2))
2751           (setq dlist
2752                 (sort dlist
2753                       (lambda (a b)
2754                         (cond ((< (nth 0 a) (nth 0 b))
2755                                t)
2756                               ((> (nth 0 a) (nth 0 b))
2757                                nil)
2758                               (t
2759                                (let ((a (or (symbol-value (nth 2 a))
2760                                             3))
2761                                      (b (or (symbol-value (nth 2 b))
2762                                             3)))
2763                                  (<= a b))))))))
2764         (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2765         (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2766         (let ((dlist dlist))
2767           (while (cdr dlist)            ; I'm not at the end-of-list
2768             (if (eq (caar dlist) (caadr dlist))
2769                 (let ((first (cdr (car dlist)))
2770                       (secnd (cdr (cadr dlist))))
2771                   (setcar first (or (car first)
2772                                     (car secnd))) ; fetch_date
2773                   (setq first (cdr first)
2774                         secnd (cdr secnd))
2775                   (setcar first (or (car first)
2776                                     (car secnd))) ; Keep_flag
2777                   (setq first (cdr first)
2778                         secnd (cdr secnd))
2779                   (setcar first (or (car first)
2780                                     (car secnd))) ; NOV_entry_marker
2781
2782                   (setcdr dlist (cddr dlist)))
2783               (setq dlist (cdr dlist)))))
2784         (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2785
2786         (let* ((len (float (length dlist)))
2787                (alist (list nil))
2788                (tail-alist alist))
2789           (while dlist
2790             (let ((new-completed (truncate (* 100.0
2791                                               (/ (setq cnt (1+ cnt))
2792                                                  len))))
2793                   message-log-max)
2794               (when (> new-completed completed)
2795                 (setq completed new-completed)
2796                 (gnus-message 7 "%3d%% completed..."  completed)))
2797             (let* ((entry          (car dlist))
2798                    (article-number (nth 0 entry))
2799                    (fetch-date     (nth 1 entry))
2800                    (keep           (nth 2 entry))
2801                    (marker         (nth 3 entry)))
2802
2803               (cond
2804                ;; Kept articles are unread, marked, or special.
2805                (keep
2806                 (gnus-agent-message 10
2807                                     "gnus-agent-expire: %s:%d: Kept %s article%s."
2808                                     group article-number keep (if fetch-date " and file" ""))
2809                 (when fetch-date
2810                   (unless (file-exists-p
2811                            (concat dir (number-to-string
2812                                         article-number)))
2813                     (setf (nth 1 entry) nil)
2814                     (gnus-agent-message 3 "gnus-agent-expire cleared \
2815 download flag on %s:%d as the cached article file is missing."
2816                                         group (caar dlist)))
2817                   (unless marker
2818                     (gnus-message 1 "gnus-agent-expire detected a \
2819 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2820                 (gnus-agent-append-to-list
2821                  tail-alist
2822                  (cons article-number fetch-date)))
2823
2824                ;; The following articles are READ, UNMARKED, and
2825                ;; ORDINARY.  See if they can be EXPIRED!!!
2826                ((setq type
2827                       (cond
2828                        ((not (integerp fetch-date))
2829                         'read) ;; never fetched article (may expire
2830                        ;; right now)
2831                        ((not (file-exists-p
2832                               (concat dir (number-to-string
2833                                            article-number))))
2834                         (setf (nth 1 entry) nil)
2835                         'externally-expired) ;; Can't find the cached
2836                        ;; article.  Handle case
2837                        ;; as though this article
2838                        ;; was never fetched.
2839
2840                        ;; We now have the arrival day, so we see
2841                        ;; whether it's old enough to be expired.
2842                        ((< fetch-date day)
2843                         'expired)
2844                        (force
2845                         'forced)))
2846
2847                 ;; I found some reason to expire this entry.
2848
2849                 (let ((actions nil))
2850                   (when (memq type '(forced expired))
2851                     (ignore-errors      ; Just being paranoid.
2852                       (let ((file-name (concat dir (number-to-string
2853                                                 article-number))))
2854                         (incf (nth 2 stats) (nth 7 (file-attributes file-name)))
2855                         (incf (nth 1 stats))
2856                         (delete-file file-name))
2857                       (push "expired cached article" actions))
2858                     (setf (nth 1 entry) nil)
2859                     )
2860
2861                   (when marker
2862                     (push "NOV entry removed" actions)
2863                     (goto-char marker)
2864
2865                     (incf (nth 0 stats))
2866
2867                     (let ((from (gnus-point-at-bol))
2868                           (to (progn (forward-line 1) (point))))
2869                       (incf (nth 2 stats) (- to from))
2870                       (delete-region from to)))
2871
2872                   ;; If considering all articles is set, I can only
2873                   ;; expire article IDs that are no longer in the
2874                   ;; active range (That is, articles that preceed the
2875                   ;; first article in the new alist).
2876                   (if (and gnus-agent-consider-all-articles
2877                            (>= article-number (car active)))
2878                       ;; I have to keep this ID in the alist
2879                       (gnus-agent-append-to-list
2880                        tail-alist (cons article-number fetch-date))
2881                     (push (format "Removed %s article number from \
2882 article alist" type) actions))
2883
2884                   (when actions
2885                     (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
2886                                         group article-number
2887                                         (mapconcat 'identity actions ", ")))))
2888                (t
2889                 (gnus-agent-message
2890                  10 "gnus-agent-expire: %s:%d: Article kept as \
2891 expiration tests failed." group article-number)
2892                 (gnus-agent-append-to-list
2893                  tail-alist (cons article-number fetch-date)))
2894                )
2895
2896               ;; Clean up markers as I want to recycle this buffer
2897               ;; over several groups.
2898               (when marker
2899                 (set-marker marker nil))
2900
2901               (setq dlist (cdr dlist))))
2902
2903           (setq alist (cdr alist))
2904
2905           (let ((inhibit-quit t))
2906             (unless (equal alist gnus-agent-article-alist)
2907               (setq gnus-agent-article-alist alist)
2908               (gnus-agent-save-alist group)
2909
2910               ;; The active list changed, set the agent's active range
2911               ;; to match the beginning of the list.
2912               (if alist
2913                   (setcar active (caar alist))))
2914
2915             (when (buffer-modified-p)
2916               (let ((coding-system-for-write
2917                      gnus-agent-file-coding-system))
2918                 (gnus-make-directory dir)
2919                 (write-region (point-min) (point-max) nov-file nil
2920                               'silent)
2921                 ;; clear the modified flag as that I'm not confused by
2922                 ;; its status on the next pass through this routine.
2923                 (set-buffer-modified-p nil)))
2924
2925             (when (eq articles t)
2926               (gnus-summary-update-info))))))))
2927
2928 (defun gnus-agent-expire (&optional articles group force)
2929   "Expire all old articles.
2930 If you want to force expiring of certain articles, this function can
2931 take ARTICLES, GROUP and FORCE parameters as well.
2932
2933 The articles on which the expiration process runs are selected as follows:
2934   if ARTICLES is null, all read and unmarked articles.
2935   if ARTICLES is t, all articles.
2936   if ARTICLES is a list, just those articles.
2937 Setting GROUP will limit expiration to that group.
2938 FORCE is equivalent to setting the expiration predicates to true."
2939   (interactive)
2940   
2941   (if group
2942       (gnus-agent-expire-group group articles force)
2943     (if (or (not (eq articles t))
2944             (yes-or-no-p "Are you sure that you want to expire all \
2945 articles in every agentized group."))
2946         (let ((methods (gnus-agent-covered-methods))
2947               ;; Bind gnus-agent-expire-current-dirs to enable tracking
2948               ;; of agent directories.
2949               (gnus-agent-expire-current-dirs nil)
2950               ;; Bind gnus-agent-expire-stats to enable tracking of
2951               ;; expiration statistics across all groups
2952               (gnus-agent-expire-stats (list 0 0 0.0))
2953               gnus-command-method overview orig)
2954           (setq overview (gnus-get-buffer-create " *expire overview*"))
2955           (unwind-protect
2956               (while (setq gnus-command-method (pop methods))
2957                 (let ((active-file (gnus-agent-lib-file "active")))
2958                   (when (file-exists-p active-file)
2959                     (with-temp-buffer
2960                       (nnheader-insert-file-contents active-file)
2961                       (gnus-active-to-gnus-format
2962                        gnus-command-method
2963                        (setq orig (gnus-make-hashtable
2964                                    (count-lines (point-min) (point-max))))))
2965                     (dolist (expiring-group (gnus-groups-from-server
2966                                              gnus-command-method))
2967                       (let* ((active
2968                               (gnus-gethash-safe expiring-group orig)))
2969                                         
2970                         (when active
2971                           (save-excursion
2972                             (gnus-agent-expire-group-1
2973                              expiring-group overview active articles force)))))
2974                     (gnus-agent-write-active active-file orig t))))
2975             (kill-buffer overview))
2976           (gnus-agent-expire-unagentized-dirs)
2977           (gnus-message 4 (gnus-agent-expire-done-message))))))
2978
2979 (defun gnus-agent-expire-done-message ()
2980   (if (and (> gnus-verbose 4)
2981            (boundp 'gnus-agent-expire-stats))
2982       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
2983              (size (nth 2 stats))
2984             (units '(B KB MB GB)))
2985         (while (and (> size 1024.0)
2986                     (cdr units))
2987           (setq size (/ size 1024.0)
2988                 units (cdr units)))
2989
2990         (format "Expiry recovered %d NOV entries, deleted %d files,\
2991  and freed %f %s." 
2992                 (nth 0 stats) 
2993                 (nth 1 stats) 
2994                 size (car units)))
2995     "Expiry...done"))
2996
2997 (defun gnus-agent-expire-unagentized-dirs ()
2998   (when (and gnus-agent-expire-unagentized-dirs
2999              (boundp 'gnus-agent-expire-current-dirs))
3000     (let* ((keep (gnus-make-hashtable))
3001            ;; Formally bind gnus-agent-expire-current-dirs so that the
3002            ;; compiler will not complain about free references.
3003            (gnus-agent-expire-current-dirs
3004             (symbol-value 'gnus-agent-expire-current-dirs))
3005            dir)
3006
3007       (gnus-sethash gnus-agent-directory t keep)
3008       (while gnus-agent-expire-current-dirs
3009         (setq dir (pop gnus-agent-expire-current-dirs))
3010         (when (and (stringp dir)
3011                    (file-directory-p dir))
3012           (while (not (gnus-gethash dir keep))
3013             (gnus-sethash dir t keep)
3014             (setq dir (file-name-directory (directory-file-name dir))))))
3015
3016       (let* (to-remove
3017              checker
3018              (checker
3019               (function
3020                (lambda (d)
3021                  "Given a directory, check it and its subdirectories for 
3022               membership in the keep hash.  If it isn't found, add 
3023               it to to-remove." 
3024                  (let ((files (directory-files d))
3025                        file)
3026                    (while (setq file (pop files))
3027                      (cond ((equal file ".") ; Ignore self
3028                             nil)
3029                            ((equal file "..") ; Ignore parent
3030                             nil)
3031                            ((equal file ".overview") 
3032                             ;; Directory must contain .overview to be
3033                             ;; agent's cache of a group.
3034                             (let ((d (file-name-as-directory d))
3035                                   r)
3036                               ;; Search ancestor's for last directory NOT
3037                               ;; found in keep hash.
3038                               (while (not (gnus-gethash
3039                                            (setq d (file-name-directory d)) keep))
3040                                 (setq r d
3041                                       d (directory-file-name d)))
3042                               ;; if ANY ancestor was NOT in keep hash and
3043                               ;; it it's already in to-remove, add it to
3044                               ;; to-remove.                          
3045                               (if (and r
3046                                        (not (member r to-remove)))
3047                                   (push r to-remove))))
3048                            ((file-directory-p (setq file (nnheader-concat d file)))
3049                             (funcall checker file)))))))))
3050         (funcall checker (expand-file-name gnus-agent-directory))
3051
3052         (when (and to-remove
3053                    (or gnus-expert-user
3054                        (gnus-y-or-n-p
3055                         "gnus-agent-expire has identified local directories that are\
3056  not currently required by any agentized group.  Do you wish to consider\
3057  deleting them?")))
3058           (while to-remove
3059             (let ((dir (pop to-remove)))
3060               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3061                   (let* (delete-recursive
3062                          (delete-recursive
3063                           (function
3064                            (lambda (f-or-d)
3065                              (ignore-errors
3066                                (if (file-directory-p f-or-d)
3067                                    (condition-case nil
3068                                        (delete-directory f-or-d)
3069                                      (file-error
3070                                       (mapcar (lambda (f)
3071                                                 (or (member f '("." ".."))
3072                                                     (funcall delete-recursive
3073                                                              (nnheader-concat
3074                                                               f-or-d f))))
3075                                               (directory-files f-or-d))
3076                                       (delete-directory f-or-d)))
3077                                  (delete-file f-or-d)))))))
3078                     (funcall delete-recursive dir))))))))))
3079
3080 ;;;###autoload
3081 (defun gnus-agent-batch ()
3082   "Start Gnus, send queue and fetch session."
3083   (interactive)
3084   (let ((init-file-user "")
3085         (gnus-always-read-dribble-file t))
3086     (gnus))
3087   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3088     (gnus-group-send-queue)
3089     (gnus-agent-fetch-session)))
3090
3091 (defun gnus-agent-unread-articles (group)
3092   (let* ((read (gnus-info-read (gnus-get-info group)))
3093          (known (gnus-agent-load-alist group))
3094          (unread (list nil))
3095          (tail-unread unread))
3096     (while (and known read)
3097       (let ((candidate (car (pop known))))
3098         (while (let* ((range (car read))
3099                       (min   (if (numberp range) range (car range)))
3100                       (max   (if (numberp range) range (cdr range))))
3101                  (cond ((or (not min)
3102                             (< candidate min))
3103                         (gnus-agent-append-to-list tail-unread candidate)
3104                         nil)
3105                        ((> candidate max)
3106                         (setq read (cdr read))
3107                         ;; return t so that I always loop one more
3108                         ;; time.  If I just iterated off the end of
3109                         ;; read, min will become nil and the current
3110                         ;; candidate will be added to the unread list.
3111                         t))))))
3112     (while known
3113       (gnus-agent-append-to-list tail-unread (car (pop known))))
3114     (cdr unread)))
3115
3116 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3117   "Restrict ARTICLES to numbers already fetched.
3118 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3119 that have already been fetched.
3120 If CACHED-HEADER is nil, articles are only excluded if the article itself
3121 has been fetched."
3122
3123   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3124   ;; 'car gnus-agent-article-alist))
3125
3126   ;; Functionally, I don't need to construct a temp list using mapcar.
3127
3128   (if (and (or gnus-agent-cache (not gnus-plugged))
3129            (gnus-agent-load-alist group))
3130     (let* ((ref gnus-agent-article-alist)
3131            (arts articles)
3132            (uncached (list nil))
3133            (tail-uncached uncached))
3134       (while (and ref arts)
3135         (let ((v1 (car arts))
3136               (v2 (caar ref)))
3137           (cond ((< v1 v2) ; v1 does not appear in the reference list
3138                  (gnus-agent-append-to-list tail-uncached v1)
3139                  (setq arts (cdr arts)))
3140                 ((= v1 v2)
3141                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3142                    (gnus-agent-append-to-list tail-uncached v1))
3143                  (setq arts (cdr arts))
3144                  (setq ref (cdr ref)))
3145                 (t ; reference article (v2) preceeds the list being filtered
3146                  (setq ref (cdr ref))))))
3147       (while arts
3148         (gnus-agent-append-to-list tail-uncached (pop arts)))
3149       (cdr uncached))
3150     ;; if gnus-agent-load-alist fails, no articles are cached.
3151     articles))
3152
3153 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3154   (save-excursion
3155     (gnus-agent-create-buffer)
3156     (let ((gnus-decode-encoded-word-function 'identity)
3157           (file (gnus-agent-article-name ".overview" group))
3158           cached-articles uncached-articles)
3159       (gnus-make-directory (nnheader-translate-file-chars
3160                             (file-name-directory file) t))
3161
3162       ;; Populate temp buffer with known headers
3163       (when (file-exists-p file)
3164         (with-current-buffer gnus-agent-overview-buffer
3165           (erase-buffer)
3166           (let ((nnheader-file-coding-system
3167                  gnus-agent-file-coding-system))
3168             (nnheader-insert-nov-file file (car articles)))))
3169
3170       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3171                                                                 t))
3172           (progn
3173             ;; Populate nntp-server-buffer with uncached headers
3174             (set-buffer nntp-server-buffer)
3175             (erase-buffer)
3176             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3177                                    (gnus-retrieve-headers
3178                                     uncached-articles group fetch-old))))
3179                    (nnvirtual-convert-headers))
3180                   ((eq 'nntp (car gnus-current-select-method))
3181                    ;; The author of gnus-get-newsgroup-headers-xover
3182                    ;; reports that the XOVER command is commonly
3183                    ;; unreliable. The problem is that recently
3184                    ;; posted articles may not be entered into the
3185                    ;; NOV database in time to respond to my XOVER
3186                    ;; query.
3187                    ;;
3188                    ;; I'm going to use his assumption that the NOV
3189                    ;; database is updated in order of ascending
3190                    ;; article ID.  Therefore, a response containing
3191                    ;; article ID N implies that all articles from 1
3192                    ;; to N-1 are up-to-date.  Therefore, missing
3193                    ;; articles in that range have expired.
3194
3195                    (set-buffer nntp-server-buffer)
3196                    (let* ((fetched-articles (list nil))
3197                           (tail-fetched-articles fetched-articles)
3198                           (min (cond ((numberp fetch-old)
3199                                       (max 1 (- (car articles) fetch-old)))
3200                                      (fetch-old
3201                                       1)
3202                                      (t
3203                                       (car articles))))
3204                           (max (car (last articles))))
3205
3206                      ;; Get the list of articles that were fetched
3207                      (goto-char (point-min))
3208                      (let ((pm (point-max)))
3209                        (while (< (point) pm)
3210                          (when (looking-at "[0-9]+\t")
3211                            (gnus-agent-append-to-list
3212                             tail-fetched-articles
3213                             (read (current-buffer))))
3214                          (forward-line 1)))
3215
3216                      ;; Clip this list to the headers that will
3217                      ;; actually be returned
3218                      (setq fetched-articles (gnus-list-range-intersection
3219                                              (cdr fetched-articles)
3220                                              (cons min max)))
3221
3222                      ;; Clip the uncached articles list to exclude
3223                      ;; IDs after the last FETCHED header.  The
3224                      ;; excluded IDs may be fetchable using HEAD.
3225                      (if (car tail-fetched-articles)
3226                          (setq uncached-articles
3227                                (gnus-list-range-intersection
3228                                 uncached-articles
3229                                 (cons (car uncached-articles)
3230                                       (car tail-fetched-articles)))))
3231
3232                      ;; Create the list of articles that were
3233                      ;; "successfully" fetched.  Success, in this
3234                      ;; case, means that the ID should not be
3235                      ;; fetched again.  In the case of an expired
3236                      ;; article, the header will not be fetched.
3237                      (setq uncached-articles
3238                            (gnus-sorted-nunion fetched-articles
3239                                                uncached-articles))
3240                      )))
3241
3242             ;; Erase the temp buffer
3243             (set-buffer gnus-agent-overview-buffer)
3244             (erase-buffer)
3245
3246             ;; Copy the nntp-server-buffer to the temp buffer
3247             (set-buffer nntp-server-buffer)
3248             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3249
3250             ;; Merge the temp buffer with the known headers (found on
3251             ;; disk in FILE) into the nntp-server-buffer
3252             (when (and uncached-articles (file-exists-p file))
3253               (gnus-agent-braid-nov group uncached-articles file))
3254
3255             ;; Save the new set of known headers to FILE
3256             (set-buffer nntp-server-buffer)
3257             (let ((coding-system-for-write
3258                    gnus-agent-file-coding-system))
3259               (gnus-agent-check-overview-buffer)
3260               (write-region (point-min) (point-max) file nil 'silent))
3261
3262             ;; Update the group's article alist to include the newly
3263             ;; fetched articles.
3264             (gnus-agent-load-alist group)
3265             (gnus-agent-save-alist group uncached-articles nil)
3266             )
3267
3268         ;; Copy the temp buffer to the nntp-server-buffer
3269         (set-buffer nntp-server-buffer)
3270         (erase-buffer)
3271         (insert-buffer-substring gnus-agent-overview-buffer)))
3272
3273     (if (and fetch-old
3274              (not (numberp fetch-old)))
3275         t                               ; Don't remove anything.
3276       (nnheader-nov-delete-outside-range
3277        (if fetch-old (max 1 (- (car articles) fetch-old))
3278          (car articles))
3279        (car (last articles)))
3280       t)
3281
3282     'nov))
3283
3284 (defun gnus-agent-request-article (article group)
3285   "Retrieve ARTICLE in GROUP from the agent cache."
3286   (when (and gnus-agent
3287              (or gnus-agent-cache
3288                  (not gnus-plugged))
3289              (numberp article))
3290     (let* ((gnus-command-method (gnus-find-method-for-group group))
3291            (file (gnus-agent-article-name (number-to-string article) group))
3292            (buffer-read-only nil))
3293       (when (and (file-exists-p file)
3294                  (> (nth 7 (file-attributes file)) 0))
3295         (erase-buffer)
3296         (gnus-kill-all-overlays)
3297         (let ((coding-system-for-read gnus-cache-coding-system))
3298           (insert-file-contents file))
3299         t))))
3300
3301 (defun gnus-agent-regenerate-group (group &optional reread)
3302   "Regenerate GROUP.
3303 If REREAD is t, all articles in the .overview are marked as unread.
3304 If REREAD is not nil, downloaded articles are marked as unread."
3305   (interactive
3306    (list (let ((def (or (gnus-group-group-name)
3307                         gnus-newsgroup-name)))
3308            (let ((select (read-string (if def
3309                                           (concat "Group Name ("
3310                                                   def "): ")
3311                                         "Group Name: "))))
3312              (if (and (equal "" select)
3313                       def)
3314                  def
3315                select)))
3316          (catch 'mark
3317            (while (let ((c (read-char-exclusive 
3318                             "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n)"
3319                             )))
3320                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3321                            (throw 'mark nil))
3322                           ((or (eq c ?a) (eq c ?A))
3323                            (throw 'mark t))
3324                           ((or (eq c ?d) (eq c ?D))
3325                            (throw 'mark 'some)))
3326                     (message "Ignoring unexpected input")
3327                     (sit-for 1)
3328                     t)))))
3329
3330   (when group
3331       (gnus-message 5 "Regenerating in %s" group)
3332       (let* ((gnus-command-method (or gnus-command-method
3333                                       (gnus-find-method-for-group group)))
3334              (file (gnus-agent-article-name ".overview" group))
3335              (dir (file-name-directory file))
3336              point
3337              (downloaded (if (file-exists-p dir)
3338                              (sort (mapcar (lambda (name) (string-to-int name))
3339                                            (directory-files dir nil "^[0-9]+$" t))
3340                                    '>)
3341                            (progn (gnus-make-directory dir) nil)))
3342              dl nov-arts
3343              alist header
3344              regenerated)
3345
3346         (mm-with-unibyte-buffer
3347           (if (file-exists-p file)
3348               (let ((nnheader-file-coding-system
3349                      gnus-agent-file-coding-system))
3350                 (nnheader-insert-file-contents file)))
3351           (set-buffer-modified-p nil)
3352
3353           ;; Load the article IDs found in the overview file.  As a
3354           ;; side-effect, validate the file contents.
3355           (let ((load t))
3356             (while load
3357               (setq load nil)
3358               (goto-char (point-min))
3359               (while (< (point) (point-max))
3360                 (cond ((and (looking-at "[0-9]+\t")
3361                             (<= (- (match-end 0) (match-beginning 0)) 9))
3362                        (push (read (current-buffer)) nov-arts)
3363                        (forward-line 1)
3364                        (let ((l1 (car nov-arts))
3365                              (l2 (cadr nov-arts)))
3366                          (cond ((not l2)
3367                                 nil)
3368                                ((< l1 l2)
3369                                 (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3370  entries are NOT in ascending order.")
3371                                 ;; Don't sort now as I haven't verified
3372                                 ;; that every line begins with a number
3373                                 (setq load t))
3374                                ((= l1 l2)
3375                                 (forward-line -1)
3376                                 (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3377  entries contained duplicate of article %s.      Duplicate deleted." l1)
3378                                 (gnus-delete-line)
3379                                 (setq nov-arts (cdr nov-arts))))))
3380                       (t
3381                        (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3382  entries contained line that did not begin with an article number.  Deleted\
3383  line.")
3384                        (gnus-delete-line))))
3385               (if load
3386                   (progn
3387                     (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3388  entries into ascending order.")
3389                     (sort-numeric-fields 1 (point-min) (point-max))
3390                     (setq nov-arts nil)))))
3391           (gnus-agent-check-overview-buffer)
3392
3393           ;; Construct a new article alist whose nodes match every header
3394           ;; in the .overview file.  As a side-effect, missing headers are
3395           ;; reconstructed from the downloaded article file.
3396           (while (or downloaded nov-arts)
3397             (cond ((and downloaded
3398                         (or (not nov-arts)
3399                             (> (car downloaded) (car nov-arts))))
3400                    ;; This entry is missing from the overview file
3401                    (gnus-message 3 "Regenerating NOV %s %d..." group
3402                                  (car downloaded))
3403                    (let ((file (concat dir (number-to-string (car downloaded)))))
3404                      (mm-with-unibyte-buffer
3405                        (nnheader-insert-file-contents file)
3406                        (nnheader-remove-body)
3407                        (setq header (nnheader-parse-naked-head)))
3408                      (mail-header-set-number header (car downloaded))
3409                      (if nov-arts
3410                          (let ((key (concat "^" (int-to-string (car nov-arts))
3411                                             "\t")))
3412                            (or (re-search-backward key nil t)
3413                                (re-search-forward key))
3414                            (forward-line 1))
3415                        (goto-char (point-min)))
3416                      (nnheader-insert-nov header))
3417                    (setq nov-arts (cons (car downloaded) nov-arts)))
3418                   ((eq (car downloaded) (car nov-arts))
3419                    ;; This entry in the overview has been downloaded
3420                    (push (cons (car downloaded)
3421                                (time-to-days
3422                                 (nth 5 (file-attributes
3423                                         (concat dir (number-to-string
3424                                                      (car downloaded))))))) alist)
3425                    (setq downloaded (cdr downloaded))
3426                    (setq nov-arts (cdr nov-arts)))
3427                   (t
3428                    ;; This entry in the overview has not been downloaded
3429                    (push (cons (car nov-arts) nil) alist)
3430                    (setq nov-arts (cdr nov-arts)))))
3431
3432           ;; When gnus-agent-consider-all-articles is set,
3433           ;; gnus-agent-regenerate-group should NOT remove article IDs from
3434           ;; the alist.  Those IDs serve as markers to indicate that an
3435           ;; attempt has been made to fetch that article's header.
3436
3437           ;; When gnus-agent-consider-all-articles is NOT set,
3438           ;; gnus-agent-regenerate-group can remove the article ID of every
3439           ;; article (with the exception of the last ID in the list - it's
3440           ;; special) that no longer appears in the overview.  In this
3441           ;; situtation, the last article ID in the list implies that it,
3442           ;; and every article ID preceeding it, have been fetched from the
3443           ;; server.
3444
3445           (if gnus-agent-consider-all-articles
3446               ;; Restore all article IDs that were not found in the overview file.
3447               (let* ((n (cons nil alist))
3448                      (merged n)
3449                      (o (gnus-agent-load-alist group)))
3450                 (while o
3451                   (let ((nID (caadr n))
3452                         (oID (caar o)))
3453                     (cond ((not nID)
3454                            (setq n (setcdr n (list (list oID))))
3455                            (setq o (cdr o)))
3456                           ((< oID nID)
3457                            (setcdr n (cons (list oID) (cdr n)))
3458                            (setq o (cdr o)))
3459                           ((= oID nID)
3460                            (setq o (cdr o))
3461                            (setq n (cdr n)))
3462                           (t
3463                            (setq n (cdr n))))))
3464                 (setq alist (cdr merged)))
3465             ;; Restore the last article ID if it is not already in the new alist
3466             (let ((n (last alist))
3467                   (o (last (gnus-agent-load-alist group))))
3468               (cond ((not o)
3469                      nil)
3470                     ((not n)
3471                      (push (cons (caar o) nil) alist))
3472                     ((< (caar n) (caar o))
3473                      (setcdr n (list (car o)))))))
3474
3475           (let ((inhibit-quit t))
3476             (if (setq regenerated (buffer-modified-p))
3477                 (let ((coding-system-for-write gnus-agent-file-coding-system))
3478                   (write-region (point-min) (point-max) file nil 'silent)))
3479
3480             (setq regenerated (or regenerated
3481                                   (and reread gnus-agent-article-alist)
3482                                   (not (equal alist gnus-agent-article-alist))))
3483
3484             (setq gnus-agent-article-alist alist)
3485
3486             (when regenerated
3487               (gnus-agent-save-alist group)
3488        
3489               ;; I have to alter the group's active range NOW as
3490               ;; gnus-make-ascending-articles-unread will use it to
3491               ;; recalculate the number of unread articles in the group
3492
3493               (let ((group (gnus-group-real-name group))
3494                     (group-active (gnus-active group)))
3495                 (when group-active
3496                   (let ((new-min (or (caar gnus-agent-article-alist)
3497                                      (car group-active)))
3498                         (new-max (or (caar (last gnus-agent-article-alist))
3499                                      (cdr group-active))))
3500
3501                     (when (< new-min (car group-active))
3502                       (setcar group-active new-min))
3503              
3504                     (when (> new-max (cdr group-active))
3505                       (setcdr group-active new-max))))))))
3506
3507         (when (and reread gnus-agent-article-alist)
3508           (gnus-make-ascending-articles-unread
3509            group
3510            (delq nil (mapcar (function (lambda (c)
3511                                          (cond ((eq reread t)
3512                                                 (car c))
3513                                                ((cdr c)
3514                                                 (car c)))))
3515                              gnus-agent-article-alist)))
3516
3517           (when (gnus-buffer-live-p gnus-group-buffer)
3518             (gnus-group-update-group group t)
3519             (sit-for 0)))
3520
3521         (gnus-message 5 nil)
3522         regenerated)))
3523
3524 ;;;###autoload
3525 (defun gnus-agent-regenerate (&optional clean reread)
3526   "Regenerate all agent covered files.
3527 If CLEAN, obsolete (ignore)."
3528   (interactive "P")
3529   (let (regenerated)
3530     (gnus-message 4 "Regenerating Gnus agent files...")
3531     (dolist (gnus-command-method (gnus-agent-covered-methods))
3532         (dolist (group (gnus-groups-from-server gnus-command-method))
3533           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3534                                 regenerated))))
3535     (gnus-message 4 "Regenerating Gnus agent files...done")
3536
3537     regenerated))
3538
3539 (defun gnus-agent-go-online (&optional force)
3540   "Switch servers into online status."
3541   (interactive (list t))
3542   (dolist (server gnus-opened-servers)
3543     (when (eq (nth 1 server) 'offline)
3544       (if (if (eq force 'ask)
3545               (gnus-y-or-n-p
3546                (format "Switch %s:%s into online status? "
3547                        (caar server) (cadar server)))
3548             force)
3549           (setcar (nthcdr 1 server) 'close)))))
3550
3551 (defun gnus-agent-toggle-group-plugged (group)
3552   "Toggle the status of the server of the current group."
3553   (interactive (list (gnus-group-group-name)))
3554   (let* ((method (gnus-find-method-for-group group))
3555          (status (cadr (assoc method gnus-opened-servers))))
3556     (if (eq status 'offline)
3557         (gnus-server-set-status method 'closed)
3558       (gnus-close-server method)
3559       (gnus-server-set-status method 'offline))
3560     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3561              (if (eq status 'offline) 'offline 'online)
3562              (if (eq status 'offline) 'online 'offline))))
3563
3564 (defun gnus-agent-group-covered-p (group)
3565   (gnus-agent-method-p (gnus-group-method group)))
3566
3567 (add-hook 'gnus-group-prepare-hook
3568           (lambda ()
3569             'gnus-agent-do-once
3570
3571             (when (listp gnus-agent-expire-days)
3572               (beep)
3573               (beep)
3574               (gnus-message 1 "WARNING: gnus-agent-expire-days no longer\
3575  supports being set to a list.")(sleep-for 3)
3576               (gnus-message 1 "Change your configuration to set it to an\
3577  integer.")(sleep-for 3)
3578               (gnus-message 1 "I am now setting group parameters on each\
3579  group to match the configuration that the list offered.")
3580
3581               (save-excursion
3582                 (let ((groups (gnus-group-listed-groups)))
3583                   (while groups
3584                     (let* ((group (pop groups))
3585                            (days gnus-agent-expire-days)
3586                            (day (catch 'found
3587                                   (while days
3588                                     (when (eq 0 (string-match
3589                                                  (caar days)
3590                                                  group))
3591                                       (throw 'found (cadar days)))
3592                                     (setq days (cdr days)))
3593                                   nil)))
3594                       (when day
3595                         (gnus-group-set-parameter group 'agent-days-until-old
3596                                                   day))))))
3597
3598               (let ((h gnus-group-prepare-hook))
3599                 (while h
3600                   (let ((func (pop h)))
3601                     (when (and (listp func)
3602                                (eq (cadr (caddr func)) 'gnus-agent-do-once))
3603                       (remove-hook 'gnus-group-prepare-hook func)
3604                       (setq h nil)))))
3605
3606               (gnus-message 1 "I have finished setting group parameters on\
3607  each group. You may now customize your groups and/or topics to control the\
3608  agent."))))
3609
3610 (provide 'gnus-agent)
3611
3612 ;;; gnus-agent.el ends here