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