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