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