66b10f57bef2635e81e78303ab52e91073b8bfc8
[gnus] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Gnus
2
3 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 ;; Boston, MA 02110-1301, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'gnus)
29 (require 'gnus-cache)
30 (require 'nnmail)
31 (require 'nnvirtual)
32 (require 'gnus-sum)
33 (require 'gnus-score)
34 (require 'gnus-srvr)
35 (require 'gnus-util)
36 (eval-when-compile
37   (if (featurep 'xemacs)
38       (require 'itimer)
39     (require 'timer))
40   (require 'cl))
41
42 (eval-and-compile
43   (autoload 'gnus-server-update-server "gnus-srvr")
44   (autoload 'gnus-agent-customize-category "gnus-cus")
45 )
46
47 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
48   "Where the Gnus agent will store its files."
49   :group 'gnus-agent
50   :type 'directory)
51
52 (defcustom gnus-agent-plugged-hook nil
53   "Hook run when plugging into the network."
54   :group 'gnus-agent
55   :type 'hook)
56
57 (defcustom gnus-agent-unplugged-hook nil
58   "Hook run when unplugging from the network."
59   :group 'gnus-agent
60   :type 'hook)
61
62 (defcustom gnus-agent-fetched-hook nil
63   "Hook run when finished fetching articles."
64   :version "22.1"
65   :group 'gnus-agent
66   :type 'hook)
67
68 (defcustom gnus-agent-handle-level gnus-level-subscribed
69   "Groups on levels higher than this variable will be ignored by the Agent."
70   :group 'gnus-agent
71   :type 'integer)
72
73 (defcustom gnus-agent-expire-days 7
74   "Read articles older than this will be expired.
75 If you wish to disable Agent expiring, see `gnus-agent-enable-expiration'."
76   :group 'gnus-agent
77   :type '(number :tag "days"))
78
79 (defcustom gnus-agent-expire-all nil
80   "If non-nil, also expire unread, ticked and dormant articles.
81 If nil, only read articles will be expired."
82   :group 'gnus-agent
83   :type 'boolean)
84
85 (defcustom gnus-agent-group-mode-hook nil
86   "Hook run in Agent group minor modes."
87   :group 'gnus-agent
88   :type 'hook)
89
90 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
91 (when (featurep 'xemacs)
92   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
93
94 (defcustom gnus-agent-summary-mode-hook nil
95   "Hook run in Agent summary minor modes."
96   :group 'gnus-agent
97   :type 'hook)
98
99 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
100 (when (featurep 'xemacs)
101   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
102
103 (defcustom gnus-agent-server-mode-hook nil
104   "Hook run in Agent summary minor modes."
105   :group 'gnus-agent
106   :type 'hook)
107
108 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
109 (when (featurep 'xemacs)
110   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
111
112 (defcustom gnus-agent-confirmation-function 'y-or-n-p
113   "Function to confirm when error happens."
114   :version "21.1"
115   :group 'gnus-agent
116   :type 'function)
117
118 (defcustom gnus-agent-synchronize-flags nil
119   "Indicate if flags are synchronized when you plug in.
120 If this is `ask' the hook will query the user."
121   ;; If the default switches to something else than nil, then the function
122   ;; should be fixed not be exceedingly slow.  See 2005-09-20 ChangeLog entry.
123   :version "21.1"
124   :type '(choice (const :tag "Always" t)
125                  (const :tag "Never" nil)
126                  (const :tag "Ask" ask))
127   :group 'gnus-agent)
128
129 (defcustom gnus-agent-go-online 'ask
130   "Indicate if offline servers go online when you plug in.
131 If this is `ask' the hook will query the user."
132   :version "21.3"
133   :type '(choice (const :tag "Always" t)
134                  (const :tag "Never" nil)
135                  (const :tag "Ask" ask))
136   :group 'gnus-agent)
137
138 (defcustom gnus-agent-mark-unread-after-downloaded t
139   "Indicate whether to mark articles unread after downloaded."
140   :version "21.1"
141   :type 'boolean
142   :group 'gnus-agent)
143
144 (defcustom gnus-agent-download-marks '(download)
145   "Marks for downloading."
146   :version "21.1"
147   :type '(repeat (symbol :tag "Mark"))
148   :group 'gnus-agent)
149
150 (defcustom gnus-agent-consider-all-articles nil
151   "When non-nil, the agent will let the agent predicate decide
152 whether articles need to be downloaded or not, for all articles.  When
153 nil, the default, the agent will only let the predicate decide
154 whether unread articles are downloaded or not.  If you enable this,
155 groups with large active ranges may open slower and you may also want
156 to look into the agent expiry settings to block the expiration of
157 read articles as they would just be downloaded again."
158   :version "22.1"
159   :type 'boolean
160   :group 'gnus-agent)
161
162 (defcustom gnus-agent-max-fetch-size 10000000 ;; 10 Mb
163   "Chunk size for `gnus-agent-fetch-session'.
164 The function will split its article fetches into chunks smaller than
165 this limit."
166   :version "22.1"
167   :group 'gnus-agent
168   :type 'integer)
169
170 (defcustom gnus-agent-enable-expiration 'ENABLE
171   "The default expiration state for each group.
172 When set to ENABLE, the default, `gnus-agent-expire' will expire old
173 contents from a group's local storage.  This value may be overridden
174 to disable expiration in specific categories, topics, and groups.  Of
175 course, you could change gnus-agent-enable-expiration to DISABLE then
176 enable expiration per categories, topics, and groups."
177   :version "22.1"
178   :group 'gnus-agent
179   :type '(radio (const :format "Enable " ENABLE)
180                 (const :format "Disable " DISABLE)))
181
182 (defcustom gnus-agent-expire-unagentized-dirs t
183   "*Whether expiration should expire in unagentized directories.
184 Have gnus-agent-expire scan the directories under
185 \(gnus-agent-directory) for groups that are no longer agentized.
186 When found, offer to remove them."
187   :version "22.1"
188   :type 'boolean
189   :group 'gnus-agent)
190
191 (defcustom gnus-agent-auto-agentize-methods '(nntp nnimap)
192   "Initially, all servers from these methods are agentized.
193 The user may remove or add servers using the Server buffer.
194 See Info node `(gnus)Server Buffer'."
195   :version "22.1"
196   :type '(repeat symbol)
197   :group 'gnus-agent)
198
199 (defcustom gnus-agent-queue-mail t
200   "Whether and when outgoing mail should be queued by the agent.
201 When `always', always queue outgoing mail.  When nil, never
202 queue.  Otherwise, queue if and only if unplugged."
203   :version "22.1"
204   :group 'gnus-agent
205   :type '(radio (const :format "Always" always)
206                 (const :format "Never" nil)
207                 (const :format "When unplugged" t)))
208
209 (defcustom gnus-agent-prompt-send-queue nil
210   "If non-nil, `gnus-group-send-queue' will prompt if called when
211 unplugged."
212   :version "22.1"
213   :group 'gnus-agent
214   :type 'boolean)
215
216 (defcustom gnus-agent-article-alist-save-format 1
217   "Indicates whether to use compression(2), versus no
218 compression(1), when writing agentview files.  The compressed
219 files do save space but load times are 6-7 times higher.  A group
220 must be opened then closed for the agentview to be updated using
221 the new format."
222   ;; Wouldn't symbols instead numbers be nicer?  --rsteib
223   :version "22.1"
224   :group 'gnus-agent
225   :type '(radio (const :format "Compressed" 2)
226                 (const :format "Uncompressed" 1)))
227
228 ;;; Internal variables
229
230 (defvar gnus-agent-history-buffers nil)
231 (defvar gnus-agent-buffer-alist nil)
232 (defvar gnus-agent-article-alist nil
233   "An assoc list identifying the articles whose headers have been fetched.
234 If successfully fetched, these headers will be stored in the group's overview
235 file.  The key of each assoc pair is the article ID, the value of each assoc
236 pair is a flag indicating whether the identified article has been downloaded
237 \(gnus-agent-fetch-articles sets the value to the day of the download).
238 NOTES:
239 1) The last element of this list can not be expired as some
240    routines (for example, get-agent-fetch-headers) use the last
241    value to track which articles have had their headers retrieved.
242 2) The function `gnus-agent-regenerate' may destructively modify the value.")
243 (defvar gnus-agent-group-alist nil)
244 (defvar gnus-category-alist nil)
245 (defvar gnus-agent-current-history nil)
246 (defvar gnus-agent-overview-buffer nil)
247 (defvar gnus-category-predicate-cache nil)
248 (defvar gnus-category-group-cache nil)
249 (defvar gnus-agent-spam-hashtb nil)
250 (defvar gnus-agent-file-name nil)
251 (defvar gnus-agent-send-mail-function nil)
252 (defvar gnus-agent-file-coding-system 'raw-text)
253 (defvar gnus-agent-file-loading-cache nil)
254 (defvar gnus-agent-total-fetched-hashtb nil)
255 (defvar gnus-agent-inhibit-update-total-fetched-for nil)
256 (defvar gnus-agent-need-update-total-fetched-for nil)
257
258 ;; Dynamic variables
259 (defvar gnus-headers)
260 (defvar gnus-score)
261
262 ;;;
263 ;;; Setup
264 ;;;
265
266 (defun gnus-open-agent ()
267   (setq gnus-agent t)
268   (gnus-agent-read-servers)
269   (gnus-category-read)
270   (gnus-agent-create-buffer)
271   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
272   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
273   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
274
275 (defun gnus-agent-create-buffer ()
276   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
277       t
278     (setq gnus-agent-overview-buffer
279           (gnus-get-buffer-create " *Gnus agent overview*"))
280     (with-current-buffer gnus-agent-overview-buffer
281       (mm-enable-multibyte))
282     nil))
283
284 (gnus-add-shutdown 'gnus-close-agent 'gnus)
285
286 (defun gnus-close-agent ()
287   (setq gnus-category-predicate-cache nil
288         gnus-category-group-cache nil
289         gnus-agent-spam-hashtb nil)
290   (gnus-kill-buffer gnus-agent-overview-buffer))
291
292 ;;;
293 ;;; Utility functions
294 ;;;
295
296 (defmacro gnus-agent-with-refreshed-group (group &rest body)
297   "Performs the body then updates the group's line in the group
298 buffer.  Automatically blocks multiple updates due to recursion."
299 `(prog1 (let ((gnus-agent-inhibit-update-total-fetched-for t)) ,@body)
300      (when (and gnus-agent-need-update-total-fetched-for
301                 (not gnus-agent-inhibit-update-total-fetched-for))
302         (save-excursion
303           (set-buffer gnus-group-buffer)
304           (setq gnus-agent-need-update-total-fetched-for nil)
305           (gnus-group-update-group ,group t)))))
306
307 (defun gnus-agent-read-file (file)
308   "Load FILE and do a `read' there."
309   (with-temp-buffer
310     (ignore-errors
311       (nnheader-insert-file-contents file)
312       (goto-char (point-min))
313       (read (current-buffer)))))
314
315 (defsubst gnus-agent-method ()
316   (concat (symbol-name (car gnus-command-method)) "/"
317           (if (equal (cadr gnus-command-method) "")
318               "unnamed"
319             (cadr gnus-command-method))))
320
321 (defsubst gnus-agent-directory ()
322   "The name of the Gnus agent directory."
323   (nnheader-concat gnus-agent-directory
324                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
325
326 (defun gnus-agent-lib-file (file)
327   "The full name of the Gnus agent library FILE."
328   (expand-file-name file
329                     (file-name-as-directory
330                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
331
332 (defun gnus-agent-cat-set-property (category property value)
333   (if value
334       (setcdr (or (assq property category)
335               (let ((cell (cons property nil)))
336                     (setcdr category (cons cell (cdr category)))
337                     cell)) value)
338     (let ((category category))
339       (while (cond ((eq property (caadr category))
340                     (setcdr category (cddr category))
341                     nil)
342                    (t
343                     (setq category (cdr category)))))))
344   category)
345
346 (eval-when-compile
347   (defmacro gnus-agent-cat-defaccessor (name prop-name)
348     "Define accessor and setter methods for manipulating a list of the form
349 \(NAME (PROPERTY1 VALUE1) ... (PROPERTY_N VALUE_N)).
350 Given the call (gnus-agent-cat-defaccessor func PROPERTY1), the list may be
351 manipulated as follows:
352   (func LIST): Returns VALUE1
353   (setf (func LIST) NEW_VALUE1): Replaces VALUE1 with NEW_VALUE1."
354     `(progn (defmacro ,name (category)
355               (list (quote cdr) (list (quote assq)
356                                       (quote (quote ,prop-name)) category)))
357
358             (define-setf-method ,name (category)
359               (let* ((--category--temp-- (make-symbol "--category--"))
360                      (--value--temp-- (make-symbol "--value--")))
361                 (list (list --category--temp--) ; temporary-variables
362                       (list category)           ; value-forms
363                       (list --value--temp--)    ; store-variables
364                       (let* ((category --category--temp--) ; store-form
365                              (value --value--temp--))
366                         (list (quote gnus-agent-cat-set-property)
367                               category
368                               (quote (quote ,prop-name))
369                               value))
370                       (list (quote ,name) --category--temp--) ; access-form
371                       )))))
372   )
373
374 (defmacro gnus-agent-cat-name (category)
375   `(car ,category))
376
377 (gnus-agent-cat-defaccessor
378  gnus-agent-cat-days-until-old             agent-days-until-old)
379 (gnus-agent-cat-defaccessor
380  gnus-agent-cat-enable-expiration          agent-enable-expiration)
381 (gnus-agent-cat-defaccessor
382  gnus-agent-cat-groups                     agent-groups)
383 (gnus-agent-cat-defaccessor
384  gnus-agent-cat-high-score                 agent-high-score)
385 (gnus-agent-cat-defaccessor
386  gnus-agent-cat-length-when-long           agent-long-article)
387 (gnus-agent-cat-defaccessor
388  gnus-agent-cat-length-when-short          agent-short-article)
389 (gnus-agent-cat-defaccessor
390  gnus-agent-cat-low-score                  agent-low-score)
391 (gnus-agent-cat-defaccessor
392  gnus-agent-cat-predicate                  agent-predicate)
393 (gnus-agent-cat-defaccessor
394  gnus-agent-cat-score-file                 agent-score)
395 (gnus-agent-cat-defaccessor
396  gnus-agent-cat-enable-undownloaded-faces  agent-enable-undownloaded-faces)
397
398
399 ;; This form is equivalent to defsetf except that it calls make-symbol
400 ;; whereas defsetf calls gensym (Using gensym creates a run-time
401 ;; dependency on the CL library).
402
403 (eval-and-compile
404   (define-setf-method gnus-agent-cat-groups (category)
405     (let* ((--category--temp-- (make-symbol "--category--"))
406            (--groups--temp-- (make-symbol "--groups--")))
407       (list (list --category--temp--)
408             (list category)
409             (list --groups--temp--)
410             (let* ((category --category--temp--)
411                    (groups --groups--temp--))
412               (list (quote gnus-agent-set-cat-groups) category groups))
413             (list (quote gnus-agent-cat-groups) --category--temp--))))
414   )
415
416 (defun gnus-agent-set-cat-groups (category groups)
417   (unless (eq groups 'ignore)
418     (let ((new-g groups)
419           (old-g (gnus-agent-cat-groups category)))
420       (cond ((eq new-g old-g)
421              ;; gnus-agent-add-group is fiddling with the group
422              ;; list. Still, Im done.
423              nil
424              )
425             ((eq new-g (cdr old-g))
426              ;; gnus-agent-add-group is fiddling with the group list
427              (setcdr (or (assq 'agent-groups category)
428                          (let ((cell (cons 'agent-groups nil)))
429                            (setcdr category (cons cell (cdr category)))
430                            cell)) new-g))
431             (t
432              (let ((groups groups))
433                (while groups
434                  (let* ((group        (pop groups))
435                         (old-category (gnus-group-category group)))
436                    (if (eq category old-category)
437                        nil
438                      (setf (gnus-agent-cat-groups old-category)
439                            (delete group (gnus-agent-cat-groups
440                                           old-category))))))
441                ;; Purge cache as preceeding loop invalidated it.
442                (setq gnus-category-group-cache nil))
443
444              (setcdr (or (assq 'agent-groups category)
445                          (let ((cell (cons 'agent-groups nil)))
446                            (setcdr category (cons cell (cdr category)))
447                            cell)) groups))))))
448
449 (defsubst gnus-agent-cat-make (name &optional default-agent-predicate)
450   (list name `(agent-predicate . ,(or default-agent-predicate 'false))))
451
452 ;; Added to support XEmacs
453 (eval-and-compile
454   (unless (fboundp 'directory-files-and-attributes)
455     (defun directory-files-and-attributes (directory
456                                            &optional full match nosort)
457       (let (result)
458         (dolist (file (directory-files directory full match nosort))
459           (push (cons file (file-attributes file)) result))
460         (nreverse result)))))
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. Perform a brute-force
2127        ;; reconstruction of its contents.
2128        (let* (alist
2129               (file-attributes (directory-files-and-attributes 
2130                                 (gnus-agent-article-name ""
2131                                                          gnus-agent-read-agentview) nil "^[0-9]+$" t)))
2132          (while file-attributes
2133            (let* ((fa (pop file-attributes))
2134                   (artnum (string-to-number (nth 0 fa)))
2135                   (days (time-to-days (nth 5 fa))))
2136              (push (cons artnum days) alist)))
2137          alist)))))
2138
2139 (defun gnus-agent-save-alist (group &optional articles state)
2140   "Save the article-state alist for GROUP."
2141   (let* ((file-name-coding-system nnmail-pathname-coding-system)
2142          (prev (cons nil gnus-agent-article-alist))
2143          (all prev)
2144          print-level print-length item article)
2145     (while (setq article (pop articles))
2146       (while (and (cdr prev)
2147                   (< (caadr prev) article))
2148         (setq prev (cdr prev)))
2149       (cond
2150        ((not (cdr prev))
2151         (setcdr prev (list (cons article state))))
2152        ((> (caadr prev) article)
2153         (setcdr prev (cons (cons article state) (cdr prev))))
2154        ((= (caadr prev) article)
2155         (setcdr (cadr prev) state)))
2156       (setq prev (cdr prev)))
2157     (setq gnus-agent-article-alist (cdr all))
2158
2159     (gnus-agent-set-local group
2160                           (caar gnus-agent-article-alist)
2161                           (caar (last gnus-agent-article-alist)))
2162
2163     (gnus-make-directory (gnus-agent-article-name "" group))
2164     (with-temp-file (gnus-agent-article-name ".agentview" group)
2165       (cond ((eq gnus-agent-article-alist-save-format 1)
2166              (princ gnus-agent-article-alist (current-buffer)))
2167             ((eq gnus-agent-article-alist-save-format 2)
2168              (let ((compressed nil))
2169                (mapcar (lambda (pair)
2170                          (let* ((article-id (car pair))
2171                                 (day-of-download (cdr pair))
2172                                 (comp-list (assq day-of-download compressed)))
2173                            (if comp-list
2174                                (setcdr comp-list
2175                                        (cons article-id (cdr comp-list)))
2176                              (setq compressed
2177                                    (cons (list day-of-download article-id)
2178                                          compressed)))
2179                            nil)) gnus-agent-article-alist)
2180                (mapcar (lambda (comp-list)
2181                          (setcdr comp-list
2182                                  (gnus-compress-sequence
2183                                   (nreverse (cdr comp-list)))))
2184                        compressed)
2185                (princ compressed (current-buffer)))))
2186       (insert "\n")
2187       (princ gnus-agent-article-alist-save-format (current-buffer))
2188       (insert "\n"))
2189
2190     (gnus-agent-update-view-total-fetched-for group nil)))
2191
2192 (defvar gnus-agent-article-local nil)
2193 (defvar gnus-agent-file-loading-local nil)
2194
2195 (defun gnus-agent-load-local (&optional method)
2196   "Load the METHOD'S local file.  The local file contains min/max
2197 article counts for each of the method's subscribed groups."
2198   (let ((gnus-command-method (or method gnus-command-method)))
2199     (setq gnus-agent-article-local
2200           (gnus-cache-file-contents
2201            (gnus-agent-lib-file "local")
2202            'gnus-agent-file-loading-local
2203            'gnus-agent-read-and-cache-local))))
2204
2205 (defun gnus-agent-read-and-cache-local (file)
2206   "Load and read FILE then bind its contents to
2207 gnus-agent-article-local.  If that variable had `dirty' (also known as
2208 modified) original contents, they are first saved to their own file."
2209
2210   (if (and gnus-agent-article-local
2211            (symbol-value (intern "+dirty" gnus-agent-article-local)))
2212       (gnus-agent-save-local))
2213   (gnus-agent-read-local file))
2214
2215 (defun gnus-agent-read-local (file)
2216   "Load FILE and do a `read' there."
2217   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min)
2218                                                       (point-max))))
2219         (line 1))
2220     (with-temp-buffer
2221       (condition-case nil
2222           (let ((nnheader-file-coding-system gnus-agent-file-coding-system))
2223             (nnheader-insert-file-contents file))
2224         (file-error))
2225
2226       (goto-char (point-min))
2227       ;; Skip any comments at the beginning of the file (the only place where they may appear)
2228       (while (= (following-char) ?\;)
2229         (forward-line 1)
2230         (setq line (1+ line)))
2231
2232       (while (not (eobp))
2233         (condition-case err
2234             (let (group
2235                   min
2236                   max
2237                   (cur (current-buffer))
2238                   (obarray my-obarray))
2239               (setq group (read cur)
2240                     min (read cur)
2241                     max (read cur))
2242
2243               (when (stringp group)
2244                 (setq group (intern group my-obarray)))
2245
2246               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
2247               (set group (cons (+ 0 min) (+ 0 max))))
2248           (error
2249            (gnus-message 3 "Warning - invalid agent local: %s on line %d: %s"
2250                          file line (error-message-string err))))
2251         (forward-line 1)
2252         (setq line (1+ line))))
2253
2254     (set (intern "+dirty" my-obarray) nil)
2255     (set (intern "+method" my-obarray) gnus-command-method)
2256     my-obarray))
2257
2258 (defun gnus-agent-save-local (&optional force)
2259   "Save gnus-agent-article-local under it method's agent.lib directory."
2260   (let ((my-obarray gnus-agent-article-local))
2261     (when (and my-obarray
2262                (or force (symbol-value (intern "+dirty" my-obarray))))
2263       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2264              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
2265              (dest (gnus-agent-lib-file "local")))
2266         (gnus-make-directory (gnus-agent-lib-file ""))
2267
2268         (let ((buffer-file-coding-system gnus-agent-file-coding-system))
2269           (with-temp-file dest
2270             (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2271                   (file-name-coding-system nnmail-pathname-coding-system)
2272                   print-level print-length item article
2273                   (standard-output (current-buffer)))
2274               (mapatoms (lambda (symbol)
2275                           (cond ((not (boundp symbol))
2276                                  nil)
2277                                 ((member (symbol-name symbol) '("+dirty" "+method"))
2278                                  nil)
2279                                 (t
2280                                  (let ((range (symbol-value symbol)))
2281                                    (when range
2282                                      (prin1 symbol)
2283                                      (princ " ")
2284                                      (princ (car range))
2285                                      (princ " ")
2286                                      (princ (cdr range))
2287                                      (princ "\n"))))))
2288                         my-obarray))))))))
2289
2290 (defun gnus-agent-get-local (group &optional gmane method)
2291   (let* ((gmane (or gmane (gnus-group-real-name group)))
2292          (gnus-command-method (or method (gnus-find-method-for-group group)))
2293          (local (gnus-agent-load-local))
2294          (symb (intern gmane local))
2295          (minmax (and (boundp symb) (symbol-value symb))))
2296     (unless minmax
2297       ;; Bind these so that gnus-agent-load-alist doesn't change the
2298       ;; current alist (i.e. gnus-agent-article-alist)
2299       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2300              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2301              (alist (gnus-agent-load-alist group)))
2302         (when alist
2303           (setq minmax
2304                 (cons (caar alist)
2305                       (caar (last alist))))
2306           (gnus-agent-set-local group (car minmax) (cdr minmax)
2307                                 gmane gnus-command-method local))))
2308     minmax))
2309
2310 (defun gnus-agent-set-local (group min max &optional gmane method local)
2311   (let* ((gmane (or gmane (gnus-group-real-name group)))
2312          (gnus-command-method (or method (gnus-find-method-for-group group)))
2313          (local (or local (gnus-agent-load-local)))
2314          (symb (intern gmane local))
2315          (minmax (and (boundp symb) (symbol-value symb))))
2316
2317     (if (cond ((and minmax
2318                     (or (not (eq min (car minmax)))
2319                         (not (eq max (cdr minmax))))
2320                     min
2321                     max)
2322                (setcar minmax min)
2323                (setcdr minmax max)
2324                t)
2325               (minmax
2326                nil)
2327               ((and min max)
2328                (set symb (cons min max))
2329                t)
2330               (t
2331                (unintern symb local)))
2332         (set (intern "+dirty" local) t))))
2333
2334 (defun gnus-agent-article-name (article group)
2335   (expand-file-name article
2336                     (file-name-as-directory
2337                      (gnus-agent-group-pathname group))))
2338
2339 (defun gnus-agent-batch-confirmation (msg)
2340   "Show error message and return t."
2341   (gnus-message 1 msg)
2342   t)
2343
2344 ;;;###autoload
2345 (defun gnus-agent-batch-fetch ()
2346   "Start Gnus and fetch session."
2347   (interactive)
2348   (gnus)
2349   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2350     (gnus-agent-fetch-session))
2351   (gnus-group-exit))
2352
2353 (defun gnus-agent-fetch-session ()
2354   "Fetch all articles and headers that are eligible for fetching."
2355   (interactive)
2356   (unless gnus-agent-covered-methods
2357     (error "No servers are covered by the Gnus agent"))
2358   (unless gnus-plugged
2359     (error "Can't fetch articles while Gnus is unplugged"))
2360   (let ((methods (gnus-agent-covered-methods))
2361         groups group gnus-command-method)
2362     (save-excursion
2363       (while methods
2364         (setq gnus-command-method (car methods))
2365         (when (and (or (gnus-server-opened gnus-command-method)
2366                        (gnus-open-server gnus-command-method))
2367                    (gnus-online gnus-command-method))
2368           (setq groups (gnus-groups-from-server (car methods)))
2369           (gnus-agent-with-fetch
2370             (while (setq group (pop groups))
2371               (when (<= (gnus-group-level group)
2372                         gnus-agent-handle-level)
2373                 (if (or debug-on-error debug-on-quit)
2374                     (gnus-agent-fetch-group-1
2375                      group gnus-command-method)
2376                   (condition-case err
2377                       (gnus-agent-fetch-group-1
2378                        group gnus-command-method)
2379                     (error
2380                      (unless (funcall gnus-agent-confirmation-function
2381                                       (format "Error %s while fetching session.  Should gnus continue? "
2382                                               (error-message-string err)))
2383                        (error "Cannot fetch articles into the Gnus agent")))
2384                     (quit
2385                      (gnus-agent-regenerate-group group)
2386                      (unless (funcall gnus-agent-confirmation-function
2387                                       (format
2388                                        "%s while fetching session.  Should gnus continue? "
2389                                        (error-message-string err)))
2390                        (signal 'quit
2391                                "Cannot fetch articles into the Gnus agent")))))))))
2392         (setq methods (cdr methods)))
2393       (gnus-run-hooks 'gnus-agent-fetched-hook)
2394       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2395
2396 (defun gnus-agent-fetch-group-1 (group method)
2397   "Fetch GROUP."
2398   (let ((gnus-command-method method)
2399         (gnus-newsgroup-name group)
2400         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2401         (gnus-newsgroup-headers gnus-newsgroup-headers)
2402         (gnus-newsgroup-scored gnus-newsgroup-scored)
2403         (gnus-use-cache gnus-use-cache)
2404         (gnus-summary-expunge-below gnus-summary-expunge-below)
2405         (gnus-summary-mark-below gnus-summary-mark-below)
2406         (gnus-orphan-score gnus-orphan-score)
2407         ;; Maybe some other gnus-summary local variables should also
2408         ;; be put here.
2409
2410         gnus-headers
2411         gnus-score
2412         articles arts
2413         category predicate info marks score-param
2414         )
2415     (unless (gnus-check-group group)
2416       (error "Can't open server for %s" group))
2417
2418     ;; Fetch headers.
2419     (when (or gnus-newsgroup-active
2420               (gnus-active group)
2421               (gnus-activate-group group))
2422       (let ((marked-articles gnus-newsgroup-downloadable))
2423         ;; Identify the articles marked for download
2424         (unless gnus-newsgroup-active
2425           ;; The variable gnus-newsgroup-active was selected as I need
2426           ;; a gnus-summary local variable that is NOT bound to any
2427           ;; value (its global value should default to nil).
2428           (dolist (mark gnus-agent-download-marks)
2429             (let ((arts (cdr (assq mark (gnus-info-marks
2430                                          (setq info (gnus-get-info group)))))))
2431               (when arts
2432                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2433                                              marked-articles))
2434                 ))))
2435         (setq marked-articles (sort marked-articles '<))
2436
2437         ;; Fetch any new articles from the server
2438         (setq articles (gnus-agent-fetch-headers group))
2439
2440         ;; Merge new articles with marked
2441         (setq articles (sort (append marked-articles articles) '<))
2442
2443         (when articles
2444           ;; Parse them and see which articles we want to fetch.
2445           (setq gnus-newsgroup-dependencies
2446                 (or gnus-newsgroup-dependencies
2447                     (make-vector (length articles) 0)))
2448           (setq gnus-newsgroup-headers
2449                 (or gnus-newsgroup-headers
2450                     (gnus-get-newsgroup-headers-xover articles nil nil
2451                                                       group)))
2452           ;; `gnus-agent-overview-buffer' may be killed for
2453           ;; timeout reason.  If so, recreate it.
2454           (gnus-agent-create-buffer)
2455
2456           ;; Figure out how to select articles in this group
2457           (setq category (gnus-group-category group))
2458
2459           (setq predicate
2460                 (gnus-get-predicate
2461                  (gnus-agent-find-parameter group 'agent-predicate)))
2462
2463           ;; If the selection predicate requires scoring, score each header
2464           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2465             (let ((score-param
2466                    (gnus-agent-find-parameter group 'agent-score-file)))
2467               ;; Translate score-param into real one
2468               (cond
2469                ((not score-param))
2470                ((eq score-param 'file)
2471                 (setq score-param (gnus-all-score-files group)))
2472                ((stringp (car score-param)))
2473                (t
2474                 (setq score-param (list (list score-param)))))
2475               (when score-param
2476                 (gnus-score-headers score-param))))
2477
2478           (unless (and (eq predicate 'gnus-agent-false)
2479                        (not marked-articles))
2480             (let ((arts (list nil)))
2481               (let ((arts-tail arts)
2482                     (alist (gnus-agent-load-alist group))
2483                     (marked-articles marked-articles)
2484                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2485                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2486                   (let ((num (mail-header-number gnus-headers)))
2487                     ;; Determine if this article is already in the cache
2488                     (while (and alist
2489                                 (> num (caar alist)))
2490                       (setq alist (cdr alist)))
2491
2492                     (unless (and (eq num (caar alist))
2493                                  (cdar alist))
2494
2495                       ;; Determine if this article was marked for download.
2496                       (while (and marked-articles
2497                                   (> num (car marked-articles)))
2498                         (setq marked-articles
2499                               (cdr marked-articles)))
2500
2501                       ;; When this article is marked, or selected by the
2502                       ;; predicate, add it to the download list
2503                       (when (or (eq num (car marked-articles))
2504                                 (let ((gnus-score
2505                                        (or (cdr
2506                                             (assq num gnus-newsgroup-scored))
2507                                            gnus-summary-default-score))
2508                                       (gnus-agent-long-article
2509                                        (gnus-agent-find-parameter
2510                                         group 'agent-long-article))
2511                                       (gnus-agent-short-article
2512                                        (gnus-agent-find-parameter
2513                                         group 'agent-short-article))
2514                                       (gnus-agent-low-score
2515                                        (gnus-agent-find-parameter
2516                                         group 'agent-low-score))
2517                                       (gnus-agent-high-score
2518                                        (gnus-agent-find-parameter
2519                                         group 'agent-high-score))
2520                                       (gnus-agent-expire-days
2521                                        (gnus-agent-find-parameter
2522                                         group 'agent-days-until-old)))
2523                                   (funcall predicate)))
2524                         (gnus-agent-append-to-list arts-tail num))))))
2525
2526               (let (fetched-articles)
2527                 ;; Fetch all selected articles
2528                 (setq gnus-newsgroup-undownloaded
2529                       (gnus-sorted-ndifference
2530                        gnus-newsgroup-undownloaded
2531                        (setq fetched-articles
2532                              (if (cdr arts)
2533                                  (gnus-agent-fetch-articles group (cdr arts))
2534                                nil))))
2535
2536                 (let ((unfetched-articles
2537                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2538                   (if gnus-newsgroup-active
2539                       ;; Update the summary buffer
2540                       (progn
2541                         (dolist (article marked-articles)
2542                           (gnus-summary-set-agent-mark article t))
2543                         (dolist (article fetched-articles)
2544                           (when gnus-agent-mark-unread-after-downloaded
2545                             (setq gnus-newsgroup-downloadable
2546                                   (delq article gnus-newsgroup-downloadable))
2547                             (gnus-summary-mark-article
2548                              article gnus-unread-mark))
2549                           (when (gnus-summary-goto-subject article nil t)
2550                             (gnus-summary-update-download-mark article)))
2551                         (dolist (article unfetched-articles)
2552                           (gnus-summary-mark-article
2553                            article gnus-canceled-mark)))
2554
2555                     ;; Update the group buffer.
2556
2557                     ;; When some, or all, of the marked articles came
2558                     ;; from the download mark.  Remove that mark.  I
2559                     ;; didn't do this earlier as I only want to remove
2560                     ;; the marks after the fetch is completed.
2561
2562                     (dolist (mark gnus-agent-download-marks)
2563                       (when (eq mark 'download)
2564                         (let ((marked-arts
2565                                (assq mark (gnus-info-marks
2566                                            (setq info (gnus-get-info group))))))
2567                           (when (cdr marked-arts)
2568                             (setq marks
2569                                   (delq marked-arts (gnus-info-marks info)))
2570                             (gnus-info-set-marks info marks)))))
2571                     (let ((read (gnus-info-read
2572                                  (or info (setq info (gnus-get-info group))))))
2573                       (gnus-info-set-read
2574                        info (gnus-add-to-range read unfetched-articles)))
2575
2576                     (gnus-group-update-group group t)
2577                     (sit-for 0)
2578
2579                     (gnus-dribble-enter
2580                      (concat "(gnus-group-set-info '"
2581                              (gnus-prin1-to-string info)
2582                              ")"))))))))))))
2583
2584 ;;;
2585 ;;; Agent Category Mode
2586 ;;;
2587
2588 (defvar gnus-category-mode-hook nil
2589   "Hook run in `gnus-category-mode' buffers.")
2590
2591 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2592   "Format of category lines.
2593
2594 Valid specifiers include:
2595 %c  Topic name (string)
2596 %g  The number of groups in the topic (integer)
2597
2598 General format specifiers can also be used.  See Info node
2599 `(gnus)Formatting Variables'.")
2600
2601 (defvar gnus-category-mode-line-format "Gnus: %%b"
2602   "The format specification for the category mode line.")
2603
2604 (defvar gnus-agent-predicate 'false
2605   "The selection predicate used when no other source is available.")
2606
2607 (defvar gnus-agent-short-article 100
2608   "Articles that have fewer lines than this are short.")
2609
2610 (defvar gnus-agent-long-article 200
2611   "Articles that have more lines than this are long.")
2612
2613 (defvar gnus-agent-low-score 0
2614   "Articles that have a score lower than this have a low score.")
2615
2616 (defvar gnus-agent-high-score 0
2617   "Articles that have a score higher than this have a high score.")
2618
2619
2620 ;;; Internal variables.
2621
2622 (defvar gnus-category-buffer "*Agent Category*")
2623
2624 (defvar gnus-category-line-format-alist
2625   `((?c gnus-tmp-name ?s)
2626     (?g gnus-tmp-groups ?d)))
2627
2628 (defvar gnus-category-mode-line-format-alist
2629   `((?u user-defined ?s)))
2630
2631 (defvar gnus-category-line-format-spec nil)
2632 (defvar gnus-category-mode-line-format-spec nil)
2633
2634 (defvar gnus-category-mode-map nil)
2635 (put 'gnus-category-mode 'mode-class 'special)
2636
2637 (unless gnus-category-mode-map
2638   (setq gnus-category-mode-map (make-sparse-keymap))
2639   (suppress-keymap gnus-category-mode-map)
2640
2641   (gnus-define-keys gnus-category-mode-map
2642     "q" gnus-category-exit
2643     "k" gnus-category-kill
2644     "c" gnus-category-copy
2645     "a" gnus-category-add
2646     "e" gnus-agent-customize-category
2647     "p" gnus-category-edit-predicate
2648     "g" gnus-category-edit-groups
2649     "s" gnus-category-edit-score
2650     "l" gnus-category-list
2651
2652     "\C-c\C-i" gnus-info-find-node
2653     "\C-c\C-b" gnus-bug))
2654
2655 (defvar gnus-category-menu-hook nil
2656   "*Hook run after the creation of the menu.")
2657
2658 (defun gnus-category-make-menu-bar ()
2659   (gnus-turn-off-edit-menu 'category)
2660   (unless (boundp 'gnus-category-menu)
2661     (easy-menu-define
2662      gnus-category-menu gnus-category-mode-map ""
2663      '("Categories"
2664        ["Add" gnus-category-add t]
2665        ["Kill" gnus-category-kill t]
2666        ["Copy" gnus-category-copy t]
2667        ["Edit category" gnus-agent-customize-category t]
2668        ["Edit predicate" gnus-category-edit-predicate t]
2669        ["Edit score" gnus-category-edit-score t]
2670        ["Edit groups" gnus-category-edit-groups t]
2671        ["Exit" gnus-category-exit t]))
2672
2673     (gnus-run-hooks 'gnus-category-menu-hook)))
2674
2675 (defun gnus-category-mode ()
2676   "Major mode for listing and editing agent categories.
2677
2678 All normal editing commands are switched off.
2679 \\<gnus-category-mode-map>
2680 For more in-depth information on this mode, read the manual
2681 \(`\\[gnus-info-find-node]').
2682
2683 The following commands are available:
2684
2685 \\{gnus-category-mode-map}"
2686   (interactive)
2687   (when (gnus-visual-p 'category-menu 'menu)
2688     (gnus-category-make-menu-bar))
2689   (kill-all-local-variables)
2690   (gnus-simplify-mode-line)
2691   (setq major-mode 'gnus-category-mode)
2692   (setq mode-name "Category")
2693   (gnus-set-default-directory)
2694   (setq mode-line-process nil)
2695   (use-local-map gnus-category-mode-map)
2696   (buffer-disable-undo)
2697   (setq truncate-lines t)
2698   (setq buffer-read-only t)
2699   (gnus-run-mode-hooks 'gnus-category-mode-hook))
2700
2701 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2702
2703 (defun gnus-category-insert-line (category)
2704   (let* ((gnus-tmp-name (format "%s" (car category)))
2705          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2706     (beginning-of-line)
2707     (gnus-add-text-properties
2708      (point)
2709      (prog1 (1+ (point))
2710        ;; Insert the text.
2711        (eval gnus-category-line-format-spec))
2712      (list 'gnus-category gnus-tmp-name))))
2713
2714 (defun gnus-enter-category-buffer ()
2715   "Go to the Category buffer."
2716   (interactive)
2717   (gnus-category-setup-buffer)
2718   (gnus-configure-windows 'category)
2719   (gnus-category-prepare))
2720
2721 (defun gnus-category-setup-buffer ()
2722   (unless (get-buffer gnus-category-buffer)
2723     (save-excursion
2724       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2725       (gnus-category-mode))))
2726
2727 (defun gnus-category-prepare ()
2728   (gnus-set-format 'category-mode)
2729   (gnus-set-format 'category t)
2730   (let ((alist gnus-category-alist)
2731         (buffer-read-only nil))
2732     (erase-buffer)
2733     (while alist
2734       (gnus-category-insert-line (pop alist)))
2735     (goto-char (point-min))
2736     (gnus-category-position-point)))
2737
2738 (defun gnus-category-name ()
2739   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2740       (error "No category on the current line")))
2741
2742 (defun gnus-category-read ()
2743   "Read the category alist."
2744   (setq gnus-category-alist
2745         (or
2746          (with-temp-buffer
2747            (ignore-errors
2748             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2749             (goto-char (point-min))
2750             ;; This code isn't temp, it will be needed so long as
2751             ;; anyone may be migrating from an older version.
2752
2753             ;; Once we're certain that people will not revert to an
2754             ;; earlier version, we can take out the old-list code in
2755             ;; gnus-category-write.
2756             (let* ((old-list (read (current-buffer)))
2757                    (new-list (ignore-errors (read (current-buffer)))))
2758               (if new-list
2759                   new-list
2760                 ;; Convert from a positional list to an alist.
2761                 (mapcar
2762                  (lambda (c)
2763                    (setcdr c
2764                            (delq nil
2765                                  (gnus-mapcar
2766                                   (lambda (valu symb)
2767                                     (if valu
2768                                         (cons symb valu)))
2769                                   (cdr c)
2770                                   '(agent-predicate agent-score-file agent-groups))))
2771                    c)
2772                  old-list)))))
2773          (list (gnus-agent-cat-make 'default 'short)))))
2774
2775 (defun gnus-category-write ()
2776   "Write the category alist."
2777   (setq gnus-category-predicate-cache nil
2778         gnus-category-group-cache nil)
2779   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2780   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2781     ;; This prin1 is temporary.  It exists so that people can revert
2782     ;; to an earlier version of gnus-agent.
2783     (prin1 (mapcar (lambda (c)
2784               (list (car c)
2785                     (cdr (assoc 'agent-predicate c))
2786                     (cdr (assoc 'agent-score-file c))
2787                     (cdr (assoc 'agent-groups c))))
2788                    gnus-category-alist)
2789            (current-buffer))
2790     (newline)
2791     (prin1 gnus-category-alist (current-buffer))))
2792
2793 (defun gnus-category-edit-predicate (category)
2794   "Edit the predicate for CATEGORY."
2795   (interactive (list (gnus-category-name)))
2796   (let ((info (assq category gnus-category-alist)))
2797     (gnus-edit-form
2798      (gnus-agent-cat-predicate info)
2799      (format "Editing the select predicate for category %s" category)
2800      `(lambda (predicate)
2801         ;; Avoid run-time execution of setf form
2802         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2803         ;;       predicate)
2804         ;; use its expansion instead:
2805         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2806                                      'agent-predicate predicate)
2807
2808         (gnus-category-write)
2809         (gnus-category-list)))))
2810
2811 (defun gnus-category-edit-score (category)
2812   "Edit the score expression for CATEGORY."
2813   (interactive (list (gnus-category-name)))
2814   (let ((info (assq category gnus-category-alist)))
2815     (gnus-edit-form
2816      (gnus-agent-cat-score-file info)
2817      (format "Editing the score expression for category %s" category)
2818      `(lambda (score-file)
2819         ;; Avoid run-time execution of setf form
2820         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2821         ;;       score-file)
2822         ;; use its expansion instead:
2823         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2824                                      'agent-score-file score-file)
2825
2826         (gnus-category-write)
2827         (gnus-category-list)))))
2828
2829 (defun gnus-category-edit-groups (category)
2830   "Edit the group list for CATEGORY."
2831   (interactive (list (gnus-category-name)))
2832   (let ((info (assq category gnus-category-alist)))
2833     (gnus-edit-form
2834      (gnus-agent-cat-groups info)
2835      (format "Editing the group list for category %s" category)
2836      `(lambda (groups)
2837         ;; Avoid run-time execution of setf form
2838         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2839         ;;       groups)
2840         ;; use its expansion instead:
2841         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2842                                    groups)
2843
2844         (gnus-category-write)
2845         (gnus-category-list)))))
2846
2847 (defun gnus-category-kill (category)
2848   "Kill the current category."
2849   (interactive (list (gnus-category-name)))
2850   (let ((info (assq category gnus-category-alist))
2851         (buffer-read-only nil))
2852     (gnus-delete-line)
2853     (setq gnus-category-alist (delq info gnus-category-alist))
2854     (gnus-category-write)))
2855
2856 (defun gnus-category-copy (category to)
2857   "Copy the current category."
2858   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2859   (let ((info (assq category gnus-category-alist)))
2860     (push (let ((newcat (gnus-copy-sequence info)))
2861             (setf (gnus-agent-cat-name newcat) to)
2862             (setf (gnus-agent-cat-groups newcat) nil)
2863             newcat)
2864           gnus-category-alist)
2865     (gnus-category-write)
2866     (gnus-category-list)))
2867
2868 (defun gnus-category-add (category)
2869   "Create a new category."
2870   (interactive "SCategory name: ")
2871   (when (assq category gnus-category-alist)
2872     (error "Category %s already exists" category))
2873   (push (gnus-agent-cat-make category)
2874         gnus-category-alist)
2875   (gnus-category-write)
2876   (gnus-category-list))
2877
2878 (defun gnus-category-list ()
2879   "List all categories."
2880   (interactive)
2881   (gnus-category-prepare))
2882
2883 (defun gnus-category-exit ()
2884   "Return to the group buffer."
2885   (interactive)
2886   (kill-buffer (current-buffer))
2887   (gnus-configure-windows 'group t))
2888
2889 ;; To avoid having 8-bit characters in the source file.
2890 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2891
2892 (defvar gnus-category-predicate-alist
2893   '((spam . gnus-agent-spam-p)
2894     (short . gnus-agent-short-p)
2895     (long . gnus-agent-long-p)
2896     (low . gnus-agent-low-scored-p)
2897     (high . gnus-agent-high-scored-p)
2898     (read . gnus-agent-read-p)
2899     (true . gnus-agent-true)
2900     (false . gnus-agent-false))
2901   "Mapping from short score predicate symbols to predicate functions.")
2902
2903 (defun gnus-agent-spam-p ()
2904   "Say whether an article is spam or not."
2905   (unless gnus-agent-spam-hashtb
2906     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2907   (if (not (equal (mail-header-references gnus-headers) ""))
2908       nil
2909     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2910       (prog1
2911           (gnus-gethash string gnus-agent-spam-hashtb)
2912         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2913
2914 (defun gnus-agent-short-p ()
2915   "Say whether an article is short or not."
2916   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2917
2918 (defun gnus-agent-long-p ()
2919   "Say whether an article is long or not."
2920   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2921
2922 (defun gnus-agent-low-scored-p ()
2923   "Say whether an article has a low score or not."
2924   (< gnus-score gnus-agent-low-score))
2925
2926 (defun gnus-agent-high-scored-p ()
2927   "Say whether an article has a high score or not."
2928   (> gnus-score gnus-agent-high-score))
2929
2930 (defun gnus-agent-read-p ()
2931   "Say whether an article is read or not."
2932   (gnus-member-of-range (mail-header-number gnus-headers)
2933                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2934
2935 (defun gnus-category-make-function (predicate)
2936   "Make a function from PREDICATE."
2937   (let ((func (gnus-category-make-function-1 predicate)))
2938     (if (and (= (length func) 1)
2939              (symbolp (car func)))
2940         (car func)
2941       (gnus-byte-compile `(lambda () ,func)))))
2942
2943 (defun gnus-agent-true ()
2944   "Return t."
2945   t)
2946
2947 (defun gnus-agent-false ()
2948   "Return nil."
2949   nil)
2950
2951 (defun gnus-category-make-function-1 (predicate)
2952   "Make a function from PREDICATE."
2953   (cond
2954    ;; Functions are just returned as is.
2955    ((or (symbolp predicate)
2956         (functionp predicate))
2957     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2958            predicate)))
2959    ;; More complex predicate.
2960    ((consp predicate)
2961     `(,(cond
2962         ((memq (car predicate) '(& and))
2963          'and)
2964         ((memq (car predicate) '(| or))
2965          'or)
2966         ((memq (car predicate) gnus-category-not)
2967          'not))
2968       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2969    (t
2970     (error "Unknown predicate type: %s" predicate))))
2971
2972 (defun gnus-get-predicate (predicate)
2973   "Return the function implementing PREDICATE."
2974   (or (cdr (assoc predicate gnus-category-predicate-cache))
2975       (let ((func (gnus-category-make-function predicate)))
2976         (setq gnus-category-predicate-cache
2977               (nconc gnus-category-predicate-cache
2978                      (list (cons predicate func))))
2979         func)))
2980
2981 (defun gnus-predicate-implies-unread (predicate)
2982   "Say whether PREDICATE implies unread articles only.
2983 It is okay to miss some cases, but there must be no false positives.
2984 That is, if this predicate returns true, then indeed the predicate must
2985 return only unread articles."
2986   (eq t (gnus-function-implies-unread-1
2987          (gnus-category-make-function-1 predicate))))
2988
2989 (defun gnus-function-implies-unread-1 (function)
2990   "Recursively evaluate a predicate function to determine whether it can select
2991 any read articles.  Returns t if the function is known to never
2992 return read articles, nil when it is known to always return read
2993 articles, and t_nil when the function may return both read and unread
2994 articles."
2995   (let ((func (car function))
2996         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2997     (cond ((eq func 'and)
2998            (cond ((memq t args) ; if any argument returns only unread articles
2999                   ;; then that argument constrains the result to only unread articles.
3000                   t)
3001                  ((memq 't_nil args) ; if any argument is indeterminate
3002                   ;; then the result is indeterminate
3003                   't_nil)))
3004           ((eq func 'or)
3005            (cond ((memq nil args) ; if any argument returns read articles
3006                   ;; then that argument ensures that the results includes read articles.
3007                   nil)
3008                  ((memq 't_nil args) ; if any argument is indeterminate
3009                   ;; then that argument ensures that the results are indeterminate
3010                   't_nil)
3011                  (t ; if all arguments return only unread articles
3012                   ;; then the result returns only unread articles
3013                   t)))
3014           ((eq func 'not)
3015            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
3016                   ; then the result is indeterminate
3017                   (car args))
3018                  (t ; otherwise
3019                   ; toggle the result to be the opposite of the argument
3020                   (not (car args)))))
3021           ((eq func 'gnus-agent-read-p)
3022            nil) ; The read predicate NEVER returns unread articles
3023           ((eq func 'gnus-agent-false)
3024            t) ; The false predicate returns t as the empty set excludes all read articles
3025           ((eq func 'gnus-agent-true)
3026            nil) ; The true predicate ALWAYS returns read articles
3027           ((catch 'found-match
3028              (let ((alist gnus-category-predicate-alist))
3029                (while alist
3030                  (if (eq func (cdar alist))
3031                      (throw 'found-match t)
3032                    (setq alist (cdr alist))))))
3033            't_nil) ; All other predicates return read and unread articles
3034           (t
3035            (error "Unknown predicate function: %s" function)))))
3036
3037 (defun gnus-group-category (group)
3038   "Return the category GROUP belongs to."
3039   (unless gnus-category-group-cache
3040     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
3041     (let ((cs gnus-category-alist)
3042           groups cat)
3043       (while (setq cat (pop cs))
3044         (setq groups (gnus-agent-cat-groups cat))
3045         (while groups
3046           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
3047   (or (gnus-gethash group gnus-category-group-cache)
3048       (assq 'default gnus-category-alist)))
3049
3050 (defun gnus-agent-expire-group (group &optional articles force)
3051   "Expire all old articles in GROUP.
3052 If you want to force expiring of certain articles, this function can
3053 take ARTICLES, and FORCE parameters as well.
3054
3055 The articles on which the expiration process runs are selected as follows:
3056   if ARTICLES is null, all read and unmarked articles.
3057   if ARTICLES is t, all articles.
3058   if ARTICLES is a list, just those articles.
3059 FORCE is equivalent to setting the expiration predicates to true."
3060   (interactive
3061    (list (let ((def (or (gnus-group-group-name)
3062                         gnus-newsgroup-name)))
3063            (let ((select (read-string (if def
3064                                           (concat "Group Name ("
3065                                                   def "): ")
3066                                         "Group Name: "))))
3067              (if (and (equal "" select)
3068                       def)
3069                  def
3070                select)))))
3071
3072   (if (not group)
3073       (gnus-agent-expire articles group force)
3074     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
3075           ;; expiration statistics of this single group
3076           (gnus-agent-expire-stats (list 0 0 0.0)))
3077       (if (or (not (eq articles t))
3078               (yes-or-no-p
3079                (concat "Are you sure that you want to "
3080                        "expire all articles in " group "? ")))
3081           (let ((gnus-command-method (gnus-find-method-for-group group))
3082                 (overview (gnus-get-buffer-create " *expire overview*"))
3083                 orig)
3084             (unwind-protect
3085                 (let ((active-file (gnus-agent-lib-file "active")))
3086                   (when (file-exists-p active-file)
3087                     (with-temp-buffer
3088                       (nnheader-insert-file-contents active-file)
3089                       (gnus-active-to-gnus-format
3090                        gnus-command-method
3091                        (setq orig (gnus-make-hashtable
3092                                    (count-lines (point-min) (point-max))))))
3093                     (save-excursion
3094                       (gnus-agent-expire-group-1
3095                        group overview (gnus-gethash-safe group orig)
3096                        articles force))))
3097               (kill-buffer overview))))
3098       (gnus-message 4 (gnus-agent-expire-done-message)))))
3099
3100 (defun gnus-agent-expire-group-1 (group overview active articles force)
3101   ;; Internal function - requires caller to have set
3102   ;; gnus-command-method, initialized overview buffer, and to have
3103   ;; provided a non-nil active
3104
3105   (let ((dir (gnus-agent-group-pathname group)))
3106     (gnus-agent-with-refreshed-group
3107      group
3108      (when (boundp 'gnus-agent-expire-current-dirs)
3109        (set 'gnus-agent-expire-current-dirs
3110             (cons dir
3111                   (symbol-value 'gnus-agent-expire-current-dirs))))
3112
3113      (if (and (not force)
3114               (eq 'DISABLE (gnus-agent-find-parameter group
3115                                                       'agent-enable-expiration)))
3116          (gnus-message 5 "Expiry skipping over %s" group)
3117        (gnus-message 5 "Expiring articles in %s" group)
3118        (gnus-agent-load-alist group)
3119        (let* ((bytes-freed 0)
3120               (size-files-deleted 0.0)
3121               (files-deleted 0)
3122               (nov-entries-deleted 0)
3123               (info (gnus-get-info group))
3124               (alist gnus-agent-article-alist)
3125               (day (- (time-to-days (current-time))
3126                       (gnus-agent-find-parameter group 'agent-days-until-old)))
3127               (specials (if (and alist
3128                                  (not force))
3129                             ;; This could be a bit of a problem.  I need to
3130                             ;; keep the last article to avoid refetching
3131                             ;; headers when using nntp in the backend.  At
3132                             ;; the same time, if someone uses a backend
3133                             ;; that supports article moving then I may have
3134                             ;; to remove the last article to complete the
3135                             ;; move.  Right now, I'm going to assume that
3136                             ;; FORCE overrides specials.
3137                             (list (caar (last alist)))))
3138               (unreads ;; Articles that are excluded from the
3139                ;; expiration process
3140                (cond (gnus-agent-expire-all
3141                       ;; All articles are marked read by global decree
3142                       nil)
3143                      ((eq articles t)
3144                       ;; All articles are marked read by function
3145                       ;; parameter
3146                       nil)
3147                      ((not articles)
3148                       ;; Unread articles are marked protected from
3149                       ;; expiration Don't call
3150                       ;; gnus-list-of-unread-articles as it returns
3151                       ;; articles that have not been fetched into the
3152                       ;; agent.
3153                       (ignore-errors
3154                         (gnus-agent-unread-articles group)))
3155                      (t
3156                       ;; All articles EXCEPT those named by the caller
3157                       ;; are protected from expiration
3158                       (gnus-sorted-difference
3159                        (gnus-uncompress-range
3160                         (cons (caar alist)
3161                               (caar (last alist))))
3162                        (sort articles '<)))))
3163               (marked ;; More articles that are excluded from the
3164                ;; expiration process
3165                (cond (gnus-agent-expire-all
3166                       ;; All articles are unmarked by global decree
3167                       nil)
3168                      ((eq articles t)
3169                       ;; All articles are unmarked by function
3170                       ;; parameter
3171                       nil)
3172                      (articles
3173                       ;; All articles may as well be unmarked as the
3174                       ;; unreads list already names the articles we are
3175                       ;; going to keep
3176                       nil)
3177                      (t
3178                       ;; Ticked and/or dormant articles are excluded
3179                       ;; from expiration
3180                       (nconc
3181                        (gnus-uncompress-range
3182                         (cdr (assq 'tick (gnus-info-marks info))))
3183                        (gnus-uncompress-range
3184                         (cdr (assq 'dormant
3185                                    (gnus-info-marks info))))))))
3186               (nov-file (concat dir ".overview"))
3187               (cnt 0)
3188               (completed -1)
3189               dlist
3190               type)
3191
3192          ;; The normal article alist contains elements that look like
3193          ;; (article# .  fetch_date) I need to combine other
3194          ;; information with this list.  For example, a flag indicating
3195          ;; that a particular article MUST BE KEPT.  To do this, I'm
3196          ;; going to transform the elements to look like (article#
3197          ;; fetch_date keep_flag NOV_entry_position) Later, I'll reverse
3198          ;; the process to generate the expired article alist.
3199
3200          ;; Convert the alist elements to (article# fetch_date nil
3201          ;; nil).
3202          (setq dlist (mapcar (lambda (e)
3203                                (list (car e) (cdr e) nil nil)) alist))
3204
3205          ;; Convert the keep lists to elements that look like (article#
3206          ;; nil keep_flag nil) then append it to the expanded dlist
3207          ;; These statements are sorted by ascending precidence of the
3208          ;; keep_flag.
3209          (setq dlist (nconc dlist
3210                             (mapcar (lambda (e)
3211                                       (list e nil 'unread  nil))
3212                                     unreads)))
3213          (setq dlist (nconc dlist
3214                             (mapcar (lambda (e)
3215                                       (list e nil 'marked  nil))
3216                                     marked)))
3217          (setq dlist (nconc dlist
3218                             (mapcar (lambda (e)
3219                                       (list e nil 'special nil))
3220                                     specials)))
3221
3222          (set-buffer overview)
3223          (erase-buffer)
3224          (buffer-disable-undo)
3225          (when (file-exists-p nov-file)
3226            (gnus-message 7 "gnus-agent-expire: Loading overview...")
3227            (nnheader-insert-file-contents nov-file)
3228            (goto-char (point-min))
3229         
3230            (let (p)
3231              (while (< (setq p (point)) (point-max))
3232                (condition-case nil
3233                    ;; If I successfully read an integer (the plus zero
3234                    ;; ensures a numeric type), append the position
3235                    ;; to the list
3236                    (push (list (+ 0 (read (current-buffer))) nil nil
3237                                p)
3238                          dlist)
3239                  (error
3240                   (gnus-message 1 "gnus-agent-expire: read error \
3241 occurred when reading expression at %s in %s.  Skipping to next \
3242 line." (point) nov-file)))
3243                ;; Whether I succeeded, or failed, it doesn't matter.
3244                ;; Move to the next line then try again.
3245                (forward-line 1)))
3246
3247            (gnus-message
3248             7 "gnus-agent-expire: Loading overview... Done"))
3249          (set-buffer-modified-p nil)
3250
3251          ;; At this point, all of the information is in dlist.  The
3252          ;; only problem is that much of it is spread across multiple
3253          ;; entries.  Sort then MERGE!!
3254          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
3255          ;; If two entries have the same article-number then sort by
3256          ;; ascending keep_flag.
3257          (let ((special 0)
3258                (marked 1)
3259                (unread 2))
3260            (setq dlist
3261                  (sort dlist
3262                        (lambda (a b)
3263                          (cond ((< (nth 0 a) (nth 0 b))
3264                                 t)
3265                                ((> (nth 0 a) (nth 0 b))
3266                                 nil)
3267                                (t
3268                                 (let ((a (or (symbol-value (nth 2 a))
3269                                              3))
3270                                       (b (or (symbol-value (nth 2 b))
3271                                              3)))
3272                                   (<= a b))))))))
3273          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3274          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3275          (let ((dlist dlist))
3276            (while (cdr dlist)           ; I'm not at the end-of-list
3277              (if (eq (caar dlist) (caadr dlist))
3278                  (let ((first (cdr (car dlist)))
3279                        (secnd (cdr (cadr dlist))))
3280                    (setcar first (or (car first)
3281                                      (car secnd))) ; fetch_date
3282                    (setq first (cdr first)
3283                          secnd (cdr secnd))
3284                    (setcar first (or (car first)
3285                                      (car secnd))) ; Keep_flag
3286                    (setq first (cdr first)
3287                          secnd (cdr secnd))
3288                    (setcar first (or (car first)
3289                                      (car secnd))) ; NOV_entry_position
3290
3291                    (setcdr dlist (cddr dlist)))
3292                (setq dlist (cdr dlist)))))
3293
3294          ;; Check the order of the entry positions.  They should be in
3295          ;; ascending order.  If they aren't, the positions must be
3296          ;; converted to markers.
3297          (when (let ((dlist dlist)
3298                      (prev-pos -1)
3299                      pos)
3300                  (while dlist
3301                    (if (setq pos (nth 3 (pop dlist)))
3302                        (if (< pos prev-pos)
3303                            (throw 'sort-results 'unsorted)
3304                          (setq prev-pos pos)))))
3305            (gnus-message 7 "gnus-agent-expire: Unsorted overview; inserting markers to compensate.")
3306            (mapcar (lambda (entry)
3307                      (let ((pos (nth 3 entry)))
3308                        (if pos
3309                            (setf (nth 3 entry)
3310                                  (set-marker (make-marker)
3311                                              pos)))))
3312                    dlist))
3313
3314          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3315
3316          (let* ((len (float (length dlist)))
3317                 (alist (list nil))
3318                 (tail-alist alist)
3319                 (position-offset 0)
3320                 )
3321
3322            (while dlist
3323              (let ((new-completed (truncate (* 100.0
3324                                                (/ (setq cnt (1+ cnt))
3325                                                   len))))
3326                    message-log-max)
3327                (when (> new-completed completed)
3328                  (setq completed new-completed)
3329                  (gnus-message 7 "%3d%% completed..."  completed)))
3330              (let* ((entry          (car dlist))
3331                     (article-number (nth 0 entry))
3332                     (fetch-date     (nth 1 entry))
3333                     (keep           (nth 2 entry))
3334                     (marker         (nth 3 entry)))
3335
3336                (cond
3337                 ;; Kept articles are unread, marked, or special.
3338                 (keep
3339                  (gnus-agent-message 10
3340                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3341                                      group article-number keep (if fetch-date " and file" ""))
3342                  (when fetch-date
3343                    (unless (file-exists-p
3344                             (concat dir (number-to-string
3345                                          article-number)))
3346                      (setf (nth 1 entry) nil)
3347                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3348 download flag on %s:%d as the cached article file is missing."
3349                                          group (caar dlist)))
3350                    (unless marker
3351                      (gnus-message 1 "gnus-agent-expire detected a \
3352 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3353                  (gnus-agent-append-to-list
3354                   tail-alist
3355                   (cons article-number fetch-date)))
3356
3357                 ;; The following articles are READ, UNMARKED, and
3358                 ;; ORDINARY.  See if they can be EXPIRED!!!
3359                 ((setq type
3360                        (cond
3361                         ((not (integerp fetch-date))
3362                          'read) ;; never fetched article (may expire
3363                         ;; right now)
3364                         ((not (file-exists-p
3365                                (concat dir (number-to-string
3366                                             article-number))))
3367                          (setf (nth 1 entry) nil)
3368                          'externally-expired) ;; Can't find the cached
3369                         ;; article.  Handle case
3370                         ;; as though this article
3371                         ;; was never fetched.
3372
3373                         ;; We now have the arrival day, so we see
3374                         ;; whether it's old enough to be expired.
3375                         ((< fetch-date day)
3376                          'expired)
3377                         (force
3378                          'forced)))
3379
3380                  ;; I found some reason to expire this entry.
3381
3382                  (let ((actions nil))
3383                    (when (memq type '(forced expired))
3384                      (ignore-errors     ; Just being paranoid.
3385                        (let* ((file-name (nnheader-concat dir (number-to-string
3386                                                                article-number)))
3387                               (size (float (nth 7 (file-attributes file-name)))))
3388                          (incf bytes-freed size)
3389                          (incf size-files-deleted size)
3390                          (incf files-deleted)
3391                          (delete-file file-name))
3392                        (push "expired cached article" actions))
3393                      (setf (nth 1 entry) nil)
3394                      )
3395
3396                    (when marker
3397                      (push "NOV entry removed" actions)
3398
3399                      (goto-char (if (markerp marker)
3400                                     marker
3401                                   (- marker position-offset)))
3402
3403                      (incf nov-entries-deleted)
3404
3405                      (let* ((from (point-at-bol))
3406                             (to (progn (forward-line 1) (point)))
3407                             (freed (- to from)))
3408                        (incf bytes-freed freed)
3409                        (incf position-offset freed)
3410                        (delete-region from to)))
3411
3412                    ;; If considering all articles is set, I can only
3413                    ;; expire article IDs that are no longer in the
3414                    ;; active range (That is, articles that preceed the
3415                    ;; first article in the new alist).
3416                    (if (and gnus-agent-consider-all-articles
3417                             (>= article-number (car active)))
3418                        ;; I have to keep this ID in the alist
3419                        (gnus-agent-append-to-list
3420                         tail-alist (cons article-number fetch-date))
3421                      (push (format "Removed %s article number from \
3422 article alist" type) actions))
3423
3424                    (when actions
3425                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3426                                          group article-number
3427                                          (mapconcat 'identity actions ", ")))))
3428                 (t
3429                  (gnus-agent-message
3430                   10 "gnus-agent-expire: %s:%d: Article kept as \
3431 expiration tests failed." group article-number)
3432                  (gnus-agent-append-to-list
3433                   tail-alist (cons article-number fetch-date)))
3434                 )
3435
3436                ;; Remove markers as I intend to reuse this buffer again.
3437                (when (and marker
3438                           (markerp marker))
3439                  (set-marker marker nil))
3440
3441                (setq dlist (cdr dlist))))
3442
3443            (setq alist (cdr alist))
3444
3445            (let ((inhibit-quit t))
3446              (unless (equal alist gnus-agent-article-alist)
3447                (setq gnus-agent-article-alist alist)
3448                (gnus-agent-save-alist group))
3449
3450              (when (buffer-modified-p)
3451                (let ((coding-system-for-write
3452                       gnus-agent-file-coding-system))
3453                  (gnus-make-directory dir)
3454                  (write-region (point-min) (point-max) nov-file nil
3455                                'silent)
3456                  ;; clear the modified flag as that I'm not confused by
3457                  ;; its status on the next pass through this routine.
3458                  (set-buffer-modified-p nil)
3459                  (gnus-agent-update-view-total-fetched-for group t)))
3460
3461              (when (eq articles t)
3462                (gnus-summary-update-info))))
3463
3464          (when (boundp 'gnus-agent-expire-stats)
3465            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3466              (incf (nth 2 stats) bytes-freed)
3467              (incf (nth 1 stats) files-deleted)
3468              (incf (nth 0 stats) nov-entries-deleted)))
3469
3470          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3471
3472 (defun gnus-agent-expire (&optional articles group force)
3473   "Expire all old articles.
3474 If you want to force expiring of certain articles, this function can
3475 take ARTICLES, GROUP and FORCE parameters as well.
3476
3477 The articles on which the expiration process runs are selected as follows:
3478   if ARTICLES is null, all read and unmarked articles.
3479   if ARTICLES is t, all articles.
3480   if ARTICLES is a list, just those articles.
3481 Setting GROUP will limit expiration to that group.
3482 FORCE is equivalent to setting the expiration predicates to true."
3483   (interactive)
3484
3485   (if group
3486       (gnus-agent-expire-group group articles force)
3487     (if (or (not (eq articles t))
3488             (yes-or-no-p "Are you sure that you want to expire all \
3489 articles in every agentized group? "))
3490         (let ((methods (gnus-agent-covered-methods))
3491               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3492               ;; of agent directories.
3493               (gnus-agent-expire-current-dirs nil)
3494               ;; Bind gnus-agent-expire-stats to enable tracking of
3495               ;; expiration statistics across all groups
3496               (gnus-agent-expire-stats (list 0 0 0.0))
3497               gnus-command-method overview orig)
3498           (setq overview (gnus-get-buffer-create " *expire overview*"))
3499           (unwind-protect
3500               (while (setq gnus-command-method (pop methods))
3501                 (let ((active-file (gnus-agent-lib-file "active")))
3502                   (when (file-exists-p active-file)
3503                     (with-temp-buffer
3504                       (nnheader-insert-file-contents active-file)
3505                       (gnus-active-to-gnus-format
3506                        gnus-command-method
3507                        (setq orig (gnus-make-hashtable
3508                                    (count-lines (point-min) (point-max))))))
3509                     (dolist (expiring-group (gnus-groups-from-server
3510                                              gnus-command-method))
3511                       (let* ((active
3512                               (gnus-gethash-safe expiring-group orig)))
3513
3514                         (when active
3515                           (save-excursion
3516                             (gnus-agent-expire-group-1
3517                              expiring-group overview active articles force))))))))
3518             (kill-buffer overview))
3519           (gnus-agent-expire-unagentized-dirs)
3520           (gnus-message 4 (gnus-agent-expire-done-message))))))
3521
3522 (defun gnus-agent-expire-done-message ()
3523   (if (and (> gnus-verbose 4)
3524            (boundp 'gnus-agent-expire-stats))
3525       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3526              (size (nth 2 stats))
3527             (units '(B KB MB GB)))
3528         (while (and (> size 1024.0)
3529                     (cdr units))
3530           (setq size (/ size 1024.0)
3531                 units (cdr units)))
3532
3533         (format "Expiry recovered %d NOV entries, deleted %d files,\
3534  and freed %f %s."
3535                 (nth 0 stats)
3536                 (nth 1 stats)
3537                 size (car units)))
3538     "Expiry...done"))
3539
3540 (defun gnus-agent-expire-unagentized-dirs ()
3541   (when (and gnus-agent-expire-unagentized-dirs
3542              (boundp 'gnus-agent-expire-current-dirs))
3543     (let* ((keep (gnus-make-hashtable))
3544            ;; Formally bind gnus-agent-expire-current-dirs so that the
3545            ;; compiler will not complain about free references.
3546            (gnus-agent-expire-current-dirs
3547             (symbol-value 'gnus-agent-expire-current-dirs))
3548            dir)
3549
3550       (gnus-sethash gnus-agent-directory t keep)
3551       (while gnus-agent-expire-current-dirs
3552         (setq dir (pop gnus-agent-expire-current-dirs))
3553         (when (and (stringp dir)
3554                    (file-directory-p dir))
3555           (while (not (gnus-gethash dir keep))
3556             (gnus-sethash dir t keep)
3557             (setq dir (file-name-directory (directory-file-name dir))))))
3558
3559       (let* (to-remove
3560              checker
3561              (checker
3562               (function
3563                (lambda (d)
3564                  "Given a directory, check it and its subdirectories for
3565               membership in the keep hash.  If it isn't found, add
3566               it to to-remove."
3567                  (let ((files (directory-files d))
3568                        file)
3569                    (while (setq file (pop files))
3570                      (cond ((equal file ".") ; Ignore self
3571                             nil)
3572                            ((equal file "..") ; Ignore parent
3573                             nil)
3574                            ((equal file ".overview")
3575                             ;; Directory must contain .overview to be
3576                             ;; agent's cache of a group.
3577                             (let ((d (file-name-as-directory d))
3578                                   r)
3579                               ;; Search ancestor's for last directory NOT
3580                               ;; found in keep hash.
3581                               (while (not (gnus-gethash
3582                                            (setq d (file-name-directory d)) keep))
3583                                 (setq r d
3584                                       d (directory-file-name d)))
3585                               ;; if ANY ancestor was NOT in keep hash and
3586                               ;; it it's already in to-remove, add it to
3587                               ;; to-remove.
3588                               (if (and r
3589                                        (not (member r to-remove)))
3590                                   (push r to-remove))))
3591                            ((file-directory-p (setq file (nnheader-concat d file)))
3592                             (funcall checker file)))))))))
3593         (funcall checker (expand-file-name gnus-agent-directory))
3594
3595         (when (and to-remove
3596                    (or gnus-expert-user
3597                        (gnus-y-or-n-p
3598                         "gnus-agent-expire has identified local directories that are\
3599  not currently required by any agentized group.  Do you wish to consider\
3600  deleting them?")))
3601           (while to-remove
3602             (let ((dir (pop to-remove)))
3603               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3604                   (let* (delete-recursive
3605                          (delete-recursive
3606                           (function
3607                            (lambda (f-or-d)
3608                              (ignore-errors
3609                                (if (file-directory-p f-or-d)
3610                                    (condition-case nil
3611                                        (delete-directory f-or-d)
3612                                      (file-error
3613                                       (mapcar (lambda (f)
3614                                                 (or (member f '("." ".."))
3615                                                     (funcall delete-recursive
3616                                                              (nnheader-concat
3617                                                               f-or-d f))))
3618                                               (directory-files f-or-d))
3619                                       (delete-directory f-or-d)))
3620                                  (delete-file f-or-d)))))))
3621                     (funcall delete-recursive dir))))))))))
3622
3623 ;;;###autoload
3624 (defun gnus-agent-batch ()
3625   "Start Gnus, send queue and fetch session."
3626   (interactive)
3627   (let ((init-file-user "")
3628         (gnus-always-read-dribble-file t))
3629     (gnus))
3630   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3631     (gnus-group-send-queue)
3632     (gnus-agent-fetch-session)))
3633
3634 (defun gnus-agent-unread-articles (group)
3635   (let* ((read (gnus-info-read (gnus-get-info group)))
3636          (known (gnus-agent-load-alist group))
3637          (unread (list nil))
3638          (tail-unread unread))
3639     (while (and known read)
3640       (let ((candidate (car (pop known))))
3641         (while (let* ((range (car read))
3642                       (min   (if (numberp range) range (car range)))
3643                       (max   (if (numberp range) range (cdr range))))
3644                  (cond ((or (not min)
3645                             (< candidate min))
3646                         (gnus-agent-append-to-list tail-unread candidate)
3647                         nil)
3648                        ((> candidate max)
3649                         (setq read (cdr read))
3650                         ;; return t so that I always loop one more
3651                         ;; time.  If I just iterated off the end of
3652                         ;; read, min will become nil and the current
3653                         ;; candidate will be added to the unread list.
3654                         t))))))
3655     (while known
3656       (gnus-agent-append-to-list tail-unread (car (pop known))))
3657     (cdr unread)))
3658
3659 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3660   "Restrict ARTICLES to numbers already fetched.
3661 Returns a sublist of ARTICLES that excludes those article ids in GROUP
3662 that have already been fetched.
3663 If CACHED-HEADER is nil, articles are only excluded if the article itself
3664 has been fetched."
3665
3666   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3667   ;; 'car gnus-agent-article-alist))
3668
3669   ;; Functionally, I don't need to construct a temp list using mapcar.
3670
3671   (if (and (or gnus-agent-cache (not gnus-plugged))
3672            (gnus-agent-load-alist group))
3673     (let* ((ref gnus-agent-article-alist)
3674            (arts articles)
3675            (uncached (list nil))
3676            (tail-uncached uncached))
3677       (while (and ref arts)
3678         (let ((v1 (car arts))
3679               (v2 (caar ref)))
3680           (cond ((< v1 v2) ; v1 does not appear in the reference list
3681                  (gnus-agent-append-to-list tail-uncached v1)
3682                  (setq arts (cdr arts)))
3683                 ((= v1 v2)
3684                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3685                    (gnus-agent-append-to-list tail-uncached v1))
3686                  (setq arts (cdr arts))
3687                  (setq ref (cdr ref)))
3688                 (t ; reference article (v2) preceeds the list being filtered
3689                  (setq ref (cdr ref))))))
3690       (while arts
3691         (gnus-agent-append-to-list tail-uncached (pop arts)))
3692       (cdr uncached))
3693     ;; if gnus-agent-load-alist fails, no articles are cached.
3694     articles))
3695
3696 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3697   (save-excursion
3698     (gnus-agent-create-buffer)
3699     (let ((gnus-decode-encoded-word-function 'identity)
3700           (file (gnus-agent-article-name ".overview" group))
3701           cached-articles uncached-articles)
3702       (gnus-make-directory (nnheader-translate-file-chars
3703                             (file-name-directory file) t))
3704
3705       ;; Populate temp buffer with known headers
3706       (when (file-exists-p file)
3707         (with-current-buffer gnus-agent-overview-buffer
3708           (erase-buffer)
3709           (let ((nnheader-file-coding-system
3710                  gnus-agent-file-coding-system))
3711             (nnheader-insert-nov-file file (car articles)))))
3712
3713       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3714                                                                 t))
3715           (progn
3716             ;; Populate nntp-server-buffer with uncached headers
3717             (set-buffer nntp-server-buffer)
3718             (erase-buffer)
3719             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3720                                    (gnus-retrieve-headers
3721                                     uncached-articles group fetch-old))))
3722                    (nnvirtual-convert-headers))
3723                   ((eq 'nntp (car gnus-current-select-method))
3724                    ;; The author of gnus-get-newsgroup-headers-xover
3725                    ;; reports that the XOVER command is commonly
3726                    ;; unreliable. The problem is that recently
3727                    ;; posted articles may not be entered into the
3728                    ;; NOV database in time to respond to my XOVER
3729                    ;; query.
3730                    ;;
3731                    ;; I'm going to use his assumption that the NOV
3732                    ;; database is updated in order of ascending
3733                    ;; article ID.  Therefore, a response containing
3734                    ;; article ID N implies that all articles from 1
3735                    ;; to N-1 are up-to-date.  Therefore, missing
3736                    ;; articles in that range have expired.
3737
3738                    (set-buffer nntp-server-buffer)
3739                    (let* ((fetched-articles (list nil))
3740                           (tail-fetched-articles fetched-articles)
3741                           (min (cond ((numberp fetch-old)
3742                                       (max 1 (- (car articles) fetch-old)))
3743                                      (fetch-old
3744                                       1)
3745                                      (t
3746                                       (car articles))))
3747                           (max (car (last articles))))
3748
3749                      ;; Get the list of articles that were fetched
3750                      (goto-char (point-min))
3751                      (let ((pm (point-max))
3752                            art)
3753                        (while (< (point) pm)
3754                          (when (setq art (gnus-agent-read-article-number))
3755                            (gnus-agent-append-to-list tail-fetched-articles art))
3756                          (forward-line 1)))
3757
3758                      ;; Clip this list to the headers that will
3759                      ;; actually be returned
3760                      (setq fetched-articles (gnus-list-range-intersection
3761                                              (cdr fetched-articles)
3762                                              (cons min max)))
3763
3764                      ;; Clip the uncached articles list to exclude
3765                      ;; IDs after the last FETCHED header.  The
3766                      ;; excluded IDs may be fetchable using HEAD.
3767                      (if (car tail-fetched-articles)
3768                          (setq uncached-articles
3769                                (gnus-list-range-intersection
3770                                 uncached-articles
3771                                 (cons (car uncached-articles)
3772                                       (car tail-fetched-articles)))))
3773
3774                      ;; Create the list of articles that were
3775                      ;; "successfully" fetched.  Success, in this
3776                      ;; case, means that the ID should not be
3777                      ;; fetched again.  In the case of an expired
3778                      ;; article, the header will not be fetched.
3779                      (setq uncached-articles
3780                            (gnus-sorted-nunion fetched-articles
3781                                                uncached-articles))
3782                      )))
3783
3784             ;; Erase the temp buffer
3785             (set-buffer gnus-agent-overview-buffer)
3786             (erase-buffer)
3787
3788             ;; Copy the nntp-server-buffer to the temp buffer
3789             (set-buffer nntp-server-buffer)
3790             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3791
3792             ;; Merge the temp buffer with the known headers (found on
3793             ;; disk in FILE) into the nntp-server-buffer
3794             (when uncached-articles
3795               (gnus-agent-braid-nov group uncached-articles file))
3796
3797             ;; Save the new set of known headers to FILE
3798             (set-buffer nntp-server-buffer)
3799             (let ((coding-system-for-write
3800                    gnus-agent-file-coding-system))
3801               (gnus-agent-check-overview-buffer)
3802               (write-region (point-min) (point-max) file nil 'silent))
3803
3804             (gnus-agent-update-view-total-fetched-for group t)
3805
3806             ;; Update the group's article alist to include the newly
3807             ;; fetched articles.
3808             (gnus-agent-load-alist group)
3809             (gnus-agent-save-alist group uncached-articles nil)
3810             )
3811
3812         ;; Copy the temp buffer to the nntp-server-buffer
3813         (set-buffer nntp-server-buffer)
3814         (erase-buffer)
3815         (insert-buffer-substring gnus-agent-overview-buffer)))
3816
3817     (if (and fetch-old
3818              (not (numberp fetch-old)))
3819         t                               ; Don't remove anything.
3820       (nnheader-nov-delete-outside-range
3821        (if fetch-old (max 1 (- (car articles) fetch-old))
3822          (car articles))
3823        (car (last articles)))
3824       t)
3825
3826     'nov))
3827
3828 (defun gnus-agent-request-article (article group)
3829   "Retrieve ARTICLE in GROUP from the agent cache."
3830   (when (and gnus-agent
3831              (or gnus-agent-cache
3832                  (not gnus-plugged))
3833              (numberp article))
3834     (let* ((gnus-command-method (gnus-find-method-for-group group))
3835            (file (gnus-agent-article-name (number-to-string article) group))
3836            (buffer-read-only nil))
3837       (when (and (file-exists-p file)
3838                  (> (nth 7 (file-attributes file)) 0))
3839         (erase-buffer)
3840         (gnus-kill-all-overlays)
3841         (let ((coding-system-for-read gnus-cache-coding-system))
3842           (insert-file-contents file))
3843         t))))
3844
3845 (defun gnus-agent-regenerate-group (group &optional reread)
3846   "Regenerate GROUP.
3847 If REREAD is t, all articles in the .overview are marked as unread.
3848 If REREAD is a list, the specified articles will be marked as unread.
3849 In addition, their NOV entries in .overview will be refreshed using
3850 the articles' current headers.
3851 If REREAD is not nil, downloaded articles are marked as unread."
3852   (interactive
3853    (list (let ((def (or (gnus-group-group-name)
3854                         gnus-newsgroup-name)))
3855            (let ((select (read-string (if def
3856                                           (concat "Group Name ("
3857                                                   def "): ")
3858                                         "Group Name: "))))
3859              (if (and (equal "" select)
3860                       def)
3861                  def
3862                select)))
3863          (catch 'mark
3864            (while (let (c
3865                         (cursor-in-echo-area t)
3866                         (echo-keystrokes 0))
3867                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3868                     (setq c (read-char-exclusive))
3869
3870                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3871                            (throw 'mark nil))
3872                           ((or (eq c ?a) (eq c ?A))
3873                            (throw 'mark t))
3874                           ((or (eq c ?d) (eq c ?D))
3875                            (throw 'mark 'some)))
3876                     (gnus-message 3 "Ignoring unexpected input")
3877                     (sit-for 1)
3878                     t)))))
3879   (when group
3880     (gnus-message 5 "Regenerating in %s" group)
3881     (let* ((gnus-command-method (or gnus-command-method
3882                                     (gnus-find-method-for-group group)))
3883            (file (gnus-agent-article-name ".overview" group))
3884            (dir (file-name-directory file))
3885            point
3886            (downloaded (if (file-exists-p dir)
3887                            (sort (delq nil (mapcar (lambda (name) 
3888                                                      (and (not (file-directory-p (nnheader-concat dir name)))
3889                                                           (string-to-number name)))
3890                                                    (directory-files dir nil "^[0-9]+$" t)))
3891                                  '>)
3892                          (progn (gnus-make-directory dir) nil)))
3893            dl nov-arts
3894            alist header
3895            regenerated)
3896
3897       (mm-with-unibyte-buffer
3898         (if (file-exists-p file)
3899             (let ((nnheader-file-coding-system
3900                    gnus-agent-file-coding-system))
3901               (nnheader-insert-file-contents file)))
3902         (set-buffer-modified-p nil)
3903
3904         ;; Load the article IDs found in the overview file.  As a
3905         ;; side-effect, validate the file contents.
3906         (let ((load t))
3907           (while load
3908             (setq load nil)
3909             (goto-char (point-min))
3910             (while (< (point) (point-max))
3911               (cond ((and (looking-at "[0-9]+\t")
3912                           (<= (- (match-end 0) (match-beginning 0)) 9))
3913                      (push (read (current-buffer)) nov-arts)
3914                      (forward-line 1)
3915                      (let ((l1 (car nov-arts))
3916                            (l2 (cadr nov-arts)))
3917                        (cond ((and (listp reread) (memq l1 reread))
3918                               (gnus-delete-line)
3919                               (setq nov-arts (cdr nov-arts))
3920                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3921  entry of article %s deleted." l1))
3922                              ((not l2)
3923                               nil)
3924                              ((< l1 l2)
3925                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3926  entries are NOT in ascending order.")
3927                               ;; Don't sort now as I haven't verified
3928                               ;; that every line begins with a number
3929                               (setq load t))
3930                              ((= l1 l2)
3931                               (forward-line -1)
3932                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3933  entries contained duplicate of article %s.      Duplicate deleted." l1)
3934                               (gnus-delete-line)
3935                               (setq nov-arts (cdr nov-arts))))))
3936                     (t
3937                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3938  entries contained line that did not begin with an article number.  Deleted\
3939  line.")
3940                      (gnus-delete-line))))
3941             (when load
3942               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3943  entries into ascending order.")
3944               (sort-numeric-fields 1 (point-min) (point-max))
3945               (setq nov-arts nil))))
3946         (gnus-agent-check-overview-buffer)
3947
3948         ;; Construct a new article alist whose nodes match every header
3949         ;; in the .overview file.  As a side-effect, missing headers are
3950         ;; reconstructed from the downloaded article file.
3951         (while (or downloaded nov-arts)
3952           (cond ((and downloaded
3953                       (or (not nov-arts)
3954                           (> (car downloaded) (car nov-arts))))
3955                  ;; This entry is missing from the overview file
3956                  (gnus-message 3 "Regenerating NOV %s %d..." group
3957                                (car downloaded))
3958                  (let ((file (concat dir (number-to-string (car downloaded)))))
3959                    (mm-with-unibyte-buffer
3960                      (nnheader-insert-file-contents file)
3961                      (nnheader-remove-body)
3962                      (setq header (nnheader-parse-naked-head)))
3963                    (mail-header-set-number header (car downloaded))
3964                    (if nov-arts
3965                        (let ((key (concat "^" (int-to-string (car nov-arts))
3966                                           "\t")))
3967                          (or (re-search-backward key nil t)
3968                              (re-search-forward key))
3969                          (forward-line 1))
3970                      (goto-char (point-min)))
3971                    (nnheader-insert-nov header))
3972                  (setq nov-arts (cons (car downloaded) nov-arts)))
3973                 ((eq (car downloaded) (car nov-arts))
3974                  ;; This entry in the overview has been downloaded
3975                  (push (cons (car downloaded)
3976                              (time-to-days
3977                               (nth 5 (file-attributes
3978                                       (concat dir (number-to-string
3979                                                    (car downloaded))))))) alist)
3980                  (setq downloaded (cdr downloaded))
3981                  (setq nov-arts (cdr nov-arts)))
3982                 (t
3983                  ;; This entry in the overview has not been downloaded
3984                  (push (cons (car nov-arts) nil) alist)
3985                  (setq nov-arts (cdr nov-arts)))))
3986
3987         ;; When gnus-agent-consider-all-articles is set,
3988         ;; gnus-agent-regenerate-group should NOT remove article IDs from
3989         ;; the alist.  Those IDs serve as markers to indicate that an
3990         ;; attempt has been made to fetch that article's header.
3991
3992         ;; When gnus-agent-consider-all-articles is NOT set,
3993         ;; gnus-agent-regenerate-group can remove the article ID of every
3994         ;; article (with the exception of the last ID in the list - it's
3995         ;; special) that no longer appears in the overview.  In this
3996         ;; situtation, the last article ID in the list implies that it,
3997         ;; and every article ID preceeding it, have been fetched from the
3998         ;; server.
3999
4000         (if gnus-agent-consider-all-articles
4001             ;; Restore all article IDs that were not found in the overview file.
4002             (let* ((n (cons nil alist))
4003                    (merged n)
4004                    (o (gnus-agent-load-alist group)))
4005               (while o
4006                 (let ((nID (caadr n))
4007                       (oID (caar o)))
4008                   (cond ((not nID)
4009                          (setq n (setcdr n (list (list oID))))
4010                          (setq o (cdr o)))
4011                         ((< oID nID)
4012                          (setcdr n (cons (list oID) (cdr n)))
4013                          (setq o (cdr o)))
4014                         ((= oID nID)
4015                          (setq o (cdr o))
4016                          (setq n (cdr n)))
4017                         (t
4018                          (setq n (cdr n))))))
4019               (setq alist (cdr merged)))
4020           ;; Restore the last article ID if it is not already in the new alist
4021           (let ((n (last alist))
4022                 (o (last (gnus-agent-load-alist group))))
4023             (cond ((not o)
4024                    nil)
4025                   ((not n)
4026                    (push (cons (caar o) nil) alist))
4027                   ((< (caar n) (caar o))
4028                    (setcdr n (list (car o)))))))
4029
4030         (let ((inhibit-quit t))
4031           (if (setq regenerated (buffer-modified-p))
4032               (let ((coding-system-for-write gnus-agent-file-coding-system))
4033                 (write-region (point-min) (point-max) file nil 'silent)))
4034
4035           (setq regenerated (or regenerated
4036                                 (and reread gnus-agent-article-alist)
4037                                 (not (equal alist gnus-agent-article-alist))))
4038
4039           (setq gnus-agent-article-alist alist)
4040
4041           (when regenerated
4042             (gnus-agent-save-alist group)
4043
4044             ;; I have to alter the group's active range NOW as
4045             ;; gnus-make-ascending-articles-unread will use it to
4046             ;; recalculate the number of unread articles in the group
4047
4048             (let ((group (gnus-group-real-name group))
4049                   (group-active (or (gnus-active group)
4050                                     (gnus-activate-group group))))
4051               (gnus-agent-possibly-alter-active group group-active)))))
4052
4053       (when (and reread gnus-agent-article-alist)
4054         (gnus-agent-synchronize-group-flags 
4055          group 
4056          (list (list
4057                 (if (listp reread)
4058                     reread
4059                   (delq nil (mapcar (function (lambda (c)
4060                                                 (cond ((eq reread t)
4061                                                        (car c))
4062                                                       ((cdr c)
4063                                                        (car c)))))
4064                                     gnus-agent-article-alist)))
4065                 'del '(read)))
4066          gnus-command-method)
4067
4068         (when regenerated
4069           (gnus-agent-update-files-total-fetched-for group nil)))
4070
4071       (gnus-message 5 "")
4072       regenerated)))
4073
4074 ;;;###autoload
4075 (defun gnus-agent-regenerate (&optional clean reread)
4076   "Regenerate all agent covered files.
4077 If CLEAN, obsolete (ignore)."
4078   (interactive "P")
4079   (let (regenerated)
4080     (gnus-message 4 "Regenerating Gnus agent files...")
4081     (dolist (gnus-command-method (gnus-agent-covered-methods))
4082         (dolist (group (gnus-groups-from-server gnus-command-method))
4083           (setq regenerated (or (gnus-agent-regenerate-group group reread)
4084                                 regenerated))))
4085     (gnus-message 4 "Regenerating Gnus agent files...done")
4086
4087     regenerated))
4088
4089 (defun gnus-agent-go-online (&optional force)
4090   "Switch servers into online status."
4091   (interactive (list t))
4092   (dolist (server gnus-opened-servers)
4093     (when (eq (nth 1 server) 'offline)
4094       (if (if (eq force 'ask)
4095               (gnus-y-or-n-p
4096                (format "Switch %s:%s into online status? "
4097                        (caar server) (cadar server)))
4098             force)
4099           (setcar (nthcdr 1 server) 'close)))))
4100
4101 (defun gnus-agent-toggle-group-plugged (group)
4102   "Toggle the status of the server of the current group."
4103   (interactive (list (gnus-group-group-name)))
4104   (let* ((method (gnus-find-method-for-group group))
4105          (status (cadr (assoc method gnus-opened-servers))))
4106     (if (eq status 'offline)
4107         (gnus-server-set-status method 'closed)
4108       (gnus-close-server method)
4109       (gnus-server-set-status method 'offline))
4110     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
4111              (if (eq status 'offline) 'offline 'online)
4112              (if (eq status 'offline) 'online 'offline))))
4113
4114 (defun gnus-agent-group-covered-p (group)
4115   (gnus-agent-method-p (gnus-group-method group)))
4116
4117 (defun gnus-agent-update-files-total-fetched-for
4118   (group delta &optional method path)
4119   "Update, or set, the total disk space used by the articles that the
4120 agent has fetched."
4121   (when gnus-agent-total-fetched-hashtb
4122     (gnus-agent-with-refreshed-group
4123      group
4124      ;; if null, gnus-agent-group-pathname will calc method.
4125      (let* ((gnus-command-method method)
4126             (path (or path (gnus-agent-group-pathname group)))
4127             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4128                        (gnus-sethash path (make-list 3 0)
4129                                      gnus-agent-total-fetched-hashtb))))
4130        (when (listp delta)
4131          (if delta
4132              (let ((sum 0.0)
4133                    file)
4134                (while (setq file (pop delta))
4135                  (incf sum (float (or (nth 7 (file-attributes
4136                                               (nnheader-concat
4137                                                path
4138                                                (if (numberp file)
4139                                                    (number-to-string file)
4140                                                  file)))) 0))))
4141                (setq delta sum))
4142            (let ((sum (- (nth 2 entry)))
4143                  (info (directory-files-and-attributes path nil "^-?[0-9]+$" t))
4144                  file)
4145              (while (setq file (pop info))
4146                (incf sum (float (or (nth 8 file) 0))))
4147              (setq delta sum))))
4148
4149        (setq gnus-agent-need-update-total-fetched-for t)
4150        (incf (nth 2 entry) delta)))))
4151
4152 (defun gnus-agent-update-view-total-fetched-for
4153   (group agent-over &optional method path)
4154   "Update, or set, the total disk space used by the .agentview and
4155 .overview files.  These files are calculated separately as they can be
4156 modified."
4157   (when gnus-agent-total-fetched-hashtb
4158     (gnus-agent-with-refreshed-group
4159      group
4160      ;; if null, gnus-agent-group-pathname will calc method.
4161      (let* ((gnus-command-method method)
4162             (path (or path (gnus-agent-group-pathname group)))
4163             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4164                        (gnus-sethash path (make-list 3 0)
4165                                      gnus-agent-total-fetched-hashtb)))
4166             (size (or (nth 7 (file-attributes
4167                               (nnheader-concat
4168                                path (if agent-over
4169                                         ".overview"
4170                                       ".agentview"))))
4171                       0)))
4172        (setq gnus-agent-need-update-total-fetched-for t)
4173        (setf (nth (if agent-over 1 0) entry) size)))))
4174
4175 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
4176   "Get the total disk space used by the specified GROUP."
4177   (unless (equal group "dummy.group")
4178     (unless gnus-agent-total-fetched-hashtb
4179       (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
4180
4181     ;; if null, gnus-agent-group-pathname will calc method.
4182     (let* ((gnus-command-method method)
4183            (path (gnus-agent-group-pathname group))
4184            (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
4185       (if entry
4186           (apply '+ entry)
4187         (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
4188           (+
4189            (gnus-agent-update-view-total-fetched-for  group nil method path)
4190            (gnus-agent-update-view-total-fetched-for  group t   method path)
4191            (gnus-agent-update-files-total-fetched-for group nil method path)))))))
4192
4193 (provide 'gnus-agent)
4194
4195 ;;; arch-tag: b0ba4afc-5229-4cee-ad25-9956daa4e91e
4196 ;;; gnus-agent.el ends here