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