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