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