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