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