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