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