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