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