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