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