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