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