d2dd0552b50c6f8626dadcd0a1259edbfcdcb5d2
[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
1455      (gnus-group-real-name
1456       (mm-decode-coding-string
1457        group (gnus-group-name-charset gnus-command-method group)))
1458      (gnus-agent-directory))))
1459
1460 (defun gnus-agent-get-function (method)
1461   (if (gnus-online method)
1462       (car method)
1463     (require 'nnagent)
1464     'nnagent))
1465
1466 (defun gnus-agent-covered-methods ()
1467   "Return the subset of methods that are covered by the agent."
1468   (delq nil (mapcar #'gnus-server-to-method gnus-agent-covered-methods)))
1469
1470 ;;; History functions
1471
1472 (defun gnus-agent-history-buffer ()
1473   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1474
1475 (defun gnus-agent-open-history ()
1476   (save-excursion
1477     (push (cons (gnus-agent-method)
1478                 (set-buffer (gnus-get-buffer-create
1479                              (format " *Gnus agent %s history*"
1480                                      (gnus-agent-method)))))
1481           gnus-agent-history-buffers)
1482     (mm-disable-multibyte) ;; everything is binary
1483     (erase-buffer)
1484     (insert "\n")
1485     (let ((file (gnus-agent-lib-file "history")))
1486       (when (file-exists-p file)
1487         (nnheader-insert-file-contents file))
1488       (set (make-local-variable 'gnus-agent-file-name) file))))
1489
1490 (defun gnus-agent-close-history ()
1491   (when (gnus-buffer-live-p gnus-agent-current-history)
1492     (kill-buffer gnus-agent-current-history)
1493     (setq gnus-agent-history-buffers
1494           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1495                 gnus-agent-history-buffers))))
1496
1497 ;;;
1498 ;;; Fetching
1499 ;;;
1500
1501 (defun gnus-agent-fetch-articles (group articles)
1502   "Fetch ARTICLES from GROUP and put them into the Agent."
1503   (when articles
1504     (gnus-agent-load-alist group)
1505     (let* ((alist   gnus-agent-article-alist)
1506            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1507            (selected-sets (list nil))
1508            (current-set-size 0)
1509            article
1510            header-number)
1511       ;; Check each article
1512       (while (setq article (pop articles))
1513         ;; Skip alist entries preceeding this article
1514         (while (> article (or (caar alist) (1+ article)))
1515           (setq alist (cdr alist)))
1516
1517         ;; Prune off articles that we have already fetched.
1518         (unless (and (eq article (caar alist))
1519                      (cdar alist))
1520           ;; Skip headers preceeding this article
1521           (while (> article
1522                     (setq header-number
1523                           (let* ((header (car headers)))
1524                             (if header
1525                                 (mail-header-number header)
1526                               (1+ article)))))
1527             (setq headers (cdr headers)))
1528
1529           ;; Add this article to the current set
1530           (setcar selected-sets (cons article (car selected-sets)))
1531
1532           ;; Update the set size, when the set is too large start a
1533           ;; new one.  I do this after adding the article as I want at
1534           ;; least one article in each set.
1535           (when (< gnus-agent-max-fetch-size
1536                    (setq current-set-size
1537                          (+ current-set-size
1538                             (if (= header-number article)
1539                                 (let ((char-size (mail-header-chars
1540                                                   (car headers))))
1541                                   (if (<= char-size 0)
1542                                       ;; The char size was missing/invalid,
1543                                       ;; assume a worst-case situation of
1544                                       ;; 65 char/line.  If the line count
1545                                       ;; is missing, arbitrarily assume a
1546                                       ;; size of 1000 characters.
1547                                     (max (* 65 (mail-header-lines
1548                                                 (car headers)))
1549                                          1000)
1550                                     char-size))
1551                               0))))
1552             (setcar selected-sets (nreverse (car selected-sets)))
1553             (setq selected-sets (cons nil selected-sets)
1554                   current-set-size 0))))
1555
1556       (when (or (cdr selected-sets) (car selected-sets))
1557         (let* ((fetched-articles (list nil))
1558                (tail-fetched-articles fetched-articles)
1559                (dir (gnus-agent-group-pathname group))
1560                (date (time-to-days (current-time)))
1561                (case-fold-search t)
1562                pos crosses id
1563                (file-name-coding-system nnmail-pathname-coding-system))
1564
1565           (setcar selected-sets (nreverse (car selected-sets)))
1566           (setq selected-sets (nreverse selected-sets))
1567
1568           (gnus-make-directory dir)
1569           (gnus-message 7 "Fetching articles for %s..." group)
1570
1571           (unwind-protect
1572               (while (setq articles (pop selected-sets))
1573                 ;; Fetch the articles from the backend.
1574                 (if (gnus-check-backend-function 'retrieve-articles group)
1575                     (setq pos (gnus-retrieve-articles articles group))
1576                   (with-temp-buffer
1577                     (let (article)
1578                       (while (setq article (pop articles))
1579                         (gnus-message 10 "Fetching article %s for %s..."
1580                                       article group)
1581                         (when (or
1582                                (gnus-backlog-request-article group article
1583                                                              nntp-server-buffer)
1584                                (gnus-request-article article group))
1585                           (goto-char (point-max))
1586                           (push (cons article (point)) pos)
1587                           (insert-buffer-substring nntp-server-buffer)))
1588                       (copy-to-buffer
1589                        nntp-server-buffer (point-min) (point-max))
1590                       (setq pos (nreverse pos)))))
1591                 ;; Then save these articles into the Agent.
1592                 (save-excursion
1593                   (set-buffer nntp-server-buffer)
1594                   (while pos
1595                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1596                     (goto-char (point-min))
1597                     (unless (eobp) ;; Don't save empty articles.
1598                       (when (search-forward "\n\n" nil t)
1599                         (when (search-backward "\nXrefs: " nil t)
1600                           ;; Handle cross posting.
1601                           (goto-char (match-end 0)) ; move to end of header name
1602                           (skip-chars-forward "^ ") ; skip server name
1603                           (skip-chars-forward " ")
1604                           (setq crosses nil)
1605                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1606                             (push (cons (buffer-substring (match-beginning 1)
1607                                                           (match-end 1))
1608                                         (string-to-number
1609                                          (buffer-substring (match-beginning 2)
1610                                                            (match-end 2))))
1611                                   crosses)
1612                             (goto-char (match-end 0)))
1613                           (gnus-agent-crosspost crosses (caar pos) date)))
1614                       (goto-char (point-min))
1615                       (if (not (re-search-forward
1616                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1617                           (setq id "No-Message-ID-in-article")
1618                         (setq id (buffer-substring
1619                                   (match-beginning 1) (match-end 1))))
1620                       (let ((coding-system-for-write
1621                              gnus-agent-file-coding-system))
1622                         (write-region (point-min) (point-max)
1623                                       (concat dir (number-to-string (caar pos)))
1624                                       nil 'silent))
1625
1626                       (gnus-agent-append-to-list
1627                        tail-fetched-articles (caar pos)))
1628                     (widen)
1629                     (setq pos (cdr pos)))))
1630
1631             (gnus-agent-save-alist group (cdr fetched-articles) date)
1632             (gnus-agent-update-files-total-fetched-for group (cdr fetched-articles))
1633
1634             (gnus-message 7 ""))
1635           (cdr fetched-articles))))))
1636
1637 (defun gnus-agent-unfetch-articles (group articles)
1638   "Delete ARTICLES that were fetched from GROUP into the agent."
1639   (when articles
1640     (gnus-agent-with-refreshed-group
1641      group
1642      (gnus-agent-load-alist group)
1643      (let* ((alist (cons nil gnus-agent-article-alist))
1644             (articles (sort articles #'<))
1645             (next-possibility alist)
1646             (delete-this (pop articles)))
1647        (while (and (cdr next-possibility) delete-this)
1648          (let ((have-this (caar (cdr next-possibility))))
1649            (cond
1650             ((< delete-this have-this)
1651              (setq delete-this (pop articles)))
1652             ((= delete-this have-this)
1653              (let ((timestamp (cdar (cdr next-possibility))))
1654                (when timestamp
1655                  (let* ((file-name (concat (gnus-agent-group-pathname group)
1656                                            (number-to-string have-this)))
1657                         (size-file
1658                          (float (or (and gnus-agent-total-fetched-hashtb
1659                                          (nth 7 (file-attributes file-name)))
1660                                     0)))
1661                         (file-name-coding-system
1662                          nnmail-pathname-coding-system))
1663                    (delete-file file-name)
1664                    (gnus-agent-update-files-total-fetched-for
1665                     group (- size-file)))))
1666
1667              (setcdr next-possibility (cddr next-possibility)))
1668             (t
1669              (setq next-possibility (cdr next-possibility))))))
1670        (setq gnus-agent-article-alist (cdr alist))
1671        (gnus-agent-save-alist group)))))
1672
1673 (defun gnus-agent-crosspost (crosses article &optional date)
1674   (setq date (or date t))
1675
1676   (let (gnus-agent-article-alist group alist beg end)
1677     (save-excursion
1678       (set-buffer gnus-agent-overview-buffer)
1679       (when (nnheader-find-nov-line article)
1680         (forward-word 1)
1681         (setq beg (point))
1682         (setq end (progn (forward-line 1) (point)))))
1683     (while crosses
1684       (setq group (caar crosses))
1685       (unless (setq alist (assoc group gnus-agent-group-alist))
1686         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1687               gnus-agent-group-alist))
1688       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1689       (save-excursion
1690         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1691                                                     group)))
1692         (when (= (point-max) (point-min))
1693           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1694           (ignore-errors
1695            (let ((file-name-coding-system nnmail-pathname-coding-system))
1696              (nnheader-insert-file-contents
1697               (gnus-agent-article-name ".overview" group)))))
1698         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1699         (insert (string-to-number (cdar crosses)))
1700         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1701         (gnus-agent-check-overview-buffer))
1702       (setq crosses (cdr crosses)))))
1703
1704 (defun gnus-agent-backup-overview-buffer ()
1705   (when gnus-newsgroup-name
1706     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1707           (cnt 0)
1708           name
1709           (file-name-coding-system nnmail-pathname-coding-system))
1710       (while (file-exists-p
1711               (setq name (concat root "~"
1712                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1713       (write-region (point-min) (point-max) name nil 'no-msg)
1714       (gnus-message 1 "Created backup copy of overview in %s." name)))
1715   t)
1716
1717 (defun gnus-agent-check-overview-buffer (&optional buffer)
1718   "Check the overview file given for sanity.
1719 In particular, checks that the file is sorted by article number
1720 and that there are no duplicates."
1721   (let ((prev-num -1)
1722         (backed-up nil))
1723     (save-excursion
1724       (when buffer
1725         (set-buffer buffer))
1726       (save-restriction
1727         (widen)
1728         (goto-char (point-min))
1729
1730         (while (< (point) (point-max))
1731           (let ((p (point))
1732                 (cur (condition-case nil
1733                          (read (current-buffer))
1734                        (error nil))))
1735             (cond
1736              ((or (not (integerp cur))
1737                   (not (eq (char-after) ?\t)))
1738               (or backed-up
1739                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1740               (gnus-message 1
1741                             "Overview buffer contains garbage '%s'."
1742                             (buffer-substring
1743                              p (point-at-eol))))
1744              ((= cur prev-num)
1745               (or backed-up
1746                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1747               (gnus-message 1
1748                             "Duplicate overview line for %d" cur)
1749               (delete-region p (progn (forward-line 1) (point))))
1750              ((< cur prev-num)
1751               (or backed-up
1752                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1753               (gnus-message 1 "Overview buffer not sorted!")
1754               (sort-numeric-fields 1 (point-min) (point-max))
1755               (goto-char (point-min))
1756               (setq prev-num -1))
1757              (t
1758               (setq prev-num cur)))
1759             (forward-line 1)))))))
1760
1761 (defun gnus-agent-flush-server (&optional server-or-method)
1762   "Flush all agent index files for every subscribed group within
1763   the given SERVER-OR-METHOD.  When called with nil, the current
1764   value of gnus-command-method identifies the server."
1765   (let* ((gnus-command-method (if server-or-method
1766                                   (gnus-server-to-method server-or-method)
1767                                 gnus-command-method))
1768          (alist gnus-newsrc-alist))
1769     (while alist
1770       (let ((entry (pop alist)))
1771         (when (gnus-methods-equal-p gnus-command-method (gnus-info-method entry))
1772           (gnus-agent-flush-group (gnus-info-group entry))))))) 
1773
1774 (defun gnus-agent-flush-group (group)
1775   "Flush the agent's index files such that the GROUP no longer
1776 appears to have any local content.  The actual content, the
1777 article files, may then be deleted using gnus-agent-expire-group.
1778 If flushing was a mistake, the gnus-agent-regenerate-group method
1779 provides an undo mechanism by reconstructing the index files from
1780 the article files."
1781   (interactive
1782    (list (let ((def (or (gnus-group-group-name)
1783                         gnus-newsgroup-name)))
1784            (let ((select (read-string (if def
1785                                           (concat "Group Name ("
1786                                                   def "): ")
1787                                         "Group Name: "))))
1788              (if (and (equal "" select)
1789                       def)
1790                  def
1791                select)))))
1792
1793   (let* ((gnus-command-method (or gnus-command-method
1794                                   (gnus-find-method-for-group group)))
1795          (overview (gnus-agent-article-name ".overview" group))
1796          (agentview (gnus-agent-article-name ".agentview" group))
1797          (file-name-coding-system nnmail-pathname-coding-system))
1798
1799     (if (file-exists-p overview)
1800         (delete-file overview))
1801     (if (file-exists-p agentview)
1802         (delete-file agentview))
1803
1804     (gnus-agent-update-view-total-fetched-for group nil gnus-command-method)
1805     (gnus-agent-update-view-total-fetched-for group t   gnus-command-method)
1806
1807     ;(gnus-agent-set-local group nil nil)
1808     ;(gnus-agent-save-local t)
1809     (gnus-agent-save-group-info nil group nil)))
1810
1811 (defun gnus-agent-flush-cache ()
1812   "Flush the agent's index files such that the group no longer
1813 appears to have any local content.  The actual content, the
1814 article files, is then deleted using gnus-agent-expire-group. The
1815 gnus-agent-regenerate-group method provides an undo mechanism by
1816 reconstructing the index files from the article files."
1817   (save-excursion
1818     (let ((file-name-coding-system nnmail-pathname-coding-system))
1819       (while gnus-agent-buffer-alist
1820         (set-buffer (cdar gnus-agent-buffer-alist))
1821         (let ((coding-system-for-write gnus-agent-file-coding-system))
1822           (write-region (point-min) (point-max)
1823                         (gnus-agent-article-name ".overview"
1824                                                  (caar gnus-agent-buffer-alist))
1825                         nil 'silent))
1826         (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1827       (while gnus-agent-group-alist
1828         (with-temp-file (gnus-agent-article-name
1829                          ".agentview" (caar gnus-agent-group-alist))
1830           (princ (cdar gnus-agent-group-alist))
1831           (insert "\n")
1832           (princ 1 (current-buffer))
1833           (insert "\n"))
1834         (setq gnus-agent-group-alist (cdr gnus-agent-group-alist))))))
1835
1836 ;;;###autoload
1837 (defun gnus-agent-find-parameter (group symbol)
1838   "Search for GROUPs SYMBOL in the group's parameters, the group's
1839 topic parameters, the group's category, or the customizable
1840 variables.  Returns the first non-nil value found."
1841   (or (gnus-group-find-parameter group symbol t)
1842       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1843       (symbol-value
1844        (cdr
1845         (assq symbol
1846               '((agent-short-article . gnus-agent-short-article)
1847                 (agent-long-article . gnus-agent-long-article)
1848                 (agent-low-score . gnus-agent-low-score)
1849                 (agent-high-score . gnus-agent-high-score)
1850                 (agent-days-until-old . gnus-agent-expire-days)
1851                 (agent-enable-expiration
1852                  . gnus-agent-enable-expiration)
1853                 (agent-predicate . gnus-agent-predicate)))))))
1854
1855 (defun gnus-agent-fetch-headers (group &optional force)
1856   "Fetch interesting headers into the agent.  The group's overview
1857 file will be updated to include the headers while a list of available
1858 article numbers will be returned."
1859   (let* ((fetch-all (and gnus-agent-consider-all-articles
1860                          ;; Do not fetch all headers if the predicate
1861                          ;; implies that we only consider unread articles.
1862                          (not (gnus-predicate-implies-unread
1863                                (gnus-agent-find-parameter group
1864                                                           'agent-predicate)))))
1865          (articles (if fetch-all
1866                        (gnus-uncompress-range (gnus-active group))
1867                      (gnus-list-of-unread-articles group)))
1868          (gnus-decode-encoded-word-function 'identity)
1869          (gnus-decode-encoded-address-function 'identity)
1870          (file (gnus-agent-article-name ".overview" group))
1871          (file-name-coding-system nnmail-pathname-coding-system))
1872
1873     (unless fetch-all
1874       ;; Add articles with marks to the list of article headers we want to
1875       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1876       ;; mark, but do fetch recent or seen articles if they have other, more
1877       ;; interesting marks.  (We have to fetch articles with boring marks
1878       ;; because otherwise the agent will remove their marks.)
1879       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1880         (unless (memq (car arts) '(seen recent killed cache))
1881           (setq articles (gnus-range-add articles (cdr arts)))))
1882       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1883
1884     ;; At this point, I have the list of articles to consider for
1885     ;; fetching.  This is the list that I'll return to my caller. Some
1886     ;; of these articles may have already been fetched.  That's OK as
1887     ;; the fetch article code will filter those out.  Internally, I'll
1888     ;; filter this list to just those articles whose headers need to
1889     ;; be fetched.
1890     (let ((articles articles))
1891       ;; Remove known articles.
1892       (when (and (or gnus-agent-cache
1893                      (not gnus-plugged))
1894                  (gnus-agent-load-alist group))
1895         ;; Remove articles marked as downloaded.
1896         (if fetch-all
1897             ;; I want to fetch all headers in the active range.
1898             ;; Therefore, exclude only those headers that are in the
1899             ;; article alist.
1900             ;; NOTE: This is probably NOT what I want to do after
1901             ;; agent expiration in this group.
1902             (setq articles (gnus-agent-uncached-articles articles group))
1903
1904           ;; I want to only fetch those headers that have never been
1905           ;; fetched.  Therefore, exclude all headers that are, or
1906           ;; WERE, in the article alist.
1907           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1908                 (high (cdr (gnus-active group))))
1909             ;; Low can be greater than High when the same group is
1910             ;; fetched twice in the same session {The first fetch will
1911             ;; fill the article alist such that (last
1912             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1913             ;; group))}.  The addition of one(the 1+ above) then
1914             ;; forces Low to be greater than High.  When this happens,
1915             ;; gnus-list-range-intersection returns nil which
1916             ;; indicates that no headers need to be fetched. -- Kevin
1917             (setq articles (gnus-list-range-intersection
1918                             articles (list (cons low high)))))))
1919
1920       (gnus-message
1921        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1922        (gnus-compress-sequence articles t))
1923
1924       (save-excursion
1925         (set-buffer nntp-server-buffer)
1926
1927         (if articles
1928             (progn
1929               (gnus-message 7 "Fetching headers for %s..." group)
1930
1931               ;; Fetch them.
1932               (gnus-make-directory (nnheader-translate-file-chars
1933                                     (file-name-directory file) t))
1934
1935               (unless (eq 'nov (gnus-retrieve-headers articles group))
1936                 (nnvirtual-convert-headers))
1937               (gnus-agent-check-overview-buffer)
1938               ;; Move these headers to the overview buffer so that
1939               ;; gnus-agent-braid-nov can merge them with the contents
1940               ;; of FILE.
1941               (copy-to-buffer
1942                gnus-agent-overview-buffer (point-min) (point-max))
1943               ;; NOTE: Call g-a-brand-nov even when the file does not
1944               ;; exist.  As a minimum, it will validate the article
1945               ;; numbers already in the buffer.
1946               (gnus-agent-braid-nov group articles file)
1947               (let ((coding-system-for-write
1948                      gnus-agent-file-coding-system))
1949                 (gnus-agent-check-overview-buffer)
1950                 (write-region (point-min) (point-max) file nil 'silent))
1951               (gnus-agent-update-view-total-fetched-for group t)
1952               (gnus-agent-save-alist group articles nil)
1953               articles)
1954           (ignore-errors
1955             (erase-buffer)
1956             (nnheader-insert-file-contents file)))))
1957     articles))
1958
1959 (defsubst gnus-agent-read-article-number ()
1960   "Reads the article number at point.  Returns nil when a valid article number can not be read."
1961
1962   ;; It is unfortunate but the read function quietly overflows
1963   ;; integer.  As a result, I have to use string operations to test
1964   ;; for overflow BEFORE calling read.
1965   (when (looking-at "[0-9]+\t")
1966     (let ((len (- (match-end 0) (match-beginning 0))))
1967       (cond ((< len 9)
1968              (read (current-buffer)))
1969             ((= len 9)
1970              ;; Many 9 digit base-10 numbers can be represented in a 27-bit int
1971              ;; Back convert from int to string to ensure that this is one of them.
1972              (let* ((str1 (buffer-substring (match-beginning 0) (1- (match-end 0))))
1973                     (num (read (current-buffer)))
1974                     (str2 (int-to-string num)))
1975                (when (equal str1 str2)
1976                  num)))))))
1977
1978 (defsubst gnus-agent-copy-nov-line (article)
1979   "Copy the indicated ARTICLE from the overview buffer to the nntp server buffer."
1980   (let (art b e)
1981     (set-buffer gnus-agent-overview-buffer)
1982     (while (and (not (eobp))
1983                 (or (not (setq art (gnus-agent-read-article-number)))
1984                     (< art article)))
1985       (forward-line 1))
1986     (beginning-of-line)
1987     (if (or (eobp)
1988             (not (eq article art)))
1989         (set-buffer nntp-server-buffer)
1990       (setq b (point))
1991       (setq e (progn (forward-line 1) (point)))
1992       (set-buffer nntp-server-buffer)
1993       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1994
1995 (defun gnus-agent-braid-nov (group articles file)
1996   "Merge agent overview data with given file.
1997 Takes unvalidated headers for ARTICLES from
1998 `gnus-agent-overview-buffer' and validated headers from the given
1999 FILE and places the combined valid headers into
2000 `nntp-server-buffer'.  This function can be used, when file
2001 doesn't exist, to valid the overview buffer."
2002   (let (start last)
2003     (set-buffer gnus-agent-overview-buffer)
2004     (goto-char (point-min))
2005     (set-buffer nntp-server-buffer)
2006     (erase-buffer)
2007     (when (file-exists-p file)
2008       (nnheader-insert-file-contents file))
2009     (goto-char (point-max))
2010     (forward-line -1)
2011
2012     (unless (or (= (point-min) (point-max))
2013                 (< (setq last (read (current-buffer))) (car articles)))
2014       ;; Old and new overlap -- We do it the hard way.
2015       (when (nnheader-find-nov-line (car articles))
2016         ;; Replacing existing NOV entry
2017         (delete-region (point) (progn (forward-line 1) (point))))
2018       (gnus-agent-copy-nov-line (pop articles))
2019
2020       (ignore-errors
2021         (while articles
2022           (while (let ((art (read (current-buffer))))
2023                    (cond ((< art (car articles))
2024                           (forward-line 1)
2025                           t)
2026                          ((= art (car articles))
2027                           (beginning-of-line)
2028                           (delete-region
2029                            (point) (progn (forward-line 1) (point)))
2030                           nil)
2031                          (t
2032                           (beginning-of-line)
2033                           nil))))
2034
2035           (gnus-agent-copy-nov-line (pop articles)))))
2036
2037     (goto-char (point-max))
2038
2039     ;; Append the remaining lines
2040     (when articles
2041       (when last
2042         (set-buffer gnus-agent-overview-buffer)
2043         (setq start (point))
2044         (set-buffer nntp-server-buffer))
2045
2046       (let ((p (point)))
2047         (insert-buffer-substring gnus-agent-overview-buffer start)
2048         (goto-char p))
2049
2050       (setq last (or last -134217728))
2051       (while (catch 'problems
2052                (let (sort art)
2053                  (while (not (eobp))
2054                    (setq art (gnus-agent-read-article-number))
2055                    (cond ((not art)
2056                           ;; Bad art num - delete this line
2057                           (beginning-of-line)
2058                           (delete-region (point) (progn (forward-line 1) (point))))
2059                          ((< art last)
2060                           ;; Art num out of order - enable sort
2061                           (setq sort t)
2062                           (forward-line 1))
2063                          ((= art last)
2064                           ;; Bad repeat of art number - delete this line
2065                           (beginning-of-line)
2066                           (delete-region (point) (progn (forward-line 1) (point))))
2067                          (t
2068                           ;; Good art num
2069                           (setq last art)
2070                           (forward-line 1))))
2071                  (when sort
2072                    ;; something is seriously wrong as we simply shouldn't see out-of-order data.
2073                    ;; First, we'll fix the sort.
2074                    (sort-numeric-fields 1 (point-min) (point-max))
2075
2076                    ;; but now we have to consider that we may have duplicate rows...
2077                    ;; so reset to beginning of file
2078                    (goto-char (point-min))
2079                    (setq last -134217728)
2080
2081                    ;; and throw a code that restarts this scan
2082                    (throw 'problems t))
2083                  nil))))))
2084
2085 ;; Keeps the compiler from warning about the free variable in
2086 ;; gnus-agent-read-agentview.
2087 (eval-when-compile
2088   (defvar gnus-agent-read-agentview))
2089
2090 (defun gnus-agent-load-alist (group)
2091   "Load the article-state alist for GROUP."
2092   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
2093   (let ((gnus-agent-read-agentview group)
2094         (file-name-coding-system nnmail-pathname-coding-system))
2095     (setq gnus-agent-article-alist
2096           (gnus-cache-file-contents
2097            (gnus-agent-article-name ".agentview" group)
2098            'gnus-agent-file-loading-cache
2099            'gnus-agent-read-agentview))))
2100
2101 (defun gnus-agent-read-agentview (file)
2102   "Load FILE and do a `read' there."
2103   (with-temp-buffer
2104     (condition-case nil
2105         (progn
2106           (nnheader-insert-file-contents file)
2107           (goto-char (point-min))
2108           (let ((alist (read (current-buffer)))
2109                 (version (condition-case nil (read (current-buffer))
2110                            (end-of-file 0)))
2111                 changed-version)
2112
2113             (cond
2114              ((= version 0)
2115               (let ((inhibit-quit t)
2116                     entry)
2117                 (gnus-agent-open-history)
2118                 (set-buffer (gnus-agent-history-buffer))
2119                 (goto-char (point-min))
2120                 (while (not (eobp))
2121                   (if (and (looking-at
2122                             "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
2123                            (string= (match-string 2)
2124                                     gnus-agent-read-agentview)
2125                            (setq entry (assoc (string-to-number (match-string 3)) alist)))
2126                       (setcdr entry (string-to-number (match-string 1))))
2127                   (forward-line 1))
2128                 (gnus-agent-close-history)
2129                 (setq changed-version t)))
2130              ((= version 1)
2131               (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
2132              ((= version 2)
2133               (let (uncomp)
2134                 (mapcar
2135                  (lambda (comp-list)
2136                    (let ((state (car comp-list))
2137                          (sequence (inline
2138                                      (gnus-uncompress-range
2139                                       (cdr comp-list)))))
2140                      (mapcar (lambda (article-id)
2141                                (setq uncomp (cons (cons article-id state) uncomp)))
2142                              sequence)))
2143                  alist)
2144                 (setq alist (sort uncomp 'car-less-than-car)))
2145               (setq changed-version (not (= 2 gnus-agent-article-alist-save-format)))))
2146             (when changed-version
2147               (let ((gnus-agent-article-alist alist))
2148                 (gnus-agent-save-alist gnus-agent-read-agentview)))
2149             alist))
2150       ((end-of-file file-error)
2151        ;; The agentview file is missing. 
2152        (condition-case nil
2153            ;; If the agent directory exists, attempt to perform a brute-force
2154            ;; reconstruction of its contents.
2155            (let* (alist
2156                   (file-name-coding-system nnmail-pathname-coding-system)
2157                   (file-attributes (directory-files-and-attributes 
2158                                     (gnus-agent-article-name ""
2159                                                              gnus-agent-read-agentview) nil "^[0-9]+$" t)))
2160              (while file-attributes
2161                (let ((fa (pop file-attributes)))
2162                  (unless (nth 1 fa)
2163                    (push (cons (string-to-number (nth 0 fa)) (time-to-days (nth 5 fa))) alist))))
2164              alist)
2165          (file-error nil))))))
2166
2167 (defun gnus-agent-save-alist (group &optional articles state)
2168   "Save the article-state alist for GROUP."
2169   (let* ((file-name-coding-system nnmail-pathname-coding-system)
2170          (prev (cons nil gnus-agent-article-alist))
2171          (all prev)
2172          print-level print-length item article)
2173     (while (setq article (pop articles))
2174       (while (and (cdr prev)
2175                   (< (caadr prev) article))
2176         (setq prev (cdr prev)))
2177       (cond
2178        ((not (cdr prev))
2179         (setcdr prev (list (cons article state))))
2180        ((> (caadr prev) article)
2181         (setcdr prev (cons (cons article state) (cdr prev))))
2182        ((= (caadr prev) article)
2183         (setcdr (cadr prev) state)))
2184       (setq prev (cdr prev)))
2185     (setq gnus-agent-article-alist (cdr all))
2186
2187     (gnus-agent-set-local group
2188                           (caar gnus-agent-article-alist)
2189                           (caar (last gnus-agent-article-alist)))
2190
2191     (gnus-make-directory (gnus-agent-article-name "" group))
2192     (with-temp-file (gnus-agent-article-name ".agentview" group)
2193       (cond ((eq gnus-agent-article-alist-save-format 1)
2194              (princ gnus-agent-article-alist (current-buffer)))
2195             ((eq gnus-agent-article-alist-save-format 2)
2196              (let ((compressed nil))
2197                (mapcar (lambda (pair)
2198                          (let* ((article-id (car pair))
2199                                 (day-of-download (cdr pair))
2200                                 (comp-list (assq day-of-download compressed)))
2201                            (if comp-list
2202                                (setcdr comp-list
2203                                        (cons article-id (cdr comp-list)))
2204                              (setq compressed
2205                                    (cons (list day-of-download article-id)
2206                                          compressed)))
2207                            nil)) gnus-agent-article-alist)
2208                (mapcar (lambda (comp-list)
2209                          (setcdr comp-list
2210                                  (gnus-compress-sequence
2211                                   (nreverse (cdr comp-list)))))
2212                        compressed)
2213                (princ compressed (current-buffer)))))
2214       (insert "\n")
2215       (princ gnus-agent-article-alist-save-format (current-buffer))
2216       (insert "\n"))
2217
2218     (gnus-agent-update-view-total-fetched-for group nil)))
2219
2220 (defvar gnus-agent-article-local nil)
2221 (defvar gnus-agent-file-loading-local nil)
2222
2223 (defun gnus-agent-load-local (&optional method)
2224   "Load the METHOD'S local file.  The local file contains min/max
2225 article counts for each of the method's subscribed groups."
2226   (let ((gnus-command-method (or method gnus-command-method)))
2227     (setq gnus-agent-article-local
2228           (gnus-cache-file-contents
2229            (gnus-agent-lib-file "local")
2230            'gnus-agent-file-loading-local
2231            'gnus-agent-read-and-cache-local))))
2232
2233 (defun gnus-agent-read-and-cache-local (file)
2234   "Load and read FILE then bind its contents to
2235 gnus-agent-article-local.  If that variable had `dirty' (also known as
2236 modified) original contents, they are first saved to their own file."
2237
2238   (if (and gnus-agent-article-local
2239            (symbol-value (intern "+dirty" gnus-agent-article-local)))
2240       (gnus-agent-save-local))
2241   (gnus-agent-read-local file))
2242
2243 (defun gnus-agent-read-local (file)
2244   "Load FILE and do a `read' there."
2245   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min)
2246                                                       (point-max))))
2247         (line 1))
2248     (with-temp-buffer
2249       (condition-case nil
2250           (let ((nnheader-file-coding-system gnus-agent-file-coding-system))
2251             (nnheader-insert-file-contents file))
2252         (file-error))
2253
2254       (goto-char (point-min))
2255       ;; Skip any comments at the beginning of the file (the only place where they may appear)
2256       (while (= (following-char) ?\;)
2257         (forward-line 1)
2258         (setq line (1+ line)))
2259
2260       (while (not (eobp))
2261         (condition-case err
2262             (let (group
2263                   min
2264                   max
2265                   (cur (current-buffer))
2266                   (obarray my-obarray))
2267               (setq group (read cur)
2268                     min (read cur)
2269                     max (read cur))
2270
2271               (when (stringp group)
2272                 (setq group (intern group my-obarray)))
2273
2274               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
2275               (set group (cons (+ 0 min) (+ 0 max))))
2276           (error
2277            (gnus-message 3 "Warning - invalid agent local: %s on line %d: %s"
2278                          file line (error-message-string err))))
2279         (forward-line 1)
2280         (setq line (1+ line))))
2281
2282     (set (intern "+dirty" my-obarray) nil)
2283     (set (intern "+method" my-obarray) gnus-command-method)
2284     my-obarray))
2285
2286 (defun gnus-agent-save-local (&optional force)
2287   "Save gnus-agent-article-local under it method's agent.lib directory."
2288   (let ((my-obarray gnus-agent-article-local))
2289     (when (and my-obarray
2290                (or force (symbol-value (intern "+dirty" my-obarray))))
2291       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2292              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
2293              (dest (gnus-agent-lib-file "local")))
2294         (gnus-make-directory (gnus-agent-lib-file ""))
2295
2296         (let ((coding-system-for-write gnus-agent-file-coding-system)
2297               (file-name-coding-system nnmail-pathname-coding-system))
2298           (with-temp-file dest
2299             (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2300                   print-level print-length item article
2301                   (standard-output (current-buffer)))
2302               (mapatoms (lambda (symbol)
2303                           (cond ((not (boundp symbol))
2304                                  nil)
2305                                 ((member (symbol-name symbol) '("+dirty" "+method"))
2306                                  nil)
2307                                 (t
2308                                  (let ((range (symbol-value symbol)))
2309                                    (when range
2310                                      (prin1 symbol)
2311                                      (princ " ")
2312                                      (princ (car range))
2313                                      (princ " ")
2314                                      (princ (cdr range))
2315                                      (princ "\n"))))))
2316                         my-obarray))))))))
2317
2318 (defun gnus-agent-get-local (group &optional gmane method)
2319   (let* ((gmane (or gmane (gnus-group-real-name group)))
2320          (gnus-command-method (or method (gnus-find-method-for-group group)))
2321          (local (gnus-agent-load-local))
2322          (symb (intern gmane local))
2323          (minmax (and (boundp symb) (symbol-value symb))))
2324     (unless minmax
2325       ;; Bind these so that gnus-agent-load-alist doesn't change the
2326       ;; current alist (i.e. gnus-agent-article-alist)
2327       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2328              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2329              (alist (gnus-agent-load-alist group)))
2330         (when alist
2331           (setq minmax
2332                 (cons (caar alist)
2333                       (caar (last alist))))
2334           (gnus-agent-set-local group (car minmax) (cdr minmax)
2335                                 gmane gnus-command-method local))))
2336     minmax))
2337
2338 (defun gnus-agent-set-local (group min max &optional gmane method local)
2339   (let* ((gmane (or gmane (gnus-group-real-name group)))
2340          (gnus-command-method (or method (gnus-find-method-for-group group)))
2341          (local (or local (gnus-agent-load-local)))
2342          (symb (intern gmane local))
2343          (minmax (and (boundp symb) (symbol-value symb))))
2344
2345     (if (cond ((and minmax
2346                     (or (not (eq min (car minmax)))
2347                         (not (eq max (cdr minmax))))
2348                     min
2349                     max)
2350                (setcar minmax min)
2351                (setcdr minmax max)
2352                t)
2353               (minmax
2354                nil)
2355               ((and min max)
2356                (set symb (cons min max))
2357                t)
2358               (t
2359                (unintern symb local)))
2360         (set (intern "+dirty" local) t))))
2361
2362 (defun gnus-agent-article-name (article group)
2363   (expand-file-name article
2364                     (file-name-as-directory
2365                      (gnus-agent-group-pathname group))))
2366
2367 (defun gnus-agent-batch-confirmation (msg)
2368   "Show error message and return t."
2369   (gnus-message 1 msg)
2370   t)
2371
2372 ;;;###autoload
2373 (defun gnus-agent-batch-fetch ()
2374   "Start Gnus and fetch session."
2375   (interactive)
2376   (gnus)
2377   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2378     (gnus-agent-fetch-session))
2379   (gnus-group-exit))
2380
2381 (defun gnus-agent-fetch-session ()
2382   "Fetch all articles and headers that are eligible for fetching."
2383   (interactive)
2384   (unless gnus-agent-covered-methods
2385     (error "No servers are covered by the Gnus agent"))
2386   (unless gnus-plugged
2387     (error "Can't fetch articles while Gnus is unplugged"))
2388   (let ((methods (gnus-agent-covered-methods))
2389         groups group gnus-command-method)
2390     (save-excursion
2391       (while methods
2392         (setq gnus-command-method (car methods))
2393         (when (and (or (gnus-server-opened gnus-command-method)
2394                        (gnus-open-server gnus-command-method))
2395                    (gnus-online gnus-command-method))
2396           (setq groups (gnus-groups-from-server (car methods)))
2397           (gnus-agent-with-fetch
2398             (while (setq group (pop groups))
2399               (when (<= (gnus-group-level group)
2400                         gnus-agent-handle-level)
2401                 (if (or debug-on-error debug-on-quit)
2402                     (gnus-agent-fetch-group-1
2403                      group gnus-command-method)
2404                   (condition-case err
2405                       (gnus-agent-fetch-group-1
2406                        group gnus-command-method)
2407                     (error
2408                      (unless (funcall gnus-agent-confirmation-function
2409                                       (format "Error %s while fetching session.  Should gnus continue? "
2410                                               (error-message-string err)))
2411                        (error "Cannot fetch articles into the Gnus agent")))
2412                     (quit
2413                      (gnus-agent-regenerate-group group)
2414                      (unless (funcall gnus-agent-confirmation-function
2415                                       (format
2416                                        "%s while fetching session.  Should gnus continue? "
2417                                        (error-message-string err)))
2418                        (signal 'quit
2419                                "Cannot fetch articles into the Gnus agent")))))))))
2420         (setq methods (cdr methods)))
2421       (gnus-run-hooks 'gnus-agent-fetched-hook)
2422       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2423
2424 (defun gnus-agent-fetch-group-1 (group method)
2425   "Fetch GROUP."
2426   (let ((gnus-command-method method)
2427         (gnus-newsgroup-name group)
2428         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2429         (gnus-newsgroup-headers gnus-newsgroup-headers)
2430         (gnus-newsgroup-scored gnus-newsgroup-scored)
2431         (gnus-use-cache gnus-use-cache)
2432         (gnus-summary-expunge-below gnus-summary-expunge-below)
2433         (gnus-summary-mark-below gnus-summary-mark-below)
2434         (gnus-orphan-score gnus-orphan-score)
2435         ;; Maybe some other gnus-summary local variables should also
2436         ;; be put here.
2437
2438         gnus-headers
2439         gnus-score
2440         articles arts
2441         category predicate info marks score-param
2442         )
2443     (unless (gnus-check-group group)
2444       (error "Can't open server for %s" group))
2445
2446     ;; Fetch headers.
2447     (when (or gnus-newsgroup-active
2448               (gnus-active group)
2449               (gnus-activate-group group))
2450       (let ((marked-articles gnus-newsgroup-downloadable))
2451         ;; Identify the articles marked for download
2452         (unless gnus-newsgroup-active
2453           ;; The variable gnus-newsgroup-active was selected as I need
2454           ;; a gnus-summary local variable that is NOT bound to any
2455           ;; value (its global value should default to nil).
2456           (dolist (mark gnus-agent-download-marks)
2457             (let ((arts (cdr (assq mark (gnus-info-marks
2458                                          (setq info (gnus-get-info group)))))))
2459               (when arts
2460                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2461                                              marked-articles))
2462                 ))))
2463         (setq marked-articles (sort marked-articles '<))
2464
2465         ;; Fetch any new articles from the server
2466         (setq articles (gnus-agent-fetch-headers group))
2467
2468         ;; Merge new articles with marked
2469         (setq articles (sort (append marked-articles articles) '<))
2470
2471         (when articles
2472           ;; Parse them and see which articles we want to fetch.
2473           (setq gnus-newsgroup-dependencies
2474                 (or gnus-newsgroup-dependencies
2475                     (make-vector (length articles) 0)))
2476           (setq gnus-newsgroup-headers
2477                 (or gnus-newsgroup-headers
2478                     (gnus-get-newsgroup-headers-xover articles nil nil
2479                                                       group)))
2480           ;; `gnus-agent-overview-buffer' may be killed for
2481           ;; timeout reason.  If so, recreate it.
2482           (gnus-agent-create-buffer)
2483
2484           ;; Figure out how to select articles in this group
2485           (setq category (gnus-group-category group))
2486
2487           (setq predicate
2488                 (gnus-get-predicate
2489                  (gnus-agent-find-parameter group 'agent-predicate)))
2490
2491           ;; If the selection predicate requires scoring, score each header
2492           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2493             (let ((score-param
2494                    (gnus-agent-find-parameter group 'agent-score-file)))
2495               ;; Translate score-param into real one
2496               (cond
2497                ((not score-param))
2498                ((eq score-param 'file)
2499                 (setq score-param (gnus-all-score-files group)))
2500                ((stringp (car score-param)))
2501                (t
2502                 (setq score-param (list (list score-param)))))
2503               (when score-param
2504                 (gnus-score-headers score-param))))
2505
2506           (unless (and (eq predicate 'gnus-agent-false)
2507                        (not marked-articles))
2508             (let ((arts (list nil)))
2509               (let ((arts-tail arts)
2510                     (alist (gnus-agent-load-alist group))
2511                     (marked-articles marked-articles)
2512                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2513                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2514                   (let ((num (mail-header-number gnus-headers)))
2515                     ;; Determine if this article is already in the cache
2516                     (while (and alist
2517                                 (> num (caar alist)))
2518                       (setq alist (cdr alist)))
2519
2520                     (unless (and (eq num (caar alist))
2521                                  (cdar alist))
2522
2523                       ;; Determine if this article was marked for download.
2524                       (while (and marked-articles
2525                                   (> num (car marked-articles)))
2526                         (setq marked-articles
2527                               (cdr marked-articles)))
2528
2529                       ;; When this article is marked, or selected by the
2530                       ;; predicate, add it to the download list
2531                       (when (or (eq num (car marked-articles))
2532                                 (let ((gnus-score
2533                                        (or (cdr
2534                                             (assq num gnus-newsgroup-scored))
2535                                            gnus-summary-default-score))
2536                                       (gnus-agent-long-article
2537                                        (gnus-agent-find-parameter
2538                                         group 'agent-long-article))
2539                                       (gnus-agent-short-article
2540                                        (gnus-agent-find-parameter
2541                                         group 'agent-short-article))
2542                                       (gnus-agent-low-score
2543                                        (gnus-agent-find-parameter
2544                                         group 'agent-low-score))
2545                                       (gnus-agent-high-score
2546                                        (gnus-agent-find-parameter
2547                                         group 'agent-high-score))
2548                                       (gnus-agent-expire-days
2549                                        (gnus-agent-find-parameter
2550                                         group 'agent-days-until-old)))
2551                                   (funcall predicate)))
2552                         (gnus-agent-append-to-list arts-tail num))))))
2553
2554               (let (fetched-articles)
2555                 ;; Fetch all selected articles
2556                 (setq gnus-newsgroup-undownloaded
2557                       (gnus-sorted-ndifference
2558                        gnus-newsgroup-undownloaded
2559                        (setq fetched-articles
2560                              (if (cdr arts)
2561                                  (gnus-agent-fetch-articles group (cdr arts))
2562                                nil))))
2563
2564                 (let ((unfetched-articles
2565                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2566                   (if gnus-newsgroup-active
2567                       ;; Update the summary buffer
2568                       (progn
2569                         (dolist (article marked-articles)
2570                           (gnus-summary-set-agent-mark article t))
2571                         (dolist (article fetched-articles)
2572                           (when gnus-agent-mark-unread-after-downloaded
2573                             (setq gnus-newsgroup-downloadable
2574                                   (delq article gnus-newsgroup-downloadable))
2575                             (gnus-summary-mark-article
2576                              article gnus-unread-mark))
2577                           (when (gnus-summary-goto-subject article nil t)
2578                             (gnus-summary-update-download-mark article)))
2579                         (dolist (article unfetched-articles)
2580                           (gnus-summary-mark-article
2581                            article gnus-canceled-mark)))
2582
2583                     ;; Update the group buffer.
2584
2585                     ;; When some, or all, of the marked articles came
2586                     ;; from the download mark.  Remove that mark.  I
2587                     ;; didn't do this earlier as I only want to remove
2588                     ;; the marks after the fetch is completed.
2589
2590                     (dolist (mark gnus-agent-download-marks)
2591                       (when (eq mark 'download)
2592                         (let ((marked-arts
2593                                (assq mark (gnus-info-marks
2594                                            (setq info (gnus-get-info group))))))
2595                           (when (cdr marked-arts)
2596                             (setq marks
2597                                   (delq marked-arts (gnus-info-marks info)))
2598                             (gnus-info-set-marks info marks)))))
2599                     (let ((read (gnus-info-read
2600                                  (or info (setq info (gnus-get-info group))))))
2601                       (gnus-info-set-read
2602                        info (gnus-add-to-range read unfetched-articles)))
2603
2604                     (gnus-group-update-group group t)
2605                     (sit-for 0)
2606
2607                     (gnus-dribble-enter
2608                      (concat "(gnus-group-set-info '"
2609                              (gnus-prin1-to-string info)
2610                              ")"))))))))))))
2611
2612 ;;;
2613 ;;; Agent Category Mode
2614 ;;;
2615
2616 (defvar gnus-category-mode-hook nil
2617   "Hook run in `gnus-category-mode' buffers.")
2618
2619 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2620   "Format of category lines.
2621
2622 Valid specifiers include:
2623 %c  Topic name (string)
2624 %g  The number of groups in the topic (integer)
2625
2626 General format specifiers can also be used.  See Info node
2627 `(gnus)Formatting Variables'.")
2628
2629 (defvar gnus-category-mode-line-format "Gnus: %%b"
2630   "The format specification for the category mode line.")
2631
2632 (defvar gnus-agent-predicate 'false
2633   "The selection predicate used when no other source is available.")
2634
2635 (defvar gnus-agent-short-article 100
2636   "Articles that have fewer lines than this are short.")
2637
2638 (defvar gnus-agent-long-article 200
2639   "Articles that have more lines than this are long.")
2640
2641 (defvar gnus-agent-low-score 0
2642   "Articles that have a score lower than this have a low score.")
2643
2644 (defvar gnus-agent-high-score 0
2645   "Articles that have a score higher than this have a high score.")
2646
2647
2648 ;;; Internal variables.
2649
2650 (defvar gnus-category-buffer "*Agent Category*")
2651
2652 (defvar gnus-category-line-format-alist
2653   `((?c gnus-tmp-name ?s)
2654     (?g gnus-tmp-groups ?d)))
2655
2656 (defvar gnus-category-mode-line-format-alist
2657   `((?u user-defined ?s)))
2658
2659 (defvar gnus-category-line-format-spec nil)
2660 (defvar gnus-category-mode-line-format-spec nil)
2661
2662 (defvar gnus-category-mode-map nil)
2663 (put 'gnus-category-mode 'mode-class 'special)
2664
2665 (unless gnus-category-mode-map
2666   (setq gnus-category-mode-map (make-sparse-keymap))
2667   (suppress-keymap gnus-category-mode-map)
2668
2669   (gnus-define-keys gnus-category-mode-map
2670     "q" gnus-category-exit
2671     "k" gnus-category-kill
2672     "c" gnus-category-copy
2673     "a" gnus-category-add
2674     "e" gnus-agent-customize-category
2675     "p" gnus-category-edit-predicate
2676     "g" gnus-category-edit-groups
2677     "s" gnus-category-edit-score
2678     "l" gnus-category-list
2679
2680     "\C-c\C-i" gnus-info-find-node
2681     "\C-c\C-b" gnus-bug))
2682
2683 (defvar gnus-category-menu-hook nil
2684   "*Hook run after the creation of the menu.")
2685
2686 (defun gnus-category-make-menu-bar ()
2687   (gnus-turn-off-edit-menu 'category)
2688   (unless (boundp 'gnus-category-menu)
2689     (easy-menu-define
2690      gnus-category-menu gnus-category-mode-map ""
2691      '("Categories"
2692        ["Add" gnus-category-add t]
2693        ["Kill" gnus-category-kill t]
2694        ["Copy" gnus-category-copy t]
2695        ["Edit category" gnus-agent-customize-category t]
2696        ["Edit predicate" gnus-category-edit-predicate t]
2697        ["Edit score" gnus-category-edit-score t]
2698        ["Edit groups" gnus-category-edit-groups t]
2699        ["Exit" gnus-category-exit t]))
2700
2701     (gnus-run-hooks 'gnus-category-menu-hook)))
2702
2703 (defun gnus-category-mode ()
2704   "Major mode for listing and editing agent categories.
2705
2706 All normal editing commands are switched off.
2707 \\<gnus-category-mode-map>
2708 For more in-depth information on this mode, read the manual
2709 \(`\\[gnus-info-find-node]').
2710
2711 The following commands are available:
2712
2713 \\{gnus-category-mode-map}"
2714   (interactive)
2715   (when (gnus-visual-p 'category-menu 'menu)
2716     (gnus-category-make-menu-bar))
2717   (kill-all-local-variables)
2718   (gnus-simplify-mode-line)
2719   (setq major-mode 'gnus-category-mode)
2720   (setq mode-name "Category")
2721   (gnus-set-default-directory)
2722   (setq mode-line-process nil)
2723   (use-local-map gnus-category-mode-map)
2724   (buffer-disable-undo)
2725   (setq truncate-lines t)
2726   (setq buffer-read-only t)
2727   (gnus-run-mode-hooks 'gnus-category-mode-hook))
2728
2729 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2730
2731 (defun gnus-category-insert-line (category)
2732   (let* ((gnus-tmp-name (format "%s" (car category)))
2733          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2734     (beginning-of-line)
2735     (gnus-add-text-properties
2736      (point)
2737      (prog1 (1+ (point))
2738        ;; Insert the text.
2739        (eval gnus-category-line-format-spec))
2740      (list 'gnus-category gnus-tmp-name))))
2741
2742 (defun gnus-enter-category-buffer ()
2743   "Go to the Category buffer."
2744   (interactive)
2745   (gnus-category-setup-buffer)
2746   (gnus-configure-windows 'category)
2747   (gnus-category-prepare))
2748
2749 (defun gnus-category-setup-buffer ()
2750   (unless (get-buffer gnus-category-buffer)
2751     (save-excursion
2752       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2753       (gnus-category-mode))))
2754
2755 (defun gnus-category-prepare ()
2756   (gnus-set-format 'category-mode)
2757   (gnus-set-format 'category t)
2758   (let ((alist gnus-category-alist)
2759         (buffer-read-only nil))
2760     (erase-buffer)
2761     (while alist
2762       (gnus-category-insert-line (pop alist)))
2763     (goto-char (point-min))
2764     (gnus-category-position-point)))
2765
2766 (defun gnus-category-name ()
2767   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2768       (error "No category on the current line")))
2769
2770 (defun gnus-category-read ()
2771   "Read the category alist."
2772   (setq gnus-category-alist
2773         (or
2774          (with-temp-buffer
2775            (ignore-errors
2776             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2777             (goto-char (point-min))
2778             ;; This code isn't temp, it will be needed so long as
2779             ;; anyone may be migrating from an older version.
2780
2781             ;; Once we're certain that people will not revert to an
2782             ;; earlier version, we can take out the old-list code in
2783             ;; gnus-category-write.
2784             (let* ((old-list (read (current-buffer)))
2785                    (new-list (ignore-errors (read (current-buffer)))))
2786               (if new-list
2787                   new-list
2788                 ;; Convert from a positional list to an alist.
2789                 (mapcar
2790                  (lambda (c)
2791                    (setcdr c
2792                            (delq nil
2793                                  (gnus-mapcar
2794                                   (lambda (valu symb)
2795                                     (if valu
2796                                         (cons symb valu)))
2797                                   (cdr c)
2798                                   '(agent-predicate agent-score-file agent-groups))))
2799                    c)
2800                  old-list)))))
2801          (list (gnus-agent-cat-make 'default 'short)))))
2802
2803 (defun gnus-category-write ()
2804   "Write the category alist."
2805   (setq gnus-category-predicate-cache nil
2806         gnus-category-group-cache nil)
2807   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2808   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2809     ;; This prin1 is temporary.  It exists so that people can revert
2810     ;; to an earlier version of gnus-agent.
2811     (prin1 (mapcar (lambda (c)
2812               (list (car c)
2813                     (cdr (assoc 'agent-predicate c))
2814                     (cdr (assoc 'agent-score-file c))
2815                     (cdr (assoc 'agent-groups c))))
2816                    gnus-category-alist)
2817            (current-buffer))
2818     (newline)
2819     (prin1 gnus-category-alist (current-buffer))))
2820
2821 (defun gnus-category-edit-predicate (category)
2822   "Edit the predicate for CATEGORY."
2823   (interactive (list (gnus-category-name)))
2824   (let ((info (assq category gnus-category-alist)))
2825     (gnus-edit-form
2826      (gnus-agent-cat-predicate info)
2827      (format "Editing the select predicate for category %s" category)
2828      `(lambda (predicate)
2829         ;; Avoid run-time execution of setf form
2830         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2831         ;;       predicate)
2832         ;; use its expansion instead:
2833         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2834                                      'agent-predicate predicate)
2835
2836         (gnus-category-write)
2837         (gnus-category-list)))))
2838
2839 (defun gnus-category-edit-score (category)
2840   "Edit the score expression for CATEGORY."
2841   (interactive (list (gnus-category-name)))
2842   (let ((info (assq category gnus-category-alist)))
2843     (gnus-edit-form
2844      (gnus-agent-cat-score-file info)
2845      (format "Editing the score expression for category %s" category)
2846      `(lambda (score-file)
2847         ;; Avoid run-time execution of setf form
2848         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2849         ;;       score-file)
2850         ;; use its expansion instead:
2851         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2852                                      'agent-score-file score-file)
2853
2854         (gnus-category-write)
2855         (gnus-category-list)))))
2856
2857 (defun gnus-category-edit-groups (category)
2858   "Edit the group list for CATEGORY."
2859   (interactive (list (gnus-category-name)))
2860   (let ((info (assq category gnus-category-alist)))
2861     (gnus-edit-form
2862      (gnus-agent-cat-groups info)
2863      (format "Editing the group list for category %s" category)
2864      `(lambda (groups)
2865         ;; Avoid run-time execution of setf form
2866         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2867         ;;       groups)
2868         ;; use its expansion instead:
2869         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2870                                    groups)
2871
2872         (gnus-category-write)
2873         (gnus-category-list)))))
2874
2875 (defun gnus-category-kill (category)
2876   "Kill the current category."
2877   (interactive (list (gnus-category-name)))
2878   (let ((info (assq category gnus-category-alist))
2879         (buffer-read-only nil))
2880     (gnus-delete-line)
2881     (setq gnus-category-alist (delq info gnus-category-alist))
2882     (gnus-category-write)))
2883
2884 (defun gnus-category-copy (category to)
2885   "Copy the current category."
2886   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2887   (let ((info (assq category gnus-category-alist)))
2888     (push (let ((newcat (gnus-copy-sequence info)))
2889             (setf (gnus-agent-cat-name newcat) to)
2890             (setf (gnus-agent-cat-groups newcat) nil)
2891             newcat)
2892           gnus-category-alist)
2893     (gnus-category-write)
2894     (gnus-category-list)))
2895
2896 (defun gnus-category-add (category)
2897   "Create a new category."
2898   (interactive "SCategory name: ")
2899   (when (assq category gnus-category-alist)
2900     (error "Category %s already exists" category))
2901   (push (gnus-agent-cat-make category)
2902         gnus-category-alist)
2903   (gnus-category-write)
2904   (gnus-category-list))
2905
2906 (defun gnus-category-list ()
2907   "List all categories."
2908   (interactive)
2909   (gnus-category-prepare))
2910
2911 (defun gnus-category-exit ()
2912   "Return to the group buffer."
2913   (interactive)
2914   (kill-buffer (current-buffer))
2915   (gnus-configure-windows 'group t))
2916
2917 ;; To avoid having 8-bit characters in the source file.
2918 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2919
2920 (defvar gnus-category-predicate-alist
2921   '((spam . gnus-agent-spam-p)
2922     (short . gnus-agent-short-p)
2923     (long . gnus-agent-long-p)
2924     (low . gnus-agent-low-scored-p)
2925     (high . gnus-agent-high-scored-p)
2926     (read . gnus-agent-read-p)
2927     (true . gnus-agent-true)
2928     (false . gnus-agent-false))
2929   "Mapping from short score predicate symbols to predicate functions.")
2930
2931 (defun gnus-agent-spam-p ()
2932   "Say whether an article is spam or not."
2933   (unless gnus-agent-spam-hashtb
2934     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2935   (if (not (equal (mail-header-references gnus-headers) ""))
2936       nil
2937     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2938       (prog1
2939           (gnus-gethash string gnus-agent-spam-hashtb)
2940         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2941
2942 (defun gnus-agent-short-p ()
2943   "Say whether an article is short or not."
2944   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2945
2946 (defun gnus-agent-long-p ()
2947   "Say whether an article is long or not."
2948   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2949
2950 (defun gnus-agent-low-scored-p ()
2951   "Say whether an article has a low score or not."
2952   (< gnus-score gnus-agent-low-score))
2953
2954 (defun gnus-agent-high-scored-p ()
2955   "Say whether an article has a high score or not."
2956   (> gnus-score gnus-agent-high-score))
2957
2958 (defun gnus-agent-read-p ()
2959   "Say whether an article is read or not."
2960   (gnus-member-of-range (mail-header-number gnus-headers)
2961                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2962
2963 (defun gnus-category-make-function (predicate)
2964   "Make a function from PREDICATE."
2965   (let ((func (gnus-category-make-function-1 predicate)))
2966     (if (and (= (length func) 1)
2967              (symbolp (car func)))
2968         (car func)
2969       (gnus-byte-compile `(lambda () ,func)))))
2970
2971 (defun gnus-agent-true ()
2972   "Return t."
2973   t)
2974
2975 (defun gnus-agent-false ()
2976   "Return nil."
2977   nil)
2978
2979 (defun gnus-category-make-function-1 (predicate)
2980   "Make a function from PREDICATE."
2981   (cond
2982    ;; Functions are just returned as is.
2983    ((or (symbolp predicate)
2984         (functionp predicate))
2985     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2986            predicate)))
2987    ;; More complex predicate.
2988    ((consp predicate)
2989     `(,(cond
2990         ((memq (car predicate) '(& and))
2991          'and)
2992         ((memq (car predicate) '(| or))
2993          'or)
2994         ((memq (car predicate) gnus-category-not)
2995          'not))
2996       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2997    (t
2998     (error "Unknown predicate type: %s" predicate))))
2999
3000 (defun gnus-get-predicate (predicate)
3001   "Return the function implementing PREDICATE."
3002   (or (cdr (assoc predicate gnus-category-predicate-cache))
3003       (let ((func (gnus-category-make-function predicate)))
3004         (setq gnus-category-predicate-cache
3005               (nconc gnus-category-predicate-cache
3006                      (list (cons predicate func))))
3007         func)))
3008
3009 (defun gnus-predicate-implies-unread (predicate)
3010   "Say whether PREDICATE implies unread articles only.
3011 It is okay to miss some cases, but there must be no false positives.
3012 That is, if this predicate returns true, then indeed the predicate must
3013 return only unread articles."
3014   (eq t (gnus-function-implies-unread-1
3015          (gnus-category-make-function-1 predicate))))
3016
3017 (defun gnus-function-implies-unread-1 (function)
3018   "Recursively evaluate a predicate function to determine whether it can select
3019 any read articles.  Returns t if the function is known to never
3020 return read articles, nil when it is known to always return read
3021 articles, and t_nil when the function may return both read and unread
3022 articles."
3023   (let ((func (car function))
3024         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
3025     (cond ((eq func 'and)
3026            (cond ((memq t args) ; if any argument returns only unread articles
3027                   ;; then that argument constrains the result to only unread articles.
3028                   t)
3029                  ((memq 't_nil args) ; if any argument is indeterminate
3030                   ;; then the result is indeterminate
3031                   't_nil)))
3032           ((eq func 'or)
3033            (cond ((memq nil args) ; if any argument returns read articles
3034                   ;; then that argument ensures that the results includes read articles.
3035                   nil)
3036                  ((memq 't_nil args) ; if any argument is indeterminate
3037                   ;; then that argument ensures that the results are indeterminate
3038                   't_nil)
3039                  (t ; if all arguments return only unread articles
3040                   ;; then the result returns only unread articles
3041                   t)))
3042           ((eq func 'not)
3043            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
3044                   ; then the result is indeterminate
3045                   (car args))
3046                  (t ; otherwise
3047                   ; toggle the result to be the opposite of the argument
3048                   (not (car args)))))
3049           ((eq func 'gnus-agent-read-p)
3050            nil) ; The read predicate NEVER returns unread articles
3051           ((eq func 'gnus-agent-false)
3052            t) ; The false predicate returns t as the empty set excludes all read articles
3053           ((eq func 'gnus-agent-true)
3054            nil) ; The true predicate ALWAYS returns read articles
3055           ((catch 'found-match
3056              (let ((alist gnus-category-predicate-alist))
3057                (while alist
3058                  (if (eq func (cdar alist))
3059                      (throw 'found-match t)
3060                    (setq alist (cdr alist))))))
3061            't_nil) ; All other predicates return read and unread articles
3062           (t
3063            (error "Unknown predicate function: %s" function)))))
3064
3065 (defun gnus-group-category (group)
3066   "Return the category GROUP belongs to."
3067   (unless gnus-category-group-cache
3068     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
3069     (let ((cs gnus-category-alist)
3070           groups cat)
3071       (while (setq cat (pop cs))
3072         (setq groups (gnus-agent-cat-groups cat))
3073         (while groups
3074           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
3075   (or (gnus-gethash group gnus-category-group-cache)
3076       (assq 'default gnus-category-alist)))
3077
3078 (defun gnus-agent-expire-group (group &optional articles force)
3079   "Expire all old articles in GROUP.
3080 If you want to force expiring of certain articles, this function can
3081 take ARTICLES, and FORCE parameters as well.
3082
3083 The articles on which the expiration process runs are selected as follows:
3084   if ARTICLES is null, all read and unmarked articles.
3085   if ARTICLES is t, all articles.
3086   if ARTICLES is a list, just those articles.
3087 FORCE is equivalent to setting the expiration predicates to true."
3088   (interactive
3089    (list (let ((def (or (gnus-group-group-name)
3090                         gnus-newsgroup-name)))
3091            (let ((select (read-string (if def
3092                                           (concat "Group Name ("
3093                                                   def "): ")
3094                                         "Group Name: "))))
3095              (if (and (equal "" select)
3096                       def)
3097                  def
3098                select)))))
3099
3100   (if (not group)
3101       (gnus-agent-expire articles group force)
3102     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
3103           ;; expiration statistics of this single group
3104           (gnus-agent-expire-stats (list 0 0 0.0)))
3105       (if (or (not (eq articles t))
3106               (yes-or-no-p
3107                (concat "Are you sure that you want to "
3108                        "expire all articles in " group "? ")))
3109           (let ((gnus-command-method (gnus-find-method-for-group group))
3110                 (overview (gnus-get-buffer-create " *expire overview*"))
3111                 orig)
3112             (unwind-protect
3113                 (let ((active-file (gnus-agent-lib-file "active")))
3114                   (when (file-exists-p active-file)
3115                     (with-temp-buffer
3116                       (nnheader-insert-file-contents active-file)
3117                       (gnus-active-to-gnus-format
3118                        gnus-command-method
3119                        (setq orig (gnus-make-hashtable
3120                                    (count-lines (point-min) (point-max))))))
3121                     (save-excursion
3122                       (gnus-agent-expire-group-1
3123                        group overview (gnus-gethash-safe group orig)
3124                        articles force))))
3125               (kill-buffer overview))))
3126       (gnus-message 4 (gnus-agent-expire-done-message)))))
3127
3128 (defun gnus-agent-expire-group-1 (group overview active articles force)
3129   ;; Internal function - requires caller to have set
3130   ;; gnus-command-method, initialized overview buffer, and to have
3131   ;; provided a non-nil active
3132
3133   (let ((dir (gnus-agent-group-pathname group))
3134         (file-name-coding-system nnmail-pathname-coding-system))
3135     (gnus-agent-with-refreshed-group
3136      group
3137      (when (boundp 'gnus-agent-expire-current-dirs)
3138        (set 'gnus-agent-expire-current-dirs
3139             (cons dir
3140                   (symbol-value 'gnus-agent-expire-current-dirs))))
3141
3142      (if (and (not force)
3143               (eq 'DISABLE (gnus-agent-find-parameter group
3144                                                       'agent-enable-expiration)))
3145          (gnus-message 5 "Expiry skipping over %s" group)
3146        (gnus-message 5 "Expiring articles in %s" group)
3147        (gnus-agent-load-alist group)
3148        (let* ((bytes-freed 0)
3149               (size-files-deleted 0.0)
3150               (files-deleted 0)
3151               (nov-entries-deleted 0)
3152               (info (gnus-get-info group))
3153               (alist gnus-agent-article-alist)
3154               (day (- (time-to-days (current-time))
3155                       (gnus-agent-find-parameter group 'agent-days-until-old)))
3156               (specials (if (and alist
3157                                  (not force))
3158                             ;; This could be a bit of a problem.  I need to
3159                             ;; keep the last article to avoid refetching
3160                             ;; headers when using nntp in the backend.  At
3161                             ;; the same time, if someone uses a backend
3162                             ;; that supports article moving then I may have
3163                             ;; to remove the last article to complete the
3164                             ;; move.  Right now, I'm going to assume that
3165                             ;; FORCE overrides specials.
3166                             (list (caar (last alist)))))
3167               (unreads ;; Articles that are excluded from the
3168                ;; expiration process
3169                (cond (gnus-agent-expire-all
3170                       ;; All articles are marked read by global decree
3171                       nil)
3172                      ((eq articles t)
3173                       ;; All articles are marked read by function
3174                       ;; parameter
3175                       nil)
3176                      ((not articles)
3177                       ;; Unread articles are marked protected from
3178                       ;; expiration Don't call
3179                       ;; gnus-list-of-unread-articles as it returns
3180                       ;; articles that have not been fetched into the
3181                       ;; agent.
3182                       (ignore-errors
3183                         (gnus-agent-unread-articles group)))
3184                      (t
3185                       ;; All articles EXCEPT those named by the caller
3186                       ;; are protected from expiration
3187                       (gnus-sorted-difference
3188                        (gnus-uncompress-range
3189                         (cons (caar alist)
3190                               (caar (last alist))))
3191                        (sort articles '<)))))
3192               (marked ;; More articles that are excluded from the
3193                ;; expiration process
3194                (cond (gnus-agent-expire-all
3195                       ;; All articles are unmarked by global decree
3196                       nil)
3197                      ((eq articles t)
3198                       ;; All articles are unmarked by function
3199                       ;; parameter
3200                       nil)
3201                      (articles
3202                       ;; All articles may as well be unmarked as the
3203                       ;; unreads list already names the articles we are
3204                       ;; going to keep
3205                       nil)
3206                      (t
3207                       ;; Ticked and/or dormant articles are excluded
3208                       ;; from expiration
3209                       (nconc
3210                        (gnus-uncompress-range
3211                         (cdr (assq 'tick (gnus-info-marks info))))
3212                        (gnus-uncompress-range
3213                         (cdr (assq 'dormant
3214                                    (gnus-info-marks info))))))))
3215               (nov-file (concat dir ".overview"))
3216               (cnt 0)
3217               (completed -1)
3218               dlist
3219               type)
3220
3221          ;; The normal article alist contains elements that look like
3222          ;; (article# .  fetch_date) I need to combine other
3223          ;; information with this list.  For example, a flag indicating
3224          ;; that a particular article MUST BE KEPT.  To do this, I'm
3225          ;; going to transform the elements to look like (article#
3226          ;; fetch_date keep_flag NOV_entry_position) Later, I'll reverse
3227          ;; the process to generate the expired article alist.
3228
3229          ;; Convert the alist elements to (article# fetch_date nil
3230          ;; nil).
3231          (setq dlist (mapcar (lambda (e)
3232                                (list (car e) (cdr e) nil nil)) alist))
3233
3234          ;; Convert the keep lists to elements that look like (article#
3235          ;; nil keep_flag nil) then append it to the expanded dlist
3236          ;; These statements are sorted by ascending precidence of the
3237          ;; keep_flag.
3238          (setq dlist (nconc dlist
3239                             (mapcar (lambda (e)
3240                                       (list e nil 'unread  nil))
3241                                     unreads)))
3242          (setq dlist (nconc dlist
3243                             (mapcar (lambda (e)
3244                                       (list e nil 'marked  nil))
3245                                     marked)))
3246          (setq dlist (nconc dlist
3247                             (mapcar (lambda (e)
3248                                       (list e nil 'special nil))
3249                                     specials)))
3250
3251          (set-buffer overview)
3252          (erase-buffer)
3253          (buffer-disable-undo)
3254          (when (file-exists-p nov-file)
3255            (gnus-message 7 "gnus-agent-expire: Loading overview...")
3256            (nnheader-insert-file-contents nov-file)
3257            (goto-char (point-min))
3258         
3259            (let (p)
3260              (while (< (setq p (point)) (point-max))
3261                (condition-case nil
3262                    ;; If I successfully read an integer (the plus zero
3263                    ;; ensures a numeric type), append the position
3264                    ;; to the list
3265                    (push (list (+ 0 (read (current-buffer))) nil nil
3266                                p)
3267                          dlist)
3268                  (error
3269                   (gnus-message 1 "gnus-agent-expire: read error \
3270 occurred when reading expression at %s in %s.  Skipping to next \
3271 line." (point) nov-file)))
3272                ;; Whether I succeeded, or failed, it doesn't matter.
3273                ;; Move to the next line then try again.
3274                (forward-line 1)))
3275
3276            (gnus-message
3277             7 "gnus-agent-expire: Loading overview... Done"))
3278          (set-buffer-modified-p nil)
3279
3280          ;; At this point, all of the information is in dlist.  The
3281          ;; only problem is that much of it is spread across multiple
3282          ;; entries.  Sort then MERGE!!
3283          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
3284          ;; If two entries have the same article-number then sort by
3285          ;; ascending keep_flag.
3286          (let ((special 0)
3287                (marked 1)
3288                (unread 2))
3289            (setq dlist
3290                  (sort dlist
3291                        (lambda (a b)
3292                          (cond ((< (nth 0 a) (nth 0 b))
3293                                 t)
3294                                ((> (nth 0 a) (nth 0 b))
3295                                 nil)
3296                                (t
3297                                 (let ((a (or (symbol-value (nth 2 a))
3298                                              3))
3299                                       (b (or (symbol-value (nth 2 b))
3300                                              3)))
3301                                   (<= a b))))))))
3302          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3303          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3304          (let ((dlist dlist))
3305            (while (cdr dlist)           ; I'm not at the end-of-list
3306              (if (eq (caar dlist) (caadr dlist))
3307                  (let ((first (cdr (car dlist)))
3308                        (secnd (cdr (cadr dlist))))
3309                    (setcar first (or (car first)
3310                                      (car secnd))) ; fetch_date
3311                    (setq first (cdr first)
3312                          secnd (cdr secnd))
3313                    (setcar first (or (car first)
3314                                      (car secnd))) ; Keep_flag
3315                    (setq first (cdr first)
3316                          secnd (cdr secnd))
3317                    (setcar first (or (car first)
3318                                      (car secnd))) ; NOV_entry_position
3319
3320                    (setcdr dlist (cddr dlist)))
3321                (setq dlist (cdr dlist)))))
3322
3323          ;; Check the order of the entry positions.  They should be in
3324          ;; ascending order.  If they aren't, the positions must be
3325          ;; converted to markers.
3326          (when (let ((dlist dlist)
3327                      (prev-pos -1)
3328                      pos)
3329                  (while dlist
3330                    (if (setq pos (nth 3 (pop dlist)))
3331                        (if (< pos prev-pos)
3332                            (throw 'sort-results 'unsorted)
3333                          (setq prev-pos pos)))))
3334            (gnus-message 7 "gnus-agent-expire: Unsorted overview; inserting markers to compensate.")
3335            (mapcar (lambda (entry)
3336                      (let ((pos (nth 3 entry)))
3337                        (if pos
3338                            (setf (nth 3 entry)
3339                                  (set-marker (make-marker)
3340                                              pos)))))
3341                    dlist))
3342
3343          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3344
3345          (let* ((len (float (length dlist)))
3346                 (alist (list nil))
3347                 (tail-alist alist)
3348                 (position-offset 0)
3349                 )
3350
3351            (while dlist
3352              (let ((new-completed (truncate (* 100.0
3353                                                (/ (setq cnt (1+ cnt))
3354                                                   len))))
3355                    message-log-max)
3356                (when (> new-completed completed)
3357                  (setq completed new-completed)
3358                  (gnus-message 7 "%3d%% completed..."  completed)))
3359              (let* ((entry          (car dlist))
3360                     (article-number (nth 0 entry))
3361                     (fetch-date     (nth 1 entry))
3362                     (keep           (nth 2 entry))
3363                     (marker         (nth 3 entry)))
3364
3365                (cond
3366                 ;; Kept articles are unread, marked, or special.
3367                 (keep
3368                  (gnus-agent-message 10
3369                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3370                                      group article-number keep (if fetch-date " and file" ""))
3371                  (when fetch-date
3372                    (unless (file-exists-p
3373                             (concat dir (number-to-string
3374                                          article-number)))
3375                      (setf (nth 1 entry) nil)
3376                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3377 download flag on %s:%d as the cached article file is missing."
3378                                          group (caar dlist)))
3379                    (unless marker
3380                      (gnus-message 1 "gnus-agent-expire detected a \
3381 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3382                  (gnus-agent-append-to-list
3383                   tail-alist
3384                   (cons article-number fetch-date)))
3385
3386                 ;; The following articles are READ, UNMARKED, and
3387                 ;; ORDINARY.  See if they can be EXPIRED!!!
3388                 ((setq type
3389                        (cond
3390                         ((not (integerp fetch-date))
3391                          'read) ;; never fetched article (may expire
3392                         ;; right now)
3393                         ((not (file-exists-p
3394                                (concat dir (number-to-string
3395                                             article-number))))
3396                          (setf (nth 1 entry) nil)
3397                          'externally-expired) ;; Can't find the cached
3398                         ;; article.  Handle case
3399                         ;; as though this article
3400                         ;; was never fetched.
3401
3402                         ;; We now have the arrival day, so we see
3403                         ;; whether it's old enough to be expired.
3404                         ((< fetch-date day)
3405                          'expired)
3406                         (force
3407                          'forced)))
3408
3409                  ;; I found some reason to expire this entry.
3410
3411                  (let ((actions nil))
3412                    (when (memq type '(forced expired))
3413                      (ignore-errors     ; Just being paranoid.
3414                        (let* ((file-name (nnheader-concat dir (number-to-string
3415                                                                article-number)))
3416                               (size (float (nth 7 (file-attributes file-name)))))
3417                          (incf bytes-freed size)
3418                          (incf size-files-deleted size)
3419                          (incf files-deleted)
3420                          (delete-file file-name))
3421                        (push "expired cached article" actions))
3422                      (setf (nth 1 entry) nil)
3423                      )
3424
3425                    (when marker
3426                      (push "NOV entry removed" actions)
3427
3428                      (goto-char (if (markerp marker)
3429                                     marker
3430                                   (- marker position-offset)))
3431
3432                      (incf nov-entries-deleted)
3433
3434                      (let* ((from (point-at-bol))
3435                             (to (progn (forward-line 1) (point)))
3436                             (freed (- to from)))
3437                        (incf bytes-freed freed)
3438                        (incf position-offset freed)
3439                        (delete-region from to)))
3440
3441                    ;; If considering all articles is set, I can only
3442                    ;; expire article IDs that are no longer in the
3443                    ;; active range (That is, articles that preceed the
3444                    ;; first article in the new alist).
3445                    (if (and gnus-agent-consider-all-articles
3446                             (>= article-number (car active)))
3447                        ;; I have to keep this ID in the alist
3448                        (gnus-agent-append-to-list
3449                         tail-alist (cons article-number fetch-date))
3450                      (push (format "Removed %s article number from \
3451 article alist" type) actions))
3452
3453                    (when actions
3454                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3455                                          group article-number
3456                                          (mapconcat 'identity actions ", ")))))
3457                 (t
3458                  (gnus-agent-message
3459                   10 "gnus-agent-expire: %s:%d: Article kept as \
3460 expiration tests failed." group article-number)
3461                  (gnus-agent-append-to-list
3462                   tail-alist (cons article-number fetch-date)))
3463                 )
3464
3465                ;; Remove markers as I intend to reuse this buffer again.
3466                (when (and marker
3467                           (markerp marker))
3468                  (set-marker marker nil))
3469
3470                (setq dlist (cdr dlist))))
3471
3472            (setq alist (cdr alist))
3473
3474            (let ((inhibit-quit t))
3475              (unless (equal alist gnus-agent-article-alist)
3476                (setq gnus-agent-article-alist alist)
3477                (gnus-agent-save-alist group))
3478
3479              (when (buffer-modified-p)
3480                (let ((coding-system-for-write
3481                       gnus-agent-file-coding-system))
3482                  (gnus-make-directory dir)
3483                  (write-region (point-min) (point-max) nov-file nil
3484                                'silent)
3485                  ;; clear the modified flag as that I'm not confused by
3486                  ;; its status on the next pass through this routine.
3487                  (set-buffer-modified-p nil)
3488                  (gnus-agent-update-view-total-fetched-for group t)))
3489
3490              (when (eq articles t)
3491                (gnus-summary-update-info))))
3492
3493          (when (boundp 'gnus-agent-expire-stats)
3494            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3495              (incf (nth 2 stats) bytes-freed)
3496              (incf (nth 1 stats) files-deleted)
3497              (incf (nth 0 stats) nov-entries-deleted)))
3498
3499          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3500
3501 (defun gnus-agent-expire (&optional articles group force)
3502   "Expire all old articles.
3503 If you want to force expiring of certain articles, this function can
3504 take ARTICLES, GROUP and FORCE parameters as well.
3505
3506 The articles on which the expiration process runs are selected as follows:
3507   if ARTICLES is null, all read and unmarked articles.
3508   if ARTICLES is t, all articles.
3509   if ARTICLES is a list, just those articles.
3510 Setting GROUP will limit expiration to that group.
3511 FORCE is equivalent to setting the expiration predicates to true."
3512   (interactive)
3513
3514   (if group
3515       (gnus-agent-expire-group group articles force)
3516     (if (or (not (eq articles t))
3517             (yes-or-no-p "Are you sure that you want to expire all \
3518 articles in every agentized group? "))
3519         (let ((methods (gnus-agent-covered-methods))
3520               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3521               ;; of agent directories.
3522               (gnus-agent-expire-current-dirs nil)
3523               ;; Bind gnus-agent-expire-stats to enable tracking of
3524               ;; expiration statistics across all groups
3525               (gnus-agent-expire-stats (list 0 0 0.0))
3526               gnus-command-method overview orig)
3527           (setq overview (gnus-get-buffer-create " *expire overview*"))
3528           (unwind-protect
3529               (while (setq gnus-command-method (pop methods))
3530                 (let ((active-file (gnus-agent-lib-file "active")))
3531                   (when (file-exists-p active-file)
3532                     (with-temp-buffer
3533                       (nnheader-insert-file-contents active-file)
3534                       (gnus-active-to-gnus-format
3535                        gnus-command-method
3536                        (setq orig (gnus-make-hashtable
3537                                    (count-lines (point-min) (point-max))))))
3538                     (dolist (expiring-group (gnus-groups-from-server
3539                                              gnus-command-method))
3540                       (let* ((active
3541                               (gnus-gethash-safe expiring-group orig)))
3542
3543                         (when active
3544                           (save-excursion
3545                             (gnus-agent-expire-group-1
3546                              expiring-group overview active articles force))))))))
3547             (kill-buffer overview))
3548           (gnus-agent-expire-unagentized-dirs)
3549           (gnus-message 4 (gnus-agent-expire-done-message))))))
3550
3551 (defun gnus-agent-expire-done-message ()
3552   (if (and (> gnus-verbose 4)
3553            (boundp 'gnus-agent-expire-stats))
3554       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3555              (size (nth 2 stats))
3556             (units '(B KB MB GB)))
3557         (while (and (> size 1024.0)
3558                     (cdr units))
3559           (setq size (/ size 1024.0)
3560                 units (cdr units)))
3561
3562         (format "Expiry recovered %d NOV entries, deleted %d files,\
3563  and freed %f %s."
3564                 (nth 0 stats)
3565                 (nth 1 stats)
3566                 size (car units)))
3567     "Expiry...done"))
3568
3569 (defun gnus-agent-expire-unagentized-dirs ()
3570   (when (and gnus-agent-expire-unagentized-dirs
3571              (boundp 'gnus-agent-expire-current-dirs))
3572     (let* ((keep (gnus-make-hashtable))
3573            ;; Formally bind gnus-agent-expire-current-dirs so that the
3574            ;; compiler will not complain about free references.
3575            (gnus-agent-expire-current-dirs
3576             (symbol-value 'gnus-agent-expire-current-dirs))
3577            dir)
3578
3579       (gnus-sethash gnus-agent-directory t keep)
3580       (while gnus-agent-expire-current-dirs
3581         (setq dir (pop gnus-agent-expire-current-dirs))
3582         (when (and (stringp dir)
3583                    (file-directory-p dir))
3584           (while (not (gnus-gethash dir keep))
3585             (gnus-sethash dir t keep)
3586             (setq dir (file-name-directory (directory-file-name dir))))))
3587
3588       (let* (to-remove
3589              checker
3590              (checker
3591               (function
3592                (lambda (d)
3593                  "Given a directory, check it and its subdirectories for
3594               membership in the keep hash.  If it isn't found, add
3595               it to to-remove."
3596                  (let ((files (directory-files d))
3597                        file)
3598                    (while (setq file (pop files))
3599                      (cond ((equal file ".") ; Ignore self
3600                             nil)
3601                            ((equal file "..") ; Ignore parent
3602                             nil)
3603                            ((equal file ".overview")
3604                             ;; Directory must contain .overview to be
3605                             ;; agent's cache of a group.
3606                             (let ((d (file-name-as-directory d))
3607                                   r)
3608                               ;; Search ancestor's for last directory NOT
3609                               ;; found in keep hash.
3610                               (while (not (gnus-gethash
3611                                            (setq d (file-name-directory d)) keep))
3612                                 (setq r d
3613                                       d (directory-file-name d)))
3614                               ;; if ANY ancestor was NOT in keep hash and
3615                               ;; it it's already in to-remove, add it to
3616                               ;; to-remove.
3617                               (if (and r
3618                                        (not (member r to-remove)))
3619                                   (push r to-remove))))
3620                            ((file-directory-p (setq file (nnheader-concat d file)))
3621                             (funcall checker file)))))))))
3622         (funcall checker (expand-file-name gnus-agent-directory))
3623
3624         (when (and to-remove
3625                    (or gnus-expert-user
3626                        (gnus-y-or-n-p
3627                         "gnus-agent-expire has identified local directories that are\
3628  not currently required by any agentized group.  Do you wish to consider\
3629  deleting them?")))
3630           (while to-remove
3631             (let ((dir (pop to-remove)))
3632               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3633                   (let* (delete-recursive
3634                          (delete-recursive
3635                           (function
3636                            (lambda (f-or-d)
3637                              (ignore-errors
3638                                (if (file-directory-p f-or-d)
3639                                    (condition-case nil
3640                                        (delete-directory f-or-d)
3641                                      (file-error
3642                                       (mapcar (lambda (f)
3643                                                 (or (member f '("." ".."))
3644                                                     (funcall delete-recursive
3645                                                              (nnheader-concat
3646                                                               f-or-d f))))
3647                                               (directory-files f-or-d))
3648                                       (delete-directory f-or-d)))
3649                                  (delete-file f-or-d)))))))
3650                     (funcall delete-recursive dir))))))))))
3651
3652 ;;;###autoload
3653 (defun gnus-agent-batch ()
3654   "Start Gnus, send queue and fetch session."
3655   (interactive)
3656   (let ((init-file-user "")
3657         (gnus-always-read-dribble-file t))
3658     (gnus))
3659   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3660     (gnus-group-send-queue)
3661     (gnus-agent-fetch-session)))
3662
3663 (defun gnus-agent-unread-articles (group)
3664   (let* ((read (gnus-info-read (gnus-get-info group)))
3665          (known (gnus-agent-load-alist group))
3666          (unread (list nil))
3667          (tail-unread unread))
3668     (while (and known read)
3669       (let ((candidate (car (pop known))))
3670         (while (let* ((range (car read))
3671                       (min   (if (numberp range) range (car range)))
3672                       (max   (if (numberp range) range (cdr range))))
3673                  (cond ((or (not min)
3674                             (< candidate min))
3675                         (gnus-agent-append-to-list tail-unread candidate)
3676                         nil)
3677                        ((> candidate max)
3678                         (setq read (cdr read))
3679                         ;; return t so that I always loop one more
3680                         ;; time.  If I just iterated off the end of
3681                         ;; read, min will become nil and the current
3682                         ;; candidate will be added to the unread list.
3683                         t))))))
3684     (while known
3685       (gnus-agent-append-to-list tail-unread (car (pop known))))
3686     (cdr unread)))
3687
3688 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3689   "Restrict ARTICLES to numbers already fetched.
3690 Returns a sublist of ARTICLES that excludes those article ids in GROUP
3691 that have already been fetched.
3692 If CACHED-HEADER is nil, articles are only excluded if the article itself
3693 has been fetched."
3694
3695   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3696   ;; 'car gnus-agent-article-alist))
3697
3698   ;; Functionally, I don't need to construct a temp list using mapcar.
3699
3700   (if (and (or gnus-agent-cache (not gnus-plugged))
3701            (gnus-agent-load-alist group))
3702     (let* ((ref gnus-agent-article-alist)
3703            (arts articles)
3704            (uncached (list nil))
3705            (tail-uncached uncached))
3706       (while (and ref arts)
3707         (let ((v1 (car arts))
3708               (v2 (caar ref)))
3709           (cond ((< v1 v2) ; v1 does not appear in the reference list
3710                  (gnus-agent-append-to-list tail-uncached v1)
3711                  (setq arts (cdr arts)))
3712                 ((= v1 v2)
3713                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3714                    (gnus-agent-append-to-list tail-uncached v1))
3715                  (setq arts (cdr arts))
3716                  (setq ref (cdr ref)))
3717                 (t ; reference article (v2) preceeds the list being filtered
3718                  (setq ref (cdr ref))))))
3719       (while arts
3720         (gnus-agent-append-to-list tail-uncached (pop arts)))
3721       (cdr uncached))
3722     ;; if gnus-agent-load-alist fails, no articles are cached.
3723     articles))
3724
3725 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3726   (save-excursion
3727     (gnus-agent-create-buffer)
3728     (let ((gnus-decode-encoded-word-function 'identity)
3729           (gnus-decode-encoded-address-function 'identity)
3730           (file (gnus-agent-article-name ".overview" group))
3731           cached-articles uncached-articles
3732           (file-name-coding-system nnmail-pathname-coding-system))
3733       (gnus-make-directory (nnheader-translate-file-chars
3734                             (file-name-directory file) t))
3735
3736       ;; Populate temp buffer with known headers
3737       (when (file-exists-p file)
3738         (with-current-buffer gnus-agent-overview-buffer
3739           (erase-buffer)
3740           (let ((nnheader-file-coding-system
3741                  gnus-agent-file-coding-system))
3742             (nnheader-insert-nov-file file (car articles)))))
3743
3744       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3745                                                                 t))
3746           (progn
3747             ;; Populate nntp-server-buffer with uncached headers
3748             (set-buffer nntp-server-buffer)
3749             (erase-buffer)
3750             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3751                                    (gnus-retrieve-headers
3752                                     uncached-articles group fetch-old))))
3753                    (nnvirtual-convert-headers))
3754                   ((eq 'nntp (car gnus-current-select-method))
3755                    ;; The author of gnus-get-newsgroup-headers-xover
3756                    ;; reports that the XOVER command is commonly
3757                    ;; unreliable. The problem is that recently
3758                    ;; posted articles may not be entered into the
3759                    ;; NOV database in time to respond to my XOVER
3760                    ;; query.
3761                    ;;
3762                    ;; I'm going to use his assumption that the NOV
3763                    ;; database is updated in order of ascending
3764                    ;; article ID.  Therefore, a response containing
3765                    ;; article ID N implies that all articles from 1
3766                    ;; to N-1 are up-to-date.  Therefore, missing
3767                    ;; articles in that range have expired.
3768
3769                    (set-buffer nntp-server-buffer)
3770                    (let* ((fetched-articles (list nil))
3771                           (tail-fetched-articles fetched-articles)
3772                           (min (cond ((numberp fetch-old)
3773                                       (max 1 (- (car articles) fetch-old)))
3774                                      (fetch-old
3775                                       1)
3776                                      (t
3777                                       (car articles))))
3778                           (max (car (last articles))))
3779
3780                      ;; Get the list of articles that were fetched
3781                      (goto-char (point-min))
3782                      (let ((pm (point-max))
3783                            art)
3784                        (while (< (point) pm)
3785                          (when (setq art (gnus-agent-read-article-number))
3786                            (gnus-agent-append-to-list tail-fetched-articles art))
3787                          (forward-line 1)))
3788
3789                      ;; Clip this list to the headers that will
3790                      ;; actually be returned
3791                      (setq fetched-articles (gnus-list-range-intersection
3792                                              (cdr fetched-articles)
3793                                              (cons min max)))
3794
3795                      ;; Clip the uncached articles list to exclude
3796                      ;; IDs after the last FETCHED header.  The
3797                      ;; excluded IDs may be fetchable using HEAD.
3798                      (if (car tail-fetched-articles)
3799                          (setq uncached-articles
3800                                (gnus-list-range-intersection
3801                                 uncached-articles
3802                                 (cons (car uncached-articles)
3803                                       (car tail-fetched-articles)))))
3804
3805                      ;; Create the list of articles that were
3806                      ;; "successfully" fetched.  Success, in this
3807                      ;; case, means that the ID should not be
3808                      ;; fetched again.  In the case of an expired
3809                      ;; article, the header will not be fetched.
3810                      (setq uncached-articles
3811                            (gnus-sorted-nunion fetched-articles
3812                                                uncached-articles))
3813                      )))
3814
3815             ;; Erase the temp buffer
3816             (set-buffer gnus-agent-overview-buffer)
3817             (erase-buffer)
3818
3819             ;; Copy the nntp-server-buffer to the temp buffer
3820             (set-buffer nntp-server-buffer)
3821             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3822
3823             ;; Merge the temp buffer with the known headers (found on
3824             ;; disk in FILE) into the nntp-server-buffer
3825             (when uncached-articles
3826               (gnus-agent-braid-nov group uncached-articles file))
3827
3828             ;; Save the new set of known headers to FILE
3829             (set-buffer nntp-server-buffer)
3830             (let ((coding-system-for-write
3831                    gnus-agent-file-coding-system))
3832               (gnus-agent-check-overview-buffer)
3833               (write-region (point-min) (point-max) file nil 'silent))
3834
3835             (gnus-agent-update-view-total-fetched-for group t)
3836
3837             ;; Update the group's article alist to include the newly
3838             ;; fetched articles.
3839             (gnus-agent-load-alist group)
3840             (gnus-agent-save-alist group uncached-articles nil)
3841             )
3842
3843         ;; Copy the temp buffer to the nntp-server-buffer
3844         (set-buffer nntp-server-buffer)
3845         (erase-buffer)
3846         (insert-buffer-substring gnus-agent-overview-buffer)))
3847
3848     (if (and fetch-old
3849              (not (numberp fetch-old)))
3850         t                               ; Don't remove anything.
3851       (nnheader-nov-delete-outside-range
3852        (if fetch-old (max 1 (- (car articles) fetch-old))
3853          (car articles))
3854        (car (last articles)))
3855       t)
3856
3857     'nov))
3858
3859 (defun gnus-agent-request-article (article group)
3860   "Retrieve ARTICLE in GROUP from the agent cache."
3861   (when (and gnus-agent
3862              (or gnus-agent-cache
3863                  (not gnus-plugged))
3864              (numberp article))
3865     (let* ((gnus-command-method (gnus-find-method-for-group group))
3866            (file (gnus-agent-article-name (number-to-string article) group))
3867            (buffer-read-only nil)
3868            (file-name-coding-system nnmail-pathname-coding-system))
3869       (when (and (file-exists-p file)
3870                  (> (nth 7 (file-attributes file)) 0))
3871         (erase-buffer)
3872         (gnus-kill-all-overlays)
3873         (let ((coding-system-for-read gnus-cache-coding-system))
3874           (insert-file-contents file))
3875         t))))
3876
3877 (defun gnus-agent-regenerate-group (group &optional reread)
3878   "Regenerate GROUP.
3879 If REREAD is t, all articles in the .overview are marked as unread.
3880 If REREAD is a list, the specified articles will be marked as unread.
3881 In addition, their NOV entries in .overview will be refreshed using
3882 the articles' current headers.
3883 If REREAD is not nil, downloaded articles are marked as unread."
3884   (interactive
3885    (list (let ((def (or (gnus-group-group-name)
3886                         gnus-newsgroup-name)))
3887            (let ((select (read-string (if def
3888                                           (concat "Group Name ("
3889                                                   def "): ")
3890                                         "Group Name: "))))
3891              (if (and (equal "" select)
3892                       def)
3893                  def
3894                select)))
3895          (catch 'mark
3896            (while (let (c
3897                         (cursor-in-echo-area t)
3898                         (echo-keystrokes 0))
3899                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3900                     (setq c (read-char-exclusive))
3901
3902                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3903                            (throw 'mark nil))
3904                           ((or (eq c ?a) (eq c ?A))
3905                            (throw 'mark t))
3906                           ((or (eq c ?d) (eq c ?D))
3907                            (throw 'mark 'some)))
3908                     (gnus-message 3 "Ignoring unexpected input")
3909                     (sit-for 1)
3910                     t)))))
3911   (when group
3912     (gnus-message 5 "Regenerating in %s" group)
3913     (let* ((gnus-command-method (or gnus-command-method
3914                                     (gnus-find-method-for-group group)))
3915            (file (gnus-agent-article-name ".overview" group))
3916            (dir (file-name-directory file))
3917            point
3918            (file-name-coding-system nnmail-pathname-coding-system)
3919            (downloaded (if (file-exists-p dir)
3920                            (sort (delq nil (mapcar (lambda (name)
3921                                                      (and (not (file-directory-p (nnheader-concat dir name)))
3922                                                           (string-to-number name)))
3923                                                    (directory-files dir nil "^[0-9]+$" t)))
3924                                  '>)
3925                          (progn (gnus-make-directory dir) nil)))
3926            dl nov-arts
3927            alist header
3928            regenerated)
3929
3930       (mm-with-unibyte-buffer
3931         (if (file-exists-p file)
3932             (let ((nnheader-file-coding-system
3933                    gnus-agent-file-coding-system))
3934               (nnheader-insert-file-contents file)))
3935         (set-buffer-modified-p nil)
3936
3937         ;; Load the article IDs found in the overview file.  As a
3938         ;; side-effect, validate the file contents.
3939         (let ((load t))
3940           (while load
3941             (setq load nil)
3942             (goto-char (point-min))
3943             (while (< (point) (point-max))
3944               (cond ((and (looking-at "[0-9]+\t")
3945                           (<= (- (match-end 0) (match-beginning 0)) 9))
3946                      (push (read (current-buffer)) nov-arts)
3947                      (forward-line 1)
3948                      (let ((l1 (car nov-arts))
3949                            (l2 (cadr nov-arts)))
3950                        (cond ((and (listp reread) (memq l1 reread))
3951                               (gnus-delete-line)
3952                               (setq nov-arts (cdr nov-arts))
3953                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3954  entry of article %s deleted." l1))
3955                              ((not l2)
3956                               nil)
3957                              ((< l1 l2)
3958                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3959  entries are NOT in ascending order.")
3960                               ;; Don't sort now as I haven't verified
3961                               ;; that every line begins with a number
3962                               (setq load t))
3963                              ((= l1 l2)
3964                               (forward-line -1)
3965                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3966  entries contained duplicate of article %s.      Duplicate deleted." l1)
3967                               (gnus-delete-line)
3968                               (setq nov-arts (cdr nov-arts))))))
3969                     (t
3970                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3971  entries contained line that did not begin with an article number.  Deleted\
3972  line.")
3973                      (gnus-delete-line))))
3974             (when load
3975               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3976  entries into ascending order.")
3977               (sort-numeric-fields 1 (point-min) (point-max))
3978               (setq nov-arts nil))))
3979         (gnus-agent-check-overview-buffer)
3980
3981         ;; Construct a new article alist whose nodes match every header
3982         ;; in the .overview file.  As a side-effect, missing headers are
3983         ;; reconstructed from the downloaded article file.
3984         (while (or downloaded nov-arts)
3985           (cond ((and downloaded
3986                       (or (not nov-arts)
3987                           (> (car downloaded) (car nov-arts))))
3988                  ;; This entry is missing from the overview file
3989                  (gnus-message 3 "Regenerating NOV %s %d..." group
3990                                (car downloaded))
3991                  (let ((file (concat dir (number-to-string (car downloaded)))))
3992                    (mm-with-unibyte-buffer
3993                      (nnheader-insert-file-contents file)
3994                      (nnheader-remove-body)
3995                      (setq header (nnheader-parse-naked-head)))
3996                    (mail-header-set-number header (car downloaded))
3997                    (if nov-arts
3998                        (let ((key (concat "^" (int-to-string (car nov-arts))
3999                                           "\t")))
4000                          (or (re-search-backward key nil t)
4001                              (re-search-forward key))
4002                          (forward-line 1))
4003                      (goto-char (point-min)))
4004                    (nnheader-insert-nov header))
4005                  (setq nov-arts (cons (car downloaded) nov-arts)))
4006                 ((eq (car downloaded) (car nov-arts))
4007                  ;; This entry in the overview has been downloaded
4008                  (push (cons (car downloaded)
4009                              (time-to-days
4010                               (nth 5 (file-attributes
4011                                       (concat dir (number-to-string
4012                                                    (car downloaded))))))) alist)
4013                  (setq downloaded (cdr downloaded))
4014                  (setq nov-arts (cdr nov-arts)))
4015                 (t
4016                  ;; This entry in the overview has not been downloaded
4017                  (push (cons (car nov-arts) nil) alist)
4018                  (setq nov-arts (cdr nov-arts)))))
4019
4020         ;; When gnus-agent-consider-all-articles is set,
4021         ;; gnus-agent-regenerate-group should NOT remove article IDs from
4022         ;; the alist.  Those IDs serve as markers to indicate that an
4023         ;; attempt has been made to fetch that article's header.
4024
4025         ;; When gnus-agent-consider-all-articles is NOT set,
4026         ;; gnus-agent-regenerate-group can remove the article ID of every
4027         ;; article (with the exception of the last ID in the list - it's
4028         ;; special) that no longer appears in the overview.  In this
4029         ;; situtation, the last article ID in the list implies that it,
4030         ;; and every article ID preceeding it, have been fetched from the
4031         ;; server.
4032
4033         (if gnus-agent-consider-all-articles
4034             ;; Restore all article IDs that were not found in the overview file.
4035             (let* ((n (cons nil alist))
4036                    (merged n)
4037                    (o (gnus-agent-load-alist group)))
4038               (while o
4039                 (let ((nID (caadr n))
4040                       (oID (caar o)))
4041                   (cond ((not nID)
4042                          (setq n (setcdr n (list (list oID))))
4043                          (setq o (cdr o)))
4044                         ((< oID nID)
4045                          (setcdr n (cons (list oID) (cdr n)))
4046                          (setq o (cdr o)))
4047                         ((= oID nID)
4048                          (setq o (cdr o))
4049                          (setq n (cdr n)))
4050                         (t
4051                          (setq n (cdr n))))))
4052               (setq alist (cdr merged)))
4053           ;; Restore the last article ID if it is not already in the new alist
4054           (let ((n (last alist))
4055                 (o (last (gnus-agent-load-alist group))))
4056             (cond ((not o)
4057                    nil)
4058                   ((not n)
4059                    (push (cons (caar o) nil) alist))
4060                   ((< (caar n) (caar o))
4061                    (setcdr n (list (car o)))))))
4062
4063         (let ((inhibit-quit t))
4064           (if (setq regenerated (buffer-modified-p))
4065               (let ((coding-system-for-write gnus-agent-file-coding-system))
4066                 (write-region (point-min) (point-max) file nil 'silent)))
4067
4068           (setq regenerated (or regenerated
4069                                 (and reread gnus-agent-article-alist)
4070                                 (not (equal alist gnus-agent-article-alist))))
4071
4072           (setq gnus-agent-article-alist alist)
4073
4074           (when regenerated
4075             (gnus-agent-save-alist group)
4076
4077             ;; I have to alter the group's active range NOW as
4078             ;; gnus-make-ascending-articles-unread will use it to
4079             ;; recalculate the number of unread articles in the group
4080
4081             (let ((group (gnus-group-real-name group))
4082                   (group-active (or (gnus-active group)
4083                                     (gnus-activate-group group))))
4084               (gnus-agent-possibly-alter-active group group-active)))))
4085
4086       (when (and reread gnus-agent-article-alist)
4087         (gnus-agent-synchronize-group-flags
4088          group
4089          (list (list
4090                 (if (listp reread)
4091                     reread
4092                   (delq nil (mapcar (function (lambda (c)
4093                                                 (cond ((eq reread t)
4094                                                        (car c))
4095                                                       ((cdr c)
4096                                                        (car c)))))
4097                                     gnus-agent-article-alist)))
4098                 'del '(read)))
4099          gnus-command-method)
4100
4101         (when regenerated
4102           (gnus-agent-update-files-total-fetched-for group nil)))
4103
4104       (gnus-message 5 "")
4105       regenerated)))
4106
4107 ;;;###autoload
4108 (defun gnus-agent-regenerate (&optional clean reread)
4109   "Regenerate all agent covered files.
4110 If CLEAN, obsolete (ignore)."
4111   (interactive "P")
4112   (let (regenerated)
4113     (gnus-message 4 "Regenerating Gnus agent files...")
4114     (dolist (gnus-command-method (gnus-agent-covered-methods))
4115         (dolist (group (gnus-groups-from-server gnus-command-method))
4116           (setq regenerated (or (gnus-agent-regenerate-group group reread)
4117                                 regenerated))))
4118     (gnus-message 4 "Regenerating Gnus agent files...done")
4119
4120     regenerated))
4121
4122 (defun gnus-agent-go-online (&optional force)
4123   "Switch servers into online status."
4124   (interactive (list t))
4125   (dolist (server gnus-opened-servers)
4126     (when (eq (nth 1 server) 'offline)
4127       (if (if (eq force 'ask)
4128               (gnus-y-or-n-p
4129                (format "Switch %s:%s into online status? "
4130                        (caar server) (cadar server)))
4131             force)
4132           (setcar (nthcdr 1 server) 'close)))))
4133
4134 (defun gnus-agent-toggle-group-plugged (group)
4135   "Toggle the status of the server of the current group."
4136   (interactive (list (gnus-group-group-name)))
4137   (let* ((method (gnus-find-method-for-group group))
4138          (status (cadr (assoc method gnus-opened-servers))))
4139     (if (eq status 'offline)
4140         (gnus-server-set-status method 'closed)
4141       (gnus-close-server method)
4142       (gnus-server-set-status method 'offline))
4143     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
4144              (if (eq status 'offline) 'offline 'online)
4145              (if (eq status 'offline) 'online 'offline))))
4146
4147 (defun gnus-agent-group-covered-p (group)
4148   (gnus-agent-method-p (gnus-group-method group)))
4149
4150 (defun gnus-agent-update-files-total-fetched-for
4151   (group delta &optional method path)
4152   "Update, or set, the total disk space used by the articles that the
4153 agent has fetched."
4154   (when gnus-agent-total-fetched-hashtb
4155     (gnus-agent-with-refreshed-group
4156      group
4157      ;; if null, gnus-agent-group-pathname will calc method.
4158      (let* ((gnus-command-method method)
4159             (path (or path (gnus-agent-group-pathname group)))
4160             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4161                        (gnus-sethash path (make-list 3 0)
4162                                      gnus-agent-total-fetched-hashtb)))
4163             (file-name-coding-system nnmail-pathname-coding-system))
4164        (when (listp delta)
4165          (if delta
4166              (let ((sum 0.0)
4167                    file)
4168                (while (setq file (pop delta))
4169                  (incf sum (float (or (nth 7 (file-attributes
4170                                               (nnheader-concat
4171                                                path
4172                                                (if (numberp file)
4173                                                    (number-to-string file)
4174                                                  file)))) 0))))
4175                (setq delta sum))
4176            (let ((sum (- (nth 2 entry)))
4177                  (info (directory-files-and-attributes path nil "^-?[0-9]+$" t))
4178                  file)
4179              (while (setq file (pop info))
4180                (incf sum (float (or (nth 8 file) 0))))
4181              (setq delta sum))))
4182
4183        (setq gnus-agent-need-update-total-fetched-for t)
4184        (incf (nth 2 entry) delta)))))
4185
4186 (defun gnus-agent-update-view-total-fetched-for
4187   (group agent-over &optional method path)
4188   "Update, or set, the total disk space used by the .agentview and
4189 .overview files.  These files are calculated separately as they can be
4190 modified."
4191   (when gnus-agent-total-fetched-hashtb
4192     (gnus-agent-with-refreshed-group
4193      group
4194      ;; if null, gnus-agent-group-pathname will calc method.
4195      (let* ((gnus-command-method method)
4196             (path (or path (gnus-agent-group-pathname group)))
4197             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4198                        (gnus-sethash path (make-list 3 0)
4199                                      gnus-agent-total-fetched-hashtb)))
4200             (file-name-coding-system nnmail-pathname-coding-system)
4201             (size (or (nth 7 (file-attributes
4202                               (nnheader-concat
4203                                path (if agent-over
4204                                         ".overview"
4205                                       ".agentview"))))
4206                       0)))
4207        (setq gnus-agent-need-update-total-fetched-for t)
4208        (setf (nth (if agent-over 1 0) entry) size)))))
4209
4210 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
4211   "Get the total disk space used by the specified GROUP."
4212   (unless (equal group "dummy.group")
4213     (unless gnus-agent-total-fetched-hashtb
4214       (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
4215
4216     ;; if null, gnus-agent-group-pathname will calc method.
4217     (let* ((gnus-command-method method)
4218            (path (gnus-agent-group-pathname group))
4219            (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
4220       (if entry
4221           (apply '+ entry)
4222         (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
4223           (+
4224            (gnus-agent-update-view-total-fetched-for  group nil method path)
4225            (gnus-agent-update-view-total-fetched-for  group t   method path)
4226            (gnus-agent-update-files-total-fetched-for group nil method path)))))))
4227
4228 (provide 'gnus-agent)
4229
4230 ;;; arch-tag: b0ba4afc-5229-4cee-ad25-9956daa4e91e
4231 ;;; gnus-agent.el ends here