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