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