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