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