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