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