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