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