7301da6f6bbb3aff8cbb1fe6810f11858cbdf916
[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          (progn
977            (setq gnus-newsgroup-downloadable
978                  (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
979            gnus-downloadable-mark)
980          )
981        'unread))))
982
983 (defun gnus-agent-get-undownloaded-list ()
984   "Construct list of articles that have not been downloaded."
985   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
986     (when (set (make-local-variable 'gnus-newsgroup-agentized)
987                (gnus-agent-method-p gnus-command-method))
988       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
989              (headers (sort (mapcar (lambda (h)
990                                       (mail-header-number h))
991                                     gnus-newsgroup-headers) '<))
992              (cached (and gnus-use-cache gnus-newsgroup-cached))
993              (undownloaded (list nil))
994              (tail-undownloaded undownloaded)
995              (unfetched (list nil))
996              (tail-unfetched unfetched))
997         (while (and alist headers)
998           (let ((a (caar alist))
999                 (h (car headers)))
1000             (cond ((< a h)
1001                    ;; Ignore IDs in the alist that are not being
1002                    ;; displayed in the summary.
1003                    (setq alist (cdr alist)))
1004                   ((> a h)
1005                    ;; Headers that are not in the alist should be
1006                    ;; fictious (see nnagent-retrieve-headers); they
1007                    ;; imply that this article isn't in the agent.
1008                    (gnus-agent-append-to-list tail-undownloaded h)
1009                    (gnus-agent-append-to-list tail-unfetched    h)
1010                    (setq headers (cdr headers))) 
1011                   ((cdar alist)
1012                    (setq alist (cdr alist))
1013                    (setq headers (cdr headers))
1014                    nil                  ; ignore already downloaded
1015                    )
1016                   (t
1017                    (setq alist (cdr alist))
1018                    (setq headers (cdr headers))
1019                    
1020                    ;; This article isn't in the agent.  Check to see
1021                    ;; if it is in the cache.  If it is, it's been
1022                    ;; downloaded.
1023                    (while (and cached (< (car cached) a))
1024                      (setq cached (cdr cached)))
1025                    (unless (equal a (car cached))
1026                      (gnus-agent-append-to-list tail-undownloaded a))))))
1027
1028         (while headers
1029           (let ((num (pop headers)))
1030             (gnus-agent-append-to-list tail-undownloaded num)
1031             (gnus-agent-append-to-list tail-unfetched    num)))
1032
1033         (setq gnus-newsgroup-undownloaded (cdr undownloaded)
1034               gnus-newsgroup-unfetched    (cdr unfetched))))))
1035
1036 (defun gnus-agent-catchup ()
1037   "Mark as read all unhandled articles.
1038 An article is unhandled if it is neither cached, nor downloaded, nor
1039 downloadable."
1040   (interactive)
1041   (save-excursion
1042     (let ((articles gnus-newsgroup-undownloaded))
1043       (when (or gnus-newsgroup-downloadable
1044                 gnus-newsgroup-cached)
1045         (setq articles (gnus-sorted-ndifference
1046                         (gnus-sorted-ndifference
1047                          (gnus-copy-sequence articles)
1048                          gnus-newsgroup-downloadable)
1049                         gnus-newsgroup-cached)))
1050
1051       (while articles
1052         (gnus-summary-mark-article
1053          (pop articles) gnus-catchup-mark)))
1054     (gnus-summary-position-point)))
1055
1056 (defun gnus-agent-summary-fetch-series ()
1057   (interactive)
1058   (when gnus-newsgroup-processable
1059     (setq gnus-newsgroup-downloadable
1060           (let* ((dl gnus-newsgroup-downloadable)
1061                  (gnus-newsgroup-downloadable
1062                   (sort (gnus-copy-sequence gnus-newsgroup-processable) '<))
1063                  (fetched-articles (gnus-agent-summary-fetch-group)))
1064             ;; The preceeding call to (gnus-agent-summary-fetch-group)
1065             ;; updated gnus-newsgroup-downloadable to remove each
1066             ;; article successfully fetched.
1067
1068             ;; For each article that I processed, remove its
1069             ;; processable mark IF the article is no longer
1070             ;; downloadable (i.e. it's already downloaded)
1071             (dolist (article gnus-newsgroup-processable)
1072               (unless (memq article gnus-newsgroup-downloadable)
1073                 (gnus-summary-remove-process-mark article)))
1074             (gnus-sorted-ndifference dl fetched-articles)))))
1075
1076 (defun gnus-agent-summary-fetch-group (&optional all)
1077   "Fetch the downloadable articles in the group.
1078 Optional arg ALL, if non-nil, means to fetch all articles."
1079   (interactive "P")
1080   (let ((articles
1081          (if all gnus-newsgroup-articles
1082            gnus-newsgroup-downloadable))
1083         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
1084         fetched-articles)
1085     (gnus-agent-while-plugged
1086       (unless articles
1087         (error "No articles to download"))
1088       (gnus-agent-with-fetch
1089         (setq gnus-newsgroup-undownloaded
1090               (gnus-sorted-ndifference
1091                gnus-newsgroup-undownloaded
1092                (setq fetched-articles
1093                      (gnus-agent-fetch-articles
1094                       gnus-newsgroup-name articles)))))
1095       (save-excursion
1096         (dolist (article articles)
1097           (let ((was-marked-downloadable 
1098                  (memq article gnus-newsgroup-downloadable)))
1099             (cond (gnus-agent-mark-unread-after-downloaded
1100                    (setq gnus-newsgroup-downloadable
1101                          (delq article gnus-newsgroup-downloadable))
1102
1103                    (gnus-summary-mark-article article gnus-unread-mark))
1104                   (was-marked-downloadable
1105                    (gnus-summary-set-agent-mark article t)))
1106             (when (gnus-summary-goto-subject article nil t)
1107               (gnus-summary-update-download-mark article))))))
1108     fetched-articles))
1109
1110 (defun gnus-agent-fetch-selected-article ()
1111   "Fetch the current article as it is selected.
1112 This can be added to `gnus-select-article-hook' or
1113 `gnus-mark-article-hook'."
1114   (let ((gnus-command-method gnus-current-select-method))
1115     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
1116       (when (gnus-agent-fetch-articles
1117              gnus-newsgroup-name
1118              (list gnus-current-article))
1119         (setq gnus-newsgroup-undownloaded
1120               (delq gnus-current-article gnus-newsgroup-undownloaded))
1121         (gnus-summary-update-download-mark gnus-current-article)))))
1122
1123 ;;;
1124 ;;; Internal functions
1125 ;;;
1126
1127 (defun gnus-agent-save-active (method)
1128   (when (gnus-agent-method-p method)
1129     (let* ((gnus-command-method method)
1130            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
1131            (file (gnus-agent-lib-file "active")))
1132       (gnus-active-to-gnus-format nil new)
1133       (gnus-agent-write-active file new)
1134       (erase-buffer)
1135       (nnheader-insert-file-contents file))))
1136
1137 (defun gnus-agent-write-active (file new)
1138     (gnus-make-directory (file-name-directory file))
1139     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
1140       ;; The hashtable contains real names of groups.  However, do NOT
1141       ;; add the foreign server prefix as gnus-active-to-gnus-format
1142       ;; will add it while reading the file.
1143       (gnus-write-active-file file new nil)))
1144
1145 (defun gnus-agent-possibly-alter-active (group active &optional info)
1146   "Possibly expand a group's active range to include articles
1147 downloaded into the agent."
1148   (let* ((gnus-command-method (or gnus-command-method
1149                                   (gnus-find-method-for-group group))))
1150     (when (gnus-agent-method-p gnus-command-method)
1151       (let* ((local (gnus-agent-get-local group))
1152              (active-min (car active))
1153              (active-max (cdr active))
1154              (agent-min (or (car local) active-min))
1155              (agent-max (or (cdr local) active-max)))
1156
1157         (when (< agent-min active-min)
1158           (setcar active agent-min))
1159
1160         (when (> agent-max active-max)
1161           (setcdr active agent-max))
1162
1163         (when (and info (< agent-max (- active-min 100)))
1164           ;; I'm expanding the active range by such a large amount
1165           ;; that there is a gap of more than 100 articles between the
1166           ;; last article known to the agent and the first article
1167           ;; currently available on the server.  This gap contains
1168           ;; articles that have been lost, mark them as read so that
1169           ;; gnus doesn't waste resources trying to fetch them.
1170
1171           ;; NOTE: I don't do this for smaller gaps (< 100) as I don't
1172           ;; want to modify the local file everytime someone restarts
1173           ;; gnus.  The small gap will cause a tiny performance hit
1174           ;; when gnus tries, and fails, to retrieve the articles.
1175           ;; Still that should be smaller than opening a buffer,
1176           ;; printing this list to the buffer, and then writing it to a
1177           ;; file.
1178
1179           (let ((read (gnus-info-read info)))
1180             (gnus-info-set-read 
1181              info 
1182              (gnus-range-add 
1183               read 
1184               (list (cons (1+ agent-max) 
1185                           (1- active-min))))))
1186
1187           ;; Lie about the agent's local range for this group to
1188           ;; disable the set read each time this server is opened.
1189           ;; NOTE: Opening this group will restore the valid local
1190           ;; range but it will also expand the local range to
1191           ;; incompass the new active range.
1192           (gnus-agent-set-local group agent-min (1- active-min)))))))
1193
1194 (defun gnus-agent-save-group-info (method group active)
1195   "Update a single group's active range in the agent's copy of the server's active file."
1196   (when (gnus-agent-method-p method)
1197     (let* ((gnus-command-method method)
1198            (coding-system-for-write nnheader-file-coding-system)
1199            (file-name-coding-system nnmail-pathname-coding-system)
1200            (file (gnus-agent-lib-file "active"))
1201            oactive-min oactive-max)
1202       (gnus-make-directory (file-name-directory file))
1203       (with-temp-file file
1204         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
1205         (set-buffer-multibyte nil)
1206         (when (file-exists-p file)
1207           (nnheader-insert-file-contents file)
1208
1209           (goto-char (point-min))
1210           (when (re-search-forward
1211                  (concat "^" (regexp-quote group) " ") nil t)
1212             (save-excursion
1213               (setq oactive-max (read (current-buffer)) ;; max
1214                     oactive-min (read (current-buffer)))) ;; min
1215             (gnus-delete-line)))
1216         (insert (format "%S %d %d y\n" (intern group)
1217                         (max (or oactive-max (cdr active)) (cdr active))
1218                         (min (or oactive-min (car active)) (car active))))
1219         (goto-char (point-max))
1220         (while (search-backward "\\." nil t)
1221           (delete-char 1))))))
1222
1223 (defun gnus-agent-group-path (group)
1224   "Translate GROUP into a file name."
1225
1226   ;; NOTE: This is what nnmail-group-pathname does as of Apr 2003.
1227   ;; The two methods must be kept synchronized, which is why
1228   ;; gnus-agent-group-pathname was added.
1229
1230   (setq group
1231         (nnheader-translate-file-chars
1232          (nnheader-replace-duplicate-chars-in-string
1233           (nnheader-replace-chars-in-string 
1234            (gnus-group-real-name group)
1235            ?/ ?_)
1236           ?. ?_)))
1237   (if (or nnmail-use-long-file-names
1238           (file-directory-p (expand-file-name group (gnus-agent-directory))))
1239       group
1240     (mm-encode-coding-string
1241      (nnheader-replace-chars-in-string group ?. ?/)
1242      nnmail-pathname-coding-system)))
1243
1244 (defun gnus-agent-group-pathname (group)
1245   "Translate GROUP into a file name."
1246   ;; nnagent uses nnmail-group-pathname to read articles while
1247   ;; unplugged.  The agent must, therefore, use the same directory
1248   ;; while plugged.
1249   (let ((gnus-command-method (or gnus-command-method
1250                                  (gnus-find-method-for-group group))))
1251     (nnmail-group-pathname (gnus-group-real-name group) (gnus-agent-directory))))
1252
1253 (defun gnus-agent-get-function (method)
1254   (if (gnus-online method)
1255       (car method)
1256     (require 'nnagent)
1257     'nnagent))
1258
1259 (defun gnus-agent-covered-methods ()
1260   "Return the subset of methods that are covered by the agent."
1261   (delq nil (mapcar #'gnus-server-to-method gnus-agent-covered-methods)))
1262
1263 ;;; History functions
1264
1265 (defun gnus-agent-history-buffer ()
1266   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1267
1268 (defun gnus-agent-open-history ()
1269   (save-excursion
1270     (push (cons (gnus-agent-method)
1271                 (set-buffer (gnus-get-buffer-create
1272                              (format " *Gnus agent %s history*"
1273                                      (gnus-agent-method)))))
1274           gnus-agent-history-buffers)
1275     (set-buffer-multibyte nil) ;; everything is binary
1276     (erase-buffer)
1277     (insert "\n")
1278     (let ((file (gnus-agent-lib-file "history")))
1279       (when (file-exists-p file)
1280         (nnheader-insert-file-contents file))
1281       (set (make-local-variable 'gnus-agent-file-name) file))))
1282
1283 (defun gnus-agent-close-history ()
1284   (when (gnus-buffer-live-p gnus-agent-current-history)
1285     (kill-buffer gnus-agent-current-history)
1286     (setq gnus-agent-history-buffers
1287           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1288                 gnus-agent-history-buffers))))
1289
1290 ;;;
1291 ;;; Fetching
1292 ;;;
1293
1294 (defun gnus-agent-fetch-articles (group articles)
1295   "Fetch ARTICLES from GROUP and put them into the Agent."
1296   (when articles
1297     (gnus-agent-load-alist group)
1298     (let* ((alist   gnus-agent-article-alist)
1299            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1300            (selected-sets (list nil))
1301            (current-set-size 0)
1302            article
1303            header-number)
1304       ;; Check each article
1305       (while (setq article (pop articles))
1306         ;; Skip alist entries preceeding this article
1307         (while (> article (or (caar alist) (1+ article)))
1308           (setq alist (cdr alist)))
1309
1310         ;; Prune off articles that we have already fetched.
1311         (unless (and (eq article (caar alist))
1312                      (cdar alist))
1313           ;; Skip headers preceeding this article
1314           (while (> article 
1315                     (setq header-number
1316                           (let* ((header (car headers)))
1317                             (if header
1318                                 (mail-header-number header)
1319                               (1+ article)))))
1320             (setq headers (cdr headers)))
1321
1322           ;; Add this article to the current set
1323           (setcar selected-sets (cons article (car selected-sets)))
1324
1325           ;; Update the set size, when the set is too large start a
1326           ;; new one.  I do this after adding the article as I want at
1327           ;; least one article in each set.
1328           (when (< gnus-agent-max-fetch-size
1329                    (setq current-set-size
1330                          (+ current-set-size
1331                             (if (= header-number article)
1332                                 (let ((char-size (mail-header-chars
1333                                                   (car headers))))
1334                                   (if (<= char-size 0)
1335                                       ;; The char size was missing/invalid,
1336                                       ;; assume a worst-case situation of
1337                                       ;; 65 char/line.  If the line count
1338                                       ;; is missing, arbitrarily assume a
1339                                       ;; size of 1000 characters.
1340                                     (max (* 65 (mail-header-lines
1341                                                 (car headers)))
1342                                          1000)
1343                                     char-size))
1344                               0))))
1345             (setcar selected-sets (nreverse (car selected-sets)))
1346             (setq selected-sets (cons nil selected-sets)
1347                   current-set-size 0))))
1348
1349       (when (or (cdr selected-sets) (car selected-sets))
1350         (let* ((fetched-articles (list nil))
1351                (tail-fetched-articles fetched-articles)
1352                (dir (gnus-agent-group-pathname group))
1353                (date (time-to-days (current-time)))
1354                (case-fold-search t)
1355                pos crosses id)
1356
1357           (setcar selected-sets (nreverse (car selected-sets)))
1358           (setq selected-sets (nreverse selected-sets))
1359
1360           (gnus-make-directory dir)
1361           (gnus-message 7 "Fetching articles for %s..." group)
1362
1363           (unwind-protect
1364               (while (setq articles (pop selected-sets))
1365                 ;; Fetch the articles from the backend.
1366                 (if (gnus-check-backend-function 'retrieve-articles group)
1367                     (setq pos (gnus-retrieve-articles articles group))
1368                   (with-temp-buffer
1369                     (let (article)
1370                       (while (setq article (pop articles))
1371                         (gnus-message 10 "Fetching article %s for %s..."
1372                                       article group)
1373                         (when (or
1374                                (gnus-backlog-request-article group article
1375                                                              nntp-server-buffer)
1376                                (gnus-request-article article group))
1377                           (goto-char (point-max))
1378                           (push (cons article (point)) pos)
1379                           (insert-buffer-substring nntp-server-buffer)))
1380                       (copy-to-buffer
1381                        nntp-server-buffer (point-min) (point-max))
1382                       (setq pos (nreverse pos)))))
1383                 ;; Then save these articles into the Agent.
1384                 (save-excursion
1385                   (set-buffer nntp-server-buffer)
1386                   (while pos
1387                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1388                     (goto-char (point-min))
1389                     (unless (eobp) ;; Don't save empty articles.
1390                       (when (search-forward "\n\n" nil t)
1391                         (when (search-backward "\nXrefs: " nil t)
1392                           ;; Handle cross posting.
1393                           (goto-char (match-end 0)) ; move to end of header name
1394                           (skip-chars-forward "^ ") ; skip server name
1395                           (skip-chars-forward " ")
1396                           (setq crosses nil)
1397                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1398                             (push (cons (buffer-substring (match-beginning 1)
1399                                                           (match-end 1))
1400                                         (string-to-int
1401                                          (buffer-substring (match-beginning 2)
1402                                                            (match-end 2))))
1403                                   crosses)
1404                             (goto-char (match-end 0)))
1405                           (gnus-agent-crosspost crosses (caar pos) date)))
1406                       (goto-char (point-min))
1407                       (if (not (re-search-forward
1408                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1409                           (setq id "No-Message-ID-in-article")
1410                         (setq id (buffer-substring
1411                                   (match-beginning 1) (match-end 1))))
1412                       (write-region-as-coding-system
1413                        gnus-agent-file-coding-system (point-min) (point-max)
1414                        (concat dir (number-to-string (caar pos))) nil 'silent)
1415
1416                       (gnus-agent-append-to-list
1417                        tail-fetched-articles (caar pos)))
1418                     (widen)
1419                     (setq pos (cdr pos)))))
1420
1421             (gnus-agent-save-alist group (cdr fetched-articles) date)
1422             (gnus-message 7 ""))
1423           (cdr fetched-articles))))))
1424
1425 (defun gnus-agent-crosspost (crosses article &optional date)
1426   (setq date (or date t))
1427
1428   (let (gnus-agent-article-alist group alist beg end)
1429     (save-excursion
1430       (set-buffer gnus-agent-overview-buffer)
1431       (when (nnheader-find-nov-line article)
1432         (forward-word 1)
1433         (setq beg (point))
1434         (setq end (progn (forward-line 1) (point)))))
1435     (while crosses
1436       (setq group (caar crosses))
1437       (unless (setq alist (assoc group gnus-agent-group-alist))
1438         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1439               gnus-agent-group-alist))
1440       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1441       (save-excursion
1442         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1443                                                     group)))
1444         (when (= (point-max) (point-min))
1445           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1446           (ignore-errors
1447             (nnheader-insert-file-contents
1448              (gnus-agent-article-name ".overview" group))))
1449         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1450         (insert (string-to-number (cdar crosses)))
1451         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1452         (gnus-agent-check-overview-buffer))
1453       (setq crosses (cdr crosses)))))
1454
1455 (defun gnus-agent-backup-overview-buffer ()
1456   (when gnus-newsgroup-name
1457     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1458           (cnt 0)
1459           name)
1460       (while (file-exists-p
1461               (setq name (concat root "~"
1462                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1463       (write-region (point-min) (point-max) name nil 'no-msg)
1464       (gnus-message 1 "Created backup copy of overview in %s." name)))
1465   t)
1466
1467 (defun gnus-agent-check-overview-buffer (&optional buffer)
1468   "Check the overview file given for sanity.
1469 In particular, checks that the file is sorted by article number
1470 and that there are no duplicates."
1471   (let ((prev-num -1)
1472         (backed-up nil))
1473     (save-excursion
1474       (when buffer
1475         (set-buffer buffer))
1476       (save-restriction
1477         (widen)
1478         (goto-char (point-min))
1479
1480         (while (< (point) (point-max))
1481           (let ((p (point))
1482                 (cur (condition-case nil
1483                          (read (current-buffer))
1484                        (error nil))))
1485             (cond
1486              ((or (not (integerp cur))
1487                   (not (eq (char-after) ?\t)))
1488               (or backed-up
1489                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1490               (gnus-message 1
1491                             "Overview buffer contains garbage '%s'."
1492                             (buffer-substring
1493                              p (point-at-eol))))
1494              ((= cur prev-num)
1495               (or backed-up
1496                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1497               (gnus-message 1
1498                             "Duplicate overview line for %d" cur)
1499               (delete-region (point) (progn (forward-line 1) (point))))
1500              ((< cur prev-num)
1501               (or backed-up
1502                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1503               (gnus-message 1 "Overview buffer not sorted!")
1504               (sort-numeric-fields 1 (point-min) (point-max))
1505               (goto-char (point-min))
1506               (setq prev-num -1))
1507              (t
1508               (setq prev-num cur)))
1509             (forward-line 1)))))))
1510
1511 (defun gnus-agent-flush-cache ()
1512   (save-excursion
1513     (while gnus-agent-buffer-alist
1514       (set-buffer (cdar gnus-agent-buffer-alist))
1515       (write-region-as-coding-system
1516        gnus-agent-file-coding-system
1517        (point-min) (point-max)
1518        (gnus-agent-article-name ".overview"
1519                                 (caar gnus-agent-buffer-alist))
1520        nil 'silent)
1521       (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1522     (while gnus-agent-group-alist
1523       (with-temp-file (gnus-agent-article-name
1524                        ".agentview" (caar gnus-agent-group-alist))
1525         (princ (cdar gnus-agent-group-alist))
1526         (insert "\n")
1527         (princ 1 (current-buffer))
1528         (insert "\n"))
1529       (setq gnus-agent-group-alist (cdr gnus-agent-group-alist)))))
1530
1531 (defun gnus-agent-find-parameter (group symbol)
1532   "Search for GROUPs SYMBOL in the group's parameters, the group's
1533 topic parameters, the group's category, or the customizable
1534 variables.  Returns the first non-nil value found."
1535   (or (gnus-group-find-parameter group symbol t)
1536       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1537       (symbol-value
1538        (cdr
1539         (assq symbol
1540               '((agent-short-article . gnus-agent-short-article)
1541                 (agent-long-article . gnus-agent-long-article)
1542                 (agent-low-score . gnus-agent-low-score)
1543                 (agent-high-score . gnus-agent-high-score)
1544                 (agent-days-until-old . gnus-agent-expire-days)
1545                 (agent-enable-expiration
1546                  . gnus-agent-enable-expiration)
1547                 (agent-predicate . gnus-agent-predicate)))))))
1548
1549 (defun gnus-agent-fetch-headers (group &optional force)
1550   "Fetch interesting headers into the agent.  The group's overview
1551 file will be updated to include the headers while a list of available
1552 article numbers will be returned."
1553   (let* ((fetch-all (and gnus-agent-consider-all-articles
1554                          ;; Do not fetch all headers if the predicate
1555                          ;; implies that we only consider unread articles.
1556                          (not (gnus-predicate-implies-unread
1557                                (gnus-agent-find-parameter group
1558                                                           'agent-predicate)))))
1559          (articles (if fetch-all
1560                        (gnus-uncompress-range (gnus-active group))
1561                      (gnus-list-of-unread-articles group)))
1562          (gnus-decode-encoded-word-function 'identity)
1563          (file (gnus-agent-article-name ".overview" group)))
1564     ;; Check whether the number of articles is not too large.
1565     (when (and (integerp gnus-agent-large-newsgroup)
1566                (> gnus-agent-large-newsgroup 0))
1567       (setq articles (nthcdr (max (- (length articles)
1568                                      gnus-agent-large-newsgroup)
1569                                   0)
1570                              articles)))
1571     (unless fetch-all
1572       ;; Add articles with marks to the list of article headers we want to
1573       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1574       ;; mark, but do fetch recent or seen articles if they have other, more
1575       ;; interesting marks.  (We have to fetch articles with boring marks
1576       ;; because otherwise the agent will remove their marks.)
1577       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1578         (unless (memq (car arts) '(seen recent killed cache))
1579           (setq articles (gnus-range-add articles (cdr arts)))))
1580       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1581
1582     ;; At this point, I have the list of articles to consider for
1583     ;; fetching.  This is the list that I'll return to my caller. Some
1584     ;; of these articles may have already been fetched.  That's OK as
1585     ;; the fetch article code will filter those out.  Internally, I'll
1586     ;; filter this list to just those articles whose headers need to
1587     ;; be fetched.
1588     (let ((articles articles))
1589       ;; Remove known articles.
1590       (when (and (or gnus-agent-cache
1591                      (not gnus-plugged))
1592                  (gnus-agent-load-alist group))
1593         ;; Remove articles marked as downloaded.
1594         (if fetch-all
1595             ;; I want to fetch all headers in the active range.
1596             ;; Therefore, exclude only those headers that are in the
1597             ;; article alist.
1598             ;; NOTE: This is probably NOT what I want to do after
1599             ;; agent expiration in this group.
1600             (setq articles (gnus-agent-uncached-articles articles group))
1601
1602           ;; I want to only fetch those headers that have never been
1603           ;; fetched.  Therefore, exclude all headers that are, or
1604           ;; WERE, in the article alist.
1605           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1606                 (high (cdr (gnus-active group))))
1607             ;; Low can be greater than High when the same group is
1608             ;; fetched twice in the same session {The first fetch will
1609             ;; fill the article alist such that (last
1610             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1611             ;; group))}.  The addition of one(the 1+ above) then
1612             ;; forces Low to be greater than High.  When this happens,
1613             ;; gnus-list-range-intersection returns nil which
1614             ;; indicates that no headers need to be fetched. -- Kevin
1615             (setq articles (gnus-list-range-intersection
1616                             articles (list (cons low high)))))))
1617
1618       (gnus-message
1619        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1620        (gnus-compress-sequence articles t))
1621
1622       (save-excursion
1623         (set-buffer nntp-server-buffer)
1624
1625         (if articles
1626             (progn
1627               (gnus-message 7 "Fetching headers for %s..." group)
1628
1629               ;; Fetch them.
1630               (gnus-make-directory (nnheader-translate-file-chars
1631                                     (file-name-directory file) t))
1632
1633               (unless (eq 'nov (gnus-retrieve-headers articles group))
1634                 (nnvirtual-convert-headers))
1635               (gnus-agent-check-overview-buffer)
1636               ;; Move these headers to the overview buffer so that
1637               ;; gnus-agent-braid-nov can merge them with the contents
1638               ;; of FILE.
1639               (copy-to-buffer
1640                gnus-agent-overview-buffer (point-min) (point-max))
1641               (when (file-exists-p file)
1642                 (gnus-agent-braid-nov group articles file))
1643               (gnus-agent-check-overview-buffer)
1644               (write-region-as-coding-system
1645                gnus-agent-file-coding-system
1646                (point-min) (point-max) file nil 'silent)
1647               (gnus-agent-save-alist group articles nil)
1648               articles)
1649           (ignore-errors
1650             (erase-buffer)
1651             (nnheader-insert-file-contents file)))))
1652     articles))
1653
1654 (defsubst gnus-agent-copy-nov-line (article)
1655   (let (art b e)
1656     (set-buffer gnus-agent-overview-buffer)
1657     (while (and (not (eobp))
1658                 (< (setq art (read (current-buffer))) article))
1659       (forward-line 1))
1660     (beginning-of-line)
1661     (if (or (eobp)
1662             (not (eq article art)))
1663         (set-buffer nntp-server-buffer)
1664       (setq b (point))
1665       (setq e (progn (forward-line 1) (point)))
1666       (set-buffer nntp-server-buffer)
1667       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1668
1669 (defun gnus-agent-braid-nov (group articles file)
1670   "Merge agent overview data with given file.
1671 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1672 FILE and places the combined headers into `nntp-server-buffer'."
1673   (let (start last)
1674     (set-buffer gnus-agent-overview-buffer)
1675     (goto-char (point-min))
1676     (set-buffer nntp-server-buffer)
1677     (erase-buffer)
1678     (nnheader-insert-file-contents file)
1679     (goto-char (point-max))
1680     (forward-line -1)
1681     (unless (looking-at "[0-9]+\t")
1682       ;; Remove corrupted lines
1683       (gnus-message
1684        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1685       (goto-char (point-min))
1686       (while (not (eobp))
1687         (if (looking-at "[0-9]+\t")
1688             (forward-line 1)
1689           (delete-region (point) (progn (forward-line 1) (point)))))
1690       (forward-line -1))
1691     (unless (or (= (point-min) (point-max))
1692                 (< (setq last (read (current-buffer))) (car articles)))
1693       ;; We do it the hard way.
1694       (when (nnheader-find-nov-line (car articles))
1695         ;; Replacing existing NOV entry
1696         (delete-region (point) (progn (forward-line 1) (point))))
1697       (gnus-agent-copy-nov-line (pop articles))
1698
1699       (ignore-errors
1700         (while articles
1701           (while (let ((art (read (current-buffer))))
1702                    (cond ((< art (car articles))
1703                           (forward-line 1)
1704                           t)
1705                          ((= art (car articles))
1706                           (beginning-of-line)
1707                           (delete-region
1708                            (point) (progn (forward-line 1) (point)))
1709                           nil)
1710                          (t
1711                           (beginning-of-line)
1712                           nil))))
1713
1714           (gnus-agent-copy-nov-line (pop articles)))))
1715
1716     ;; Copy the rest lines
1717     (set-buffer nntp-server-buffer)
1718     (goto-char (point-max))
1719     (when articles
1720       (when last
1721         (set-buffer gnus-agent-overview-buffer)
1722         (ignore-errors
1723           (while (<= (read (current-buffer)) last)
1724             (forward-line 1)))
1725         (beginning-of-line)
1726         (setq start (point))
1727         (set-buffer nntp-server-buffer))
1728       (insert-buffer-substring gnus-agent-overview-buffer start))))
1729
1730 ;; Keeps the compiler from warning about the free variable in
1731 ;; gnus-agent-read-agentview.
1732 (eval-when-compile
1733   (defvar gnus-agent-read-agentview))
1734
1735 (defun gnus-agent-load-alist (group)
1736   "Load the article-state alist for GROUP."
1737   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1738   (let ((gnus-agent-read-agentview group))
1739     (setq gnus-agent-article-alist
1740           (gnus-cache-file-contents
1741            (gnus-agent-article-name ".agentview" group)
1742            'gnus-agent-file-loading-cache
1743            'gnus-agent-read-agentview))))
1744
1745 ;; Save format may be either 1 or 2.  Two is the new, compressed
1746 ;; format that is still being tested.  Format 1 is uncompressed but
1747 ;; known to be reliable.
1748 (defconst gnus-agent-article-alist-save-format 2)
1749
1750 (defun gnus-agent-read-agentview (file)
1751   "Load FILE and do a `read' there."
1752   (with-temp-buffer
1753     (ignore-errors
1754       (nnheader-insert-file-contents file)
1755       (goto-char (point-min))
1756       (let ((alist (read (current-buffer)))
1757             (version (condition-case nil (read (current-buffer))
1758                        (end-of-file 0)))
1759             changed-version)
1760
1761         (cond
1762          ((= version 0)
1763           (let ((inhibit-quit t)
1764                 entry)
1765             (gnus-agent-open-history)
1766             (set-buffer (gnus-agent-history-buffer))
1767             (goto-char (point-min))
1768             (while (not (eobp))
1769               (if (and (looking-at
1770                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1771                        (string= (match-string 2)
1772                                 gnus-agent-read-agentview)
1773                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1774                   (setcdr entry (string-to-number (match-string 1))))
1775               (forward-line 1))
1776             (gnus-agent-close-history)
1777             (setq changed-version t)))
1778          ((= version 1)
1779           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1780          ((= version 2)
1781           (let (uncomp)
1782             (mapcar
1783              (lambda (comp-list)
1784                (let ((state (car comp-list))
1785                      (sequence (gnus-uncompress-sequence
1786                                 (cdr comp-list))))
1787                  (mapcar (lambda (article-id)
1788                            (setq uncomp (cons (cons article-id state) uncomp)))
1789                          sequence)))
1790              alist)
1791             (setq alist (sort uncomp 'car-less-than-car)))))
1792         (when changed-version
1793           (let ((gnus-agent-article-alist alist))
1794             (gnus-agent-save-alist gnus-agent-read-agentview)))
1795         alist))))
1796
1797 (defun gnus-agent-save-alist (group &optional articles state)
1798   "Save the article-state alist for GROUP."
1799   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1800          (prev (cons nil gnus-agent-article-alist))
1801          (all prev)
1802          print-level print-length item article)
1803     (while (setq article (pop articles))
1804       (while (and (cdr prev)
1805                   (< (caadr prev) article))
1806         (setq prev (cdr prev)))
1807       (cond
1808        ((not (cdr prev))
1809         (setcdr prev (list (cons article state))))
1810        ((> (caadr prev) article)
1811         (setcdr prev (cons (cons article state) (cdr prev))))
1812        ((= (caadr prev) article)
1813         (setcdr (cadr prev) state)))
1814       (setq prev (cdr prev)))
1815     (setq gnus-agent-article-alist (cdr all))
1816
1817     (gnus-agent-set-local group 
1818                           (caar gnus-agent-article-alist) 
1819                           (caar (last gnus-agent-article-alist)))
1820
1821     (gnus-make-directory (gnus-agent-article-name "" group))
1822     (with-temp-file (gnus-agent-article-name ".agentview" group)
1823       (cond ((eq gnus-agent-article-alist-save-format 1)
1824              (princ gnus-agent-article-alist (current-buffer)))
1825             ((eq gnus-agent-article-alist-save-format 2)
1826              (let ((compressed nil))
1827                (mapcar (lambda (pair)
1828                          (let* ((article-id (car pair))
1829                                 (day-of-download (cdr pair))
1830                                 (comp-list (assq day-of-download compressed)))
1831                            (if comp-list
1832                                (setcdr comp-list
1833                                        (cons article-id (cdr comp-list)))
1834                              (setq compressed
1835                                    (cons (list day-of-download article-id)
1836                                          compressed)))
1837                            nil)) gnus-agent-article-alist)
1838                (mapcar (lambda (comp-list)
1839                          (setcdr comp-list
1840                                  (gnus-compress-sequence
1841                                   (nreverse (cdr comp-list)))))
1842                        compressed)
1843                (princ compressed (current-buffer)))))
1844       (insert "\n")
1845       (princ gnus-agent-article-alist-save-format (current-buffer))
1846       (insert "\n"))))
1847
1848 (defvar gnus-agent-article-local nil)
1849 (defvar gnus-agent-file-loading-local nil)
1850
1851 (defun gnus-agent-load-local (&optional method)
1852   "Load the METHOD'S local file.  The local file contains min/max
1853 article counts for each of the method's subscribed groups."
1854   (let ((gnus-command-method (or method gnus-command-method)))
1855     (setq gnus-agent-article-local
1856           (gnus-cache-file-contents
1857            (gnus-agent-lib-file "local")
1858            'gnus-agent-file-loading-local
1859            'gnus-agent-read-and-cache-local))))
1860
1861 (defun gnus-agent-read-and-cache-local (file)
1862   "Load and read FILE then bind its contents to
1863 gnus-agent-article-local.  If that variable had `dirty' (also known as
1864 modified) original contents, they are first saved to their own file."
1865
1866   (if (and gnus-agent-article-local
1867            (symbol-value (intern "+dirty" gnus-agent-article-local)))
1868       (gnus-agent-save-local))
1869   (gnus-agent-read-local file))
1870
1871 (defun gnus-agent-read-local (file)
1872   "Load FILE and do a `read' there."
1873   (let ((obarray (gnus-make-hashtable (count-lines (point-min) (point-max))))
1874         (line 1))
1875         (with-temp-buffer
1876           (condition-case nil
1877               (nnheader-insert-file-contents file)
1878             (file-error))
1879
1880           (goto-char (point-min))
1881           ;; Skip any comments at the beginning of the file (the only place where they may appear)
1882           (while (= (following-char) ?\;)
1883             (forward-line 1)
1884             (setq line (1+ line)))
1885
1886           (while (not (eobp))
1887             (condition-case err
1888                 (let (group 
1889                       min
1890                       max
1891                       (cur (current-buffer)))
1892                   (setq group (read cur)
1893                         min (read cur)
1894                         max (read cur))
1895
1896                   (when (stringp group)
1897                     (setq group (intern group obarray)))
1898
1899                   ;; NOTE: The '+ 0' ensure that min and max are both numerics.
1900                   (set group (cons (+ 0 min) (+ 0 max))))
1901               (error
1902                (gnus-message 3 "Warning - invalid agent local: %s on line %d: " file line (error-message-string err))))
1903             (forward-line 1)
1904             (setq line (1+ line))))
1905       
1906     (set (intern "+dirty" obarray) nil)
1907     (set (intern "+method" obarray) gnus-command-method)
1908     obarray))
1909
1910 (defun gnus-agent-save-local (&optional force)
1911   "Save gnus-agent-article-local under it method's agent.lib directory."
1912   (let ((obarray gnus-agent-article-local))
1913     (when (and obarray
1914                (or force (symbol-value (intern "+dirty" obarray))))
1915       (let* ((gnus-command-method (symbol-value (intern "+method" obarray)))
1916              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
1917              (dest (gnus-agent-lib-file "local")))
1918         (gnus-make-directory (gnus-agent-lib-file ""))
1919         (with-temp-file dest
1920           (let ((gnus-command-method (symbol-value (intern "+method" obarray)))
1921                 (file-name-coding-system nnmail-pathname-coding-system)
1922                 (coding-system-for-write
1923                  gnus-agent-file-coding-system)
1924                 print-level print-length item article
1925                 (standard-output (current-buffer)))
1926             (mapatoms (lambda (symbol)
1927                         (cond ((not (boundp symbol))
1928                                nil)
1929                               ((member (symbol-name symbol) '("+dirty" "+method"))
1930                                nil)
1931                               (t
1932                                (prin1 symbol)
1933                                (let ((range (symbol-value symbol)))
1934                                  (princ " ")
1935                                  (princ (car range))
1936                                  (princ " ")
1937                                  (princ (cdr range))
1938                                  (princ "\n"))))))))))))
1939
1940 (defun gnus-agent-get-local (group)
1941   (let* ((gmane (gnus-group-real-name group))
1942          (gnus-command-method (gnus-find-method-for-group group))
1943          (local (gnus-agent-load-local))
1944          (symb (intern gmane local))
1945          (minmax (and (boundp symb) (symbol-value symb))))
1946     (unless minmax
1947       ;; Bind these so that gnus-agent-load-alist doesn't change the
1948       ;; current alist (i.e. gnus-agent-article-alist)
1949       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
1950              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
1951              (alist (gnus-agent-load-alist group)))
1952         (when alist
1953           (setq minmax
1954                 (cons (caar alist)
1955                       (caar (last alist))))
1956           (gnus-agent-set-local group (car minmax) (cdr minmax) 
1957                                 gmane gnus-command-method local))))
1958     minmax))
1959
1960 (defun gnus-agent-set-local (group min max &optional gmane method local)
1961   (let* ((gmane (or gmane (gnus-group-real-name group)))
1962          (gnus-command-method (or method (gnus-find-method-for-group group)))
1963          (local (or local (gnus-agent-load-local)))
1964          (symb (intern gmane local))
1965          (minmax (and (boundp symb) (symbol-value symb))))
1966     
1967     (if (cond ((and minmax
1968                     (or (not (eq min (car minmax)))
1969                         (not (eq max (cdr minmax)))))
1970                (setcar minmax min)
1971                (setcdr minmax max)
1972                t)
1973               (minmax
1974                nil)
1975               (t
1976                (set symb (cons min max))
1977                t))
1978         (set (intern "+dirty" local) t))))
1979
1980 (defun gnus-agent-article-name (article group)
1981   (expand-file-name article
1982                     (file-name-as-directory
1983                      (gnus-agent-group-pathname group))))
1984
1985 (defun gnus-agent-batch-confirmation (msg)
1986   "Show error message and return t."
1987   (gnus-message 1 msg)
1988   t)
1989
1990 ;;;###autoload
1991 (defun gnus-agent-batch-fetch ()
1992   "Start Gnus and fetch session."
1993   (interactive)
1994   (gnus)
1995   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1996     (gnus-agent-fetch-session))
1997   (gnus-group-exit))
1998
1999 (defun gnus-agent-fetch-session ()
2000   "Fetch all articles and headers that are eligible for fetching."
2001   (interactive)
2002   (unless gnus-agent-covered-methods
2003     (error "No servers are covered by the Gnus agent"))
2004   (unless gnus-plugged
2005     (error "Can't fetch articles while Gnus is unplugged"))
2006   (let ((methods (gnus-agent-covered-methods))
2007         groups group gnus-command-method)
2008     (save-excursion
2009       (while methods
2010         (setq gnus-command-method (car methods))
2011         (when (and (or (gnus-server-opened gnus-command-method)
2012                        (gnus-open-server gnus-command-method))
2013                    (gnus-online gnus-command-method))
2014           (setq groups (gnus-groups-from-server (car methods)))
2015           (gnus-agent-with-fetch
2016             (while (setq group (pop groups))
2017               (when (<= (gnus-group-level group)
2018                         gnus-agent-handle-level)
2019                 (if (or debug-on-error debug-on-quit)
2020                     (gnus-agent-fetch-group-1
2021                      group gnus-command-method)
2022                   (condition-case err
2023                       (gnus-agent-fetch-group-1
2024                        group gnus-command-method)
2025                     (error
2026                      (unless (funcall gnus-agent-confirmation-function
2027                                       (format "Error %s.  Continue? "
2028                                               (error-message-string err)))
2029                        (error "Cannot fetch articles into the Gnus agent")))
2030                     (quit
2031                      (unless (funcall gnus-agent-confirmation-function
2032                                       (format
2033                                        "Quit fetching session %s.  Continue? "
2034                                        (error-message-string err)))
2035                        (signal 'quit
2036                                "Cannot fetch articles into the Gnus agent")))))))))
2037         (setq methods (cdr methods)))
2038       (gnus-run-hooks 'gnus-agent-fetched-hook)
2039       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2040
2041 (defun gnus-agent-fetch-group-1 (group method)
2042   "Fetch GROUP."
2043   (let ((gnus-command-method method)
2044         (gnus-newsgroup-name group)
2045         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2046         (gnus-newsgroup-headers gnus-newsgroup-headers)
2047         (gnus-newsgroup-scored gnus-newsgroup-scored)
2048         (gnus-use-cache gnus-use-cache)
2049         (gnus-summary-expunge-below gnus-summary-expunge-below)
2050         (gnus-summary-mark-below gnus-summary-mark-below)
2051         (gnus-orphan-score gnus-orphan-score)
2052         ;; Maybe some other gnus-summary local variables should also
2053         ;; be put here.
2054
2055         gnus-headers
2056         gnus-score
2057         articles arts
2058         category predicate info marks score-param
2059         )
2060     (unless (gnus-check-group group)
2061       (error "Can't open server for %s" group))
2062
2063     ;; Fetch headers.
2064     (when (or gnus-newsgroup-active
2065               (gnus-active group)
2066               (gnus-activate-group group))
2067       (let ((marked-articles gnus-newsgroup-downloadable))
2068         ;; Identify the articles marked for download
2069         (unless gnus-newsgroup-active
2070           ;; The variable gnus-newsgroup-active was selected as I need
2071           ;; a gnus-summary local variable that is NOT bound to any
2072           ;; value (its global value should default to nil).
2073           (dolist (mark gnus-agent-download-marks)
2074             (let ((arts (cdr (assq mark (gnus-info-marks
2075                                          (setq info (gnus-get-info group)))))))
2076               (when arts
2077                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2078                                              marked-articles))
2079                 ))))
2080         (setq marked-articles (sort marked-articles '<))
2081
2082         ;; Fetch any new articles from the server
2083         (setq articles (gnus-agent-fetch-headers group))
2084
2085         ;; Merge new articles with marked
2086         (setq articles (sort (append marked-articles articles) '<))
2087
2088         (when articles
2089           ;; Parse them and see which articles we want to fetch.
2090           (setq gnus-newsgroup-dependencies
2091                 (or gnus-newsgroup-dependencies
2092                     (make-vector (length articles) 0)))
2093           (setq gnus-newsgroup-headers
2094                 (or gnus-newsgroup-headers
2095                     (gnus-get-newsgroup-headers-xover articles nil nil
2096                                                       group)))
2097           ;; `gnus-agent-overview-buffer' may be killed for
2098           ;; timeout reason.  If so, recreate it.
2099           (gnus-agent-create-buffer)
2100
2101           ;; Figure out how to select articles in this group
2102           (setq category (gnus-group-category group))
2103
2104           (setq predicate
2105                 (gnus-get-predicate
2106                  (gnus-agent-find-parameter group 'agent-predicate)))
2107
2108           ;; If the selection predicate requires scoring, score each header
2109           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2110             (let ((score-param
2111                    (gnus-agent-find-parameter group 'agent-score-file)))
2112               ;; Translate score-param into real one
2113               (cond
2114                ((not score-param))
2115                ((eq score-param 'file)
2116                 (setq score-param (gnus-all-score-files group)))
2117                ((stringp (car score-param)))
2118                (t
2119                 (setq score-param (list (list score-param)))))
2120               (when score-param
2121                 (gnus-score-headers score-param))))
2122
2123           (unless (and (eq predicate 'gnus-agent-false)
2124                        (not marked-articles))
2125             (let ((arts (list nil)))
2126               (let ((arts-tail arts)
2127                     (alist (gnus-agent-load-alist group))
2128                     (marked-articles marked-articles)
2129                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2130                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2131                   (let ((num (mail-header-number gnus-headers)))
2132                     ;; Determine if this article is already in the cache
2133                     (while (and alist
2134                                 (> num (caar alist)))
2135                       (setq alist (cdr alist)))
2136
2137                     (unless (and (eq num (caar alist))
2138                                  (cdar alist))
2139
2140                       ;; Determine if this article was marked for download.
2141                       (while (and marked-articles
2142                                   (> num (car marked-articles)))
2143                         (setq marked-articles
2144                               (cdr marked-articles)))
2145
2146                       ;; When this article is marked, or selected by the
2147                       ;; predicate, add it to the download list
2148                       (when (or (eq num (car marked-articles))
2149                                 (let ((gnus-score
2150                                        (or (cdr
2151                                             (assq num gnus-newsgroup-scored))
2152                                            gnus-summary-default-score))
2153                                       (gnus-agent-long-article
2154                                        (gnus-agent-find-parameter
2155                                         group 'agent-long-article))
2156                                       (gnus-agent-short-article
2157                                        (gnus-agent-find-parameter
2158                                         group 'agent-short-article))
2159                                       (gnus-agent-low-score
2160                                        (gnus-agent-find-parameter
2161                                         group 'agent-low-score))
2162                                       (gnus-agent-high-score
2163                                        (gnus-agent-find-parameter
2164                                         group 'agent-high-score))
2165                                       (gnus-agent-expire-days
2166                                        (gnus-agent-find-parameter
2167                                         group 'agent-days-until-old)))
2168                                   (funcall predicate)))
2169                         (gnus-agent-append-to-list arts-tail num))))))
2170
2171               (let (fetched-articles)
2172                 ;; Fetch all selected articles
2173                 (setq gnus-newsgroup-undownloaded
2174                       (gnus-sorted-ndifference
2175                        gnus-newsgroup-undownloaded
2176                        (setq fetched-articles
2177                              (if (cdr arts)
2178                                  (gnus-agent-fetch-articles group (cdr arts))
2179                                nil))))
2180
2181                 (let ((unfetched-articles
2182                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2183                   (if gnus-newsgroup-active
2184                       ;; Update the summary buffer
2185                       (progn
2186                         (dolist (article marked-articles)
2187                           (gnus-summary-set-agent-mark article t))
2188                         (dolist (article fetched-articles)
2189                           (if gnus-agent-mark-unread-after-downloaded
2190                               (gnus-summary-mark-article
2191                                article gnus-unread-mark))
2192                           (when (gnus-summary-goto-subject article nil t)
2193                             (gnus-summary-update-download-mark article)))
2194                         (dolist (article unfetched-articles)
2195                           (gnus-summary-mark-article
2196                            article gnus-canceled-mark)))
2197
2198                     ;; Update the group buffer.
2199
2200                     ;; When some, or all, of the marked articles came
2201                     ;; from the download mark.  Remove that mark.  I
2202                     ;; didn't do this earlier as I only want to remove
2203                     ;; the marks after the fetch is completed.
2204
2205                     (dolist (mark gnus-agent-download-marks)
2206                       (when (eq mark 'download)
2207                         (let ((marked-arts
2208                                (assq mark (gnus-info-marks
2209                                            (setq info (gnus-get-info group))))))
2210                           (when (cdr marked-arts)
2211                             (setq marks
2212                                   (delq marked-arts (gnus-info-marks info)))
2213                             (gnus-info-set-marks info marks)))))
2214                     (let ((read (gnus-info-read
2215                                  (or info (setq info (gnus-get-info group))))))
2216                       (gnus-info-set-read
2217                        info (gnus-add-to-range read unfetched-articles)))
2218
2219                     (gnus-group-update-group group t)
2220                     (sit-for 0)
2221
2222                     (gnus-dribble-enter
2223                      (concat "(gnus-group-set-info '"
2224                              (gnus-prin1-to-string info)
2225                              ")"))))))))))))
2226
2227 ;;;
2228 ;;; Agent Category Mode
2229 ;;;
2230
2231 (defvar gnus-category-mode-hook nil
2232   "Hook run in `gnus-category-mode' buffers.")
2233
2234 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2235   "Format of category lines.
2236
2237 Valid specifiers include:
2238 %c  Topic name (string)
2239 %g  The number of groups in the topic (integer)
2240
2241 General format specifiers can also be used.  See Info node
2242 `(gnus)Formatting Variables'.")
2243
2244 (defvar gnus-category-mode-line-format "Gnus: %%b"
2245   "The format specification for the category mode line.")
2246
2247 (defvar gnus-agent-predicate 'false
2248   "The selection predicate used when no other source is available.")
2249
2250 (defvar gnus-agent-short-article 100
2251   "Articles that have fewer lines than this are short.")
2252
2253 (defvar gnus-agent-long-article 200
2254   "Articles that have more lines than this are long.")
2255
2256 (defvar gnus-agent-low-score 0
2257   "Articles that have a score lower than this have a low score.")
2258
2259 (defvar gnus-agent-high-score 0
2260   "Articles that have a score higher than this have a high score.")
2261
2262
2263 ;;; Internal variables.
2264
2265 (defvar gnus-category-buffer "*Agent Category*")
2266
2267 (defvar gnus-category-line-format-alist
2268   `((?c gnus-tmp-name ?s)
2269     (?g gnus-tmp-groups ?d)))
2270
2271 (defvar gnus-category-mode-line-format-alist
2272   `((?u user-defined ?s)))
2273
2274 (defvar gnus-category-line-format-spec nil)
2275 (defvar gnus-category-mode-line-format-spec nil)
2276
2277 (defvar gnus-category-mode-map nil)
2278 (put 'gnus-category-mode 'mode-class 'special)
2279
2280 (unless gnus-category-mode-map
2281   (setq gnus-category-mode-map (make-sparse-keymap))
2282   (suppress-keymap gnus-category-mode-map)
2283
2284   (gnus-define-keys gnus-category-mode-map
2285     "q" gnus-category-exit
2286     "k" gnus-category-kill
2287     "c" gnus-category-copy
2288     "a" gnus-category-add
2289     "e" gnus-agent-customize-category
2290     "p" gnus-category-edit-predicate
2291     "g" gnus-category-edit-groups
2292     "s" gnus-category-edit-score
2293     "l" gnus-category-list
2294
2295     "\C-c\C-i" gnus-info-find-node
2296     "\C-c\C-b" gnus-bug))
2297
2298 (defvar gnus-category-menu-hook nil
2299   "*Hook run after the creation of the menu.")
2300
2301 (defun gnus-category-make-menu-bar ()
2302   (gnus-turn-off-edit-menu 'category)
2303   (unless (boundp 'gnus-category-menu)
2304     (easy-menu-define
2305      gnus-category-menu gnus-category-mode-map ""
2306      '("Categories"
2307        ["Add" gnus-category-add t]
2308        ["Kill" gnus-category-kill t]
2309        ["Copy" gnus-category-copy t]
2310        ["Edit category" gnus-agent-customize-category t]
2311        ["Edit predicate" gnus-category-edit-predicate t]
2312        ["Edit score" gnus-category-edit-score t]
2313        ["Edit groups" gnus-category-edit-groups t]
2314        ["Exit" gnus-category-exit t]))
2315
2316     (gnus-run-hooks 'gnus-category-menu-hook)))
2317
2318 (defun gnus-category-mode ()
2319   "Major mode for listing and editing agent categories.
2320
2321 All normal editing commands are switched off.
2322 \\<gnus-category-mode-map>
2323 For more in-depth information on this mode, read the manual
2324 \(`\\[gnus-info-find-node]').
2325
2326 The following commands are available:
2327
2328 \\{gnus-category-mode-map}"
2329   (interactive)
2330   (when (gnus-visual-p 'category-menu 'menu)
2331     (gnus-category-make-menu-bar))
2332   (kill-all-local-variables)
2333   (gnus-simplify-mode-line)
2334   (setq major-mode 'gnus-category-mode)
2335   (setq mode-name "Category")
2336   (gnus-set-default-directory)
2337   (setq mode-line-process nil)
2338   (use-local-map gnus-category-mode-map)
2339   (buffer-disable-undo)
2340   (setq truncate-lines t)
2341   (setq buffer-read-only t)
2342   (gnus-run-hooks 'gnus-category-mode-hook))
2343
2344 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2345
2346 (defun gnus-category-insert-line (category)
2347   (let* ((gnus-tmp-name (format "%s" (car category)))
2348          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2349     (beginning-of-line)
2350     (gnus-add-text-properties
2351      (point)
2352      (prog1 (1+ (point))
2353        ;; Insert the text.
2354        (eval gnus-category-line-format-spec))
2355      (list 'gnus-category gnus-tmp-name))))
2356
2357 (defun gnus-enter-category-buffer ()
2358   "Go to the Category buffer."
2359   (interactive)
2360   (gnus-category-setup-buffer)
2361   (gnus-configure-windows 'category)
2362   (gnus-category-prepare))
2363
2364 (defun gnus-category-setup-buffer ()
2365   (unless (get-buffer gnus-category-buffer)
2366     (save-excursion
2367       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2368       (gnus-category-mode))))
2369
2370 (defun gnus-category-prepare ()
2371   (gnus-set-format 'category-mode)
2372   (gnus-set-format 'category t)
2373   (let ((alist gnus-category-alist)
2374         (buffer-read-only nil))
2375     (erase-buffer)
2376     (while alist
2377       (gnus-category-insert-line (pop alist)))
2378     (goto-char (point-min))
2379     (gnus-category-position-point)))
2380
2381 (defun gnus-category-name ()
2382   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2383       (error "No category on the current line")))
2384
2385 (defun gnus-category-read ()
2386   "Read the category alist."
2387   (setq gnus-category-alist
2388         (or
2389          (with-temp-buffer
2390            (ignore-errors
2391             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2392             (goto-char (point-min))
2393             ;; This code isn't temp, it will be needed so long as
2394             ;; anyone may be migrating from an older version.
2395
2396             ;; Once we're certain that people will not revert to an
2397             ;; earlier version, we can take out the old-list code in
2398             ;; gnus-category-write.
2399             (let* ((old-list (read (current-buffer)))
2400                    (new-list (ignore-errors (read (current-buffer)))))
2401               (if new-list
2402                   new-list
2403                 ;; Convert from a positional list to an alist.
2404                 (mapcar
2405                  (lambda (c)
2406                    (setcdr c
2407                            (delq nil
2408                                  (gnus-mapcar
2409                                   (lambda (valu symb)
2410                                     (if valu
2411                                         (cons symb valu)))
2412                                   (cdr c)
2413                                   '(agent-predicate agent-score-file agent-groups))))
2414                    c)
2415                  old-list)))))
2416          (list (gnus-agent-cat-make 'default 'short)))))
2417
2418 (defun gnus-category-write ()
2419   "Write the category alist."
2420   (setq gnus-category-predicate-cache nil
2421         gnus-category-group-cache nil)
2422   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2423   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2424     ;; This prin1 is temporary.  It exists so that people can revert
2425     ;; to an earlier version of gnus-agent.
2426     (prin1 (mapcar (lambda (c)
2427               (list (car c)
2428                     (cdr (assoc 'agent-predicate c))
2429                     (cdr (assoc 'agent-score-file c))
2430                     (cdr (assoc 'agent-groups c))))
2431                    gnus-category-alist)
2432            (current-buffer))
2433     (newline)
2434     (prin1 gnus-category-alist (current-buffer))))
2435
2436 (defun gnus-category-edit-predicate (category)
2437   "Edit the predicate for CATEGORY."
2438   (interactive (list (gnus-category-name)))
2439   (let ((info (assq category gnus-category-alist)))
2440     (gnus-edit-form
2441      (gnus-agent-cat-predicate info)
2442      (format "Editing the select predicate for category %s" category)
2443      `(lambda (predicate)
2444         ;; Avoid run-time execution of setf form
2445         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2446         ;;       predicate)
2447         ;; use its expansion instead:
2448         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2449                                      'agent-predicate predicate)
2450
2451         (gnus-category-write)
2452         (gnus-category-list)))))
2453
2454 (defun gnus-category-edit-score (category)
2455   "Edit the score expression for CATEGORY."
2456   (interactive (list (gnus-category-name)))
2457   (let ((info (assq category gnus-category-alist)))
2458     (gnus-edit-form
2459      (gnus-agent-cat-score-file info)
2460      (format "Editing the score expression for category %s" category)
2461      `(lambda (score-file)
2462         ;; Avoid run-time execution of setf form
2463         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2464         ;;       score-file)
2465         ;; use its expansion instead:
2466         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2467                                      'agent-score-file score-file)
2468
2469         (gnus-category-write)
2470         (gnus-category-list)))))
2471
2472 (defun gnus-category-edit-groups (category)
2473   "Edit the group list for CATEGORY."
2474   (interactive (list (gnus-category-name)))
2475   (let ((info (assq category gnus-category-alist)))
2476     (gnus-edit-form
2477      (gnus-agent-cat-groups info)
2478      (format "Editing the group list for category %s" category)
2479      `(lambda (groups)
2480         ;; Avoid run-time execution of setf form
2481         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2482         ;;       groups)
2483         ;; use its expansion instead:
2484         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2485                                    groups)
2486
2487         (gnus-category-write)
2488         (gnus-category-list)))))
2489
2490 (defun gnus-category-kill (category)
2491   "Kill the current category."
2492   (interactive (list (gnus-category-name)))
2493   (let ((info (assq category gnus-category-alist))
2494         (buffer-read-only nil))
2495     (gnus-delete-line)
2496     (setq gnus-category-alist (delq info gnus-category-alist))
2497     (gnus-category-write)))
2498
2499 (defun gnus-category-copy (category to)
2500   "Copy the current category."
2501   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2502   (let ((info (assq category gnus-category-alist)))
2503     (push (let ((newcat (gnus-copy-sequence info)))
2504             (setf (gnus-agent-cat-name newcat) to)
2505             (setf (gnus-agent-cat-groups newcat) nil)
2506             newcat)
2507           gnus-category-alist)
2508     (gnus-category-write)
2509     (gnus-category-list)))
2510
2511 (defun gnus-category-add (category)
2512   "Create a new category."
2513   (interactive "SCategory name: ")
2514   (when (assq category gnus-category-alist)
2515     (error "Category %s already exists" category))
2516   (push (gnus-agent-cat-make category)
2517         gnus-category-alist)
2518   (gnus-category-write)
2519   (gnus-category-list))
2520
2521 (defun gnus-category-list ()
2522   "List all categories."
2523   (interactive)
2524   (gnus-category-prepare))
2525
2526 (defun gnus-category-exit ()
2527   "Return to the group buffer."
2528   (interactive)
2529   (kill-buffer (current-buffer))
2530   (gnus-configure-windows 'group t))
2531
2532 ;; To avoid having 8-bit characters in the source file.
2533 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2534
2535 (defvar gnus-category-predicate-alist
2536   '((spam . gnus-agent-spam-p)
2537     (short . gnus-agent-short-p)
2538     (long . gnus-agent-long-p)
2539     (low . gnus-agent-low-scored-p)
2540     (high . gnus-agent-high-scored-p)
2541     (read . gnus-agent-read-p)
2542     (true . gnus-agent-true)
2543     (false . gnus-agent-false))
2544   "Mapping from short score predicate symbols to predicate functions.")
2545
2546 (defun gnus-agent-spam-p ()
2547   "Say whether an article is spam or not."
2548   (unless gnus-agent-spam-hashtb
2549     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2550   (if (not (equal (mail-header-references gnus-headers) ""))
2551       nil
2552     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2553       (prog1
2554           (gnus-gethash string gnus-agent-spam-hashtb)
2555         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2556
2557 (defun gnus-agent-short-p ()
2558   "Say whether an article is short or not."
2559   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2560
2561 (defun gnus-agent-long-p ()
2562   "Say whether an article is long or not."
2563   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2564
2565 (defun gnus-agent-low-scored-p ()
2566   "Say whether an article has a low score or not."
2567   (< gnus-score gnus-agent-low-score))
2568
2569 (defun gnus-agent-high-scored-p ()
2570   "Say whether an article has a high score or not."
2571   (> gnus-score gnus-agent-high-score))
2572
2573 (defun gnus-agent-read-p ()
2574   "Say whether an article is read or not."
2575   (gnus-member-of-range (mail-header-number gnus-headers)
2576                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2577
2578 (defun gnus-category-make-function (predicate)
2579   "Make a function from PREDICATE."
2580   (let ((func (gnus-category-make-function-1 predicate)))
2581     (if (and (= (length func) 1)
2582              (symbolp (car func)))
2583         (car func)
2584       (gnus-byte-compile `(lambda () ,func)))))
2585
2586 (defun gnus-agent-true ()
2587   "Return t."
2588   t)
2589
2590 (defun gnus-agent-false ()
2591   "Return nil."
2592   nil)
2593
2594 (defun gnus-category-make-function-1 (predicate)
2595   "Make a function from PREDICATE."
2596   (cond
2597    ;; Functions are just returned as is.
2598    ((or (symbolp predicate)
2599         (functionp predicate))
2600     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2601            predicate)))
2602    ;; More complex predicate.
2603    ((consp predicate)
2604     `(,(cond
2605         ((memq (car predicate) '(& and))
2606          'and)
2607         ((memq (car predicate) '(| or))
2608          'or)
2609         ((memq (car predicate) gnus-category-not)
2610          'not))
2611       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2612    (t
2613     (error "Unknown predicate type: %s" predicate))))
2614
2615 (defun gnus-get-predicate (predicate)
2616   "Return the function implementing PREDICATE."
2617   (or (cdr (assoc predicate gnus-category-predicate-cache))
2618       (let ((func (gnus-category-make-function predicate)))
2619         (setq gnus-category-predicate-cache
2620               (nconc gnus-category-predicate-cache
2621                      (list (cons predicate func))))
2622         func)))
2623
2624 (defun gnus-predicate-implies-unread (predicate)
2625   "Say whether PREDICATE implies unread articles only.
2626 It is okay to miss some cases, but there must be no false positives.
2627 That is, if this predicate returns true, then indeed the predicate must
2628 return only unread articles."
2629   (eq t (gnus-function-implies-unread-1 
2630          (gnus-category-make-function-1 predicate))))
2631
2632 (defun gnus-function-implies-unread-1 (function)
2633   "Recursively evaluate a predicate function to determine whether it can select
2634 any read articles.  Returns t if the function is known to never
2635 return read articles, nil when it is known to always return read
2636 articles, and t_nil when the function may return both read and unread
2637 articles."
2638   (let ((func (car function))
2639         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2640     (cond ((eq func 'and)
2641            (cond ((memq t args) ; if any argument returns only unread articles
2642                   ;; then that argument constrains the result to only unread articles.
2643                   t)
2644                  ((memq 't_nil args) ; if any argument is indeterminate
2645                   ;; then the result is indeterminate
2646                   't_nil)))
2647           ((eq func 'or)
2648            (cond ((memq nil args) ; if any argument returns read articles
2649                   ;; then that argument ensures that the results includes read articles.
2650                   nil)
2651                  ((memq 't_nil args) ; if any argument is indeterminate
2652                   ;; then that argument ensures that the results are indeterminate
2653                   't_nil)
2654                  (t ; if all arguments return only unread articles
2655                   ;; then the result returns only unread articles
2656                   t)))
2657           ((eq func 'not)
2658            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2659                   ; then the result is indeterminate
2660                   (car args))
2661                  (t ; otherwise
2662                   ; toggle the result to be the opposite of the argument
2663                   (not (car args)))))
2664           ((eq func 'gnus-agent-read-p)
2665            nil) ; The read predicate NEVER returns unread articles
2666           ((eq func 'gnus-agent-false)
2667            t) ; The false predicate returns t as the empty set excludes all read articles
2668           ((eq func 'gnus-agent-true)
2669            nil) ; The true predicate ALWAYS returns read articles
2670           ((catch 'found-match
2671              (let ((alist gnus-category-predicate-alist))
2672                (while alist
2673                  (if (eq func (cdar alist))
2674                      (throw 'found-match t)
2675                    (setq alist (cdr alist))))))
2676            't_nil) ; All other predicates return read and unread articles
2677           (t
2678            (error "Unknown predicate function: %s" function)))))
2679
2680 (defun gnus-group-category (group)
2681   "Return the category GROUP belongs to."
2682   (unless gnus-category-group-cache
2683     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2684     (let ((cs gnus-category-alist)
2685           groups cat)
2686       (while (setq cat (pop cs))
2687         (setq groups (gnus-agent-cat-groups cat))
2688         (while groups
2689           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2690   (or (gnus-gethash group gnus-category-group-cache)
2691       (assq 'default gnus-category-alist)))
2692
2693 (defun gnus-agent-expire-group (group &optional articles force)
2694   "Expire all old articles in GROUP.
2695 If you want to force expiring of certain articles, this function can
2696 take ARTICLES, and FORCE parameters as well.
2697
2698 The articles on which the expiration process runs are selected as follows:
2699   if ARTICLES is null, all read and unmarked articles.
2700   if ARTICLES is t, all articles.
2701   if ARTICLES is a list, just those articles.
2702 FORCE is equivalent to setting the expiration predicates to true."
2703   (interactive
2704    (list (let ((def (or (gnus-group-group-name)
2705                         gnus-newsgroup-name)))
2706            (let ((select (read-string (if def
2707                                           (concat "Group Name ("
2708                                                   def "): ")
2709                                         "Group Name: "))))
2710              (if (and (equal "" select)
2711                       def)
2712                  def
2713                select)))))
2714
2715   (if (not group)
2716       (gnus-agent-expire articles group force)
2717     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2718            ;; expiration statistics of this single group
2719           (gnus-agent-expire-stats (list 0 0 0.0)))
2720       (if (or (not (eq articles t))
2721               (yes-or-no-p
2722                (concat "Are you sure that you want to "
2723                        "expire all articles in " group ".")))
2724           (let ((gnus-command-method (gnus-find-method-for-group group))
2725                 (overview (gnus-get-buffer-create " *expire overview*"))
2726                 orig)
2727             (unwind-protect
2728                 (let ((active-file (gnus-agent-lib-file "active")))
2729                   (when (file-exists-p active-file)
2730                     (with-temp-buffer
2731                       (nnheader-insert-file-contents active-file)
2732                       (gnus-active-to-gnus-format
2733                        gnus-command-method
2734                        (setq orig (gnus-make-hashtable
2735                                    (count-lines (point-min) (point-max))))))
2736                     (save-excursion
2737                       (gnus-agent-expire-group-1
2738                        group overview (gnus-gethash-safe group orig)
2739                        articles force))))
2740               (kill-buffer overview))))
2741       (gnus-message 4 (gnus-agent-expire-done-message)))))
2742
2743 (defun gnus-agent-expire-group-1 (group overview active articles force)
2744   ;; Internal function - requires caller to have set
2745   ;; gnus-command-method, initialized overview buffer, and to have
2746   ;; provided a non-nil active
2747
2748   (let ((dir (gnus-agent-group-pathname group)))
2749     (when (boundp 'gnus-agent-expire-current-dirs)
2750       (set 'gnus-agent-expire-current-dirs 
2751            (cons dir 
2752                  (symbol-value 'gnus-agent-expire-current-dirs))))
2753
2754     (if (and (not force)
2755              (eq 'DISABLE (gnus-agent-find-parameter group 
2756                                                      'agent-enable-expiration)))
2757         (gnus-message 5 "Expiry skipping over %s" group)
2758       (gnus-message 5 "Expiring articles in %s" group)
2759       (gnus-agent-load-alist group)
2760       (let* ((stats (if (boundp 'gnus-agent-expire-stats)
2761                         ;; Use the list provided by my caller
2762                         (symbol-value 'gnus-agent-expire-stats)
2763                       ;; otherwise use my own temporary list
2764                       (list 0 0 0.0)))
2765              (info (gnus-get-info group))
2766              (alist gnus-agent-article-alist)
2767              (day (- (time-to-days (current-time))
2768                      (gnus-agent-find-parameter group 'agent-days-until-old)))
2769              (specials (if (and alist
2770                                 (not force))
2771                            ;; This could be a bit of a problem.  I need to
2772                            ;; keep the last article to avoid refetching
2773                            ;; headers when using nntp in the backend.  At
2774                            ;; the same time, if someone uses a backend
2775                            ;; that supports article moving then I may have
2776                            ;; to remove the last article to complete the
2777                            ;; move.  Right now, I'm going to assume that
2778                            ;; FORCE overrides specials.
2779                            (list (caar (last alist)))))
2780              (unreads ;; Articles that are excluded from the
2781               ;; expiration process
2782               (cond (gnus-agent-expire-all
2783                      ;; All articles are marked read by global decree
2784                      nil)
2785                     ((eq articles t)
2786                      ;; All articles are marked read by function
2787                      ;; parameter
2788                      nil)
2789                     ((not articles)
2790                      ;; Unread articles are marked protected from
2791                      ;; expiration Don't call
2792                      ;; gnus-list-of-unread-articles as it returns
2793                      ;; articles that have not been fetched into the
2794                      ;; agent.
2795                      (ignore-errors
2796                        (gnus-agent-unread-articles group)))
2797                     (t
2798                      ;; All articles EXCEPT those named by the caller
2799                      ;; are protected from expiration
2800                      (gnus-sorted-difference
2801                       (gnus-uncompress-range
2802                        (cons (caar alist)
2803                              (caar (last alist))))
2804                       (sort articles '<)))))
2805              (marked ;; More articles that are excluded from the
2806               ;; expiration process
2807               (cond (gnus-agent-expire-all
2808                      ;; All articles are unmarked by global decree
2809                      nil)
2810                     ((eq articles t)
2811                      ;; All articles are unmarked by function
2812                      ;; parameter
2813                      nil)
2814                     (articles
2815                      ;; All articles may as well be unmarked as the
2816                      ;; unreads list already names the articles we are
2817                      ;; going to keep
2818                      nil)
2819                     (t
2820                      ;; Ticked and/or dormant articles are excluded
2821                      ;; from expiration
2822                      (nconc
2823                       (gnus-uncompress-range
2824                        (cdr (assq 'tick (gnus-info-marks info))))
2825                       (gnus-uncompress-range
2826                        (cdr (assq 'dormant
2827                                   (gnus-info-marks info))))))))
2828              (nov-file (concat dir ".overview"))
2829              (cnt 0)
2830              (completed -1)
2831              dlist
2832              type)
2833
2834         ;; The normal article alist contains elements that look like
2835         ;; (article# .  fetch_date) I need to combine other
2836         ;; information with this list.  For example, a flag indicating
2837         ;; that a particular article MUST BE KEPT.  To do this, I'm
2838         ;; going to transform the elements to look like (article#
2839         ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2840         ;; the process to generate the expired article alist.
2841
2842         ;; Convert the alist elements to (article# fetch_date nil
2843         ;; nil).
2844         (setq dlist (mapcar (lambda (e)
2845                               (list (car e) (cdr e) nil nil)) alist))
2846
2847         ;; Convert the keep lists to elements that look like (article#
2848         ;; nil keep_flag nil) then append it to the expanded dlist
2849         ;; These statements are sorted by ascending precidence of the
2850         ;; keep_flag.
2851         (setq dlist (nconc dlist
2852                            (mapcar (lambda (e)
2853                                      (list e nil 'unread  nil))
2854                                    unreads)))
2855         (setq dlist (nconc dlist
2856                            (mapcar (lambda (e)
2857                                      (list e nil 'marked  nil))
2858                                    marked)))
2859         (setq dlist (nconc dlist
2860                            (mapcar (lambda (e)
2861                                      (list e nil 'special nil))
2862                                    specials)))
2863
2864         (set-buffer overview)
2865         (erase-buffer)
2866         (buffer-disable-undo)
2867         (when (file-exists-p nov-file)
2868           (gnus-message 7 "gnus-agent-expire: Loading overview...")
2869           (nnheader-insert-file-contents nov-file)
2870           (goto-char (point-min))
2871
2872           (let (p)
2873             (while (< (setq p (point)) (point-max))
2874               (condition-case nil
2875                   ;; If I successfully read an integer (the plus zero
2876                   ;; ensures a numeric type), prepend a marker entry
2877                   ;; to the list
2878                   (push (list (+ 0 (read (current-buffer))) nil nil
2879                               (set-marker (make-marker) p))
2880                         dlist)
2881                 (error
2882                  (gnus-message 1 "gnus-agent-expire: read error \
2883 occurred when reading expression at %s in %s.  Skipping to next \
2884 line." (point) nov-file)))
2885               ;; Whether I succeeded, or failed, it doesn't matter.
2886               ;; Move to the next line then try again.
2887               (forward-line 1)))
2888
2889           (gnus-message
2890            7 "gnus-agent-expire: Loading overview... Done"))
2891         (set-buffer-modified-p nil)
2892
2893         ;; At this point, all of the information is in dlist.  The
2894         ;; only problem is that much of it is spread across multiple
2895         ;; entries.  Sort then MERGE!!
2896         (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2897         ;; If two entries have the same article-number then sort by
2898         ;; ascending keep_flag.
2899         (let ((special 0)
2900               (marked 1)
2901               (unread 2))
2902           (setq dlist
2903                 (sort dlist
2904                       (lambda (a b)
2905                         (cond ((< (nth 0 a) (nth 0 b))
2906                                t)
2907                               ((> (nth 0 a) (nth 0 b))
2908                                nil)
2909                               (t
2910                                (let ((a (or (symbol-value (nth 2 a))
2911                                             3))
2912                                      (b (or (symbol-value (nth 2 b))
2913                                             3)))
2914                                  (<= a b))))))))
2915         (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2916         (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2917         (let ((dlist dlist))
2918           (while (cdr dlist)            ; I'm not at the end-of-list
2919             (if (eq (caar dlist) (caadr dlist))
2920                 (let ((first (cdr (car dlist)))
2921                       (secnd (cdr (cadr dlist))))
2922                   (setcar first (or (car first)
2923                                     (car secnd))) ; fetch_date
2924                   (setq first (cdr first)
2925                         secnd (cdr secnd))
2926                   (setcar first (or (car first)
2927                                     (car secnd))) ; Keep_flag
2928                   (setq first (cdr first)
2929                         secnd (cdr secnd))
2930                   (setcar first (or (car first)
2931                                     (car secnd))) ; NOV_entry_marker
2932
2933                   (setcdr dlist (cddr dlist)))
2934               (setq dlist (cdr dlist)))))
2935         (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2936
2937         (let* ((len (float (length dlist)))
2938                (alist (list nil))
2939                (tail-alist alist))
2940           (while dlist
2941             (let ((new-completed (truncate (* 100.0
2942                                               (/ (setq cnt (1+ cnt))
2943                                                  len))))
2944                   message-log-max)
2945               (when (> new-completed completed)
2946                 (setq completed new-completed)
2947                 (gnus-message 7 "%3d%% completed..."  completed)))
2948             (let* ((entry          (car dlist))
2949                    (article-number (nth 0 entry))
2950                    (fetch-date     (nth 1 entry))
2951                    (keep           (nth 2 entry))
2952                    (marker         (nth 3 entry)))
2953
2954               (cond
2955                ;; Kept articles are unread, marked, or special.
2956                (keep
2957                 (gnus-agent-message 10
2958                                     "gnus-agent-expire: %s:%d: Kept %s article%s."
2959                                     group article-number keep (if fetch-date " and file" ""))
2960                 (when fetch-date
2961                   (unless (file-exists-p
2962                            (concat dir (number-to-string
2963                                         article-number)))
2964                     (setf (nth 1 entry) nil)
2965                     (gnus-agent-message 3 "gnus-agent-expire cleared \
2966 download flag on %s:%d as the cached article file is missing."
2967                                         group (caar dlist)))
2968                   (unless marker
2969                     (gnus-message 1 "gnus-agent-expire detected a \
2970 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2971                 (gnus-agent-append-to-list
2972                  tail-alist
2973                  (cons article-number fetch-date)))
2974
2975                ;; The following articles are READ, UNMARKED, and
2976                ;; ORDINARY.  See if they can be EXPIRED!!!
2977                ((setq type
2978                       (cond
2979                        ((not (integerp fetch-date))
2980                         'read) ;; never fetched article (may expire
2981                        ;; right now)
2982                        ((not (file-exists-p
2983                               (concat dir (number-to-string
2984                                            article-number))))
2985                         (setf (nth 1 entry) nil)
2986                         'externally-expired) ;; Can't find the cached
2987                        ;; article.  Handle case
2988                        ;; as though this article
2989                        ;; was never fetched.
2990
2991                        ;; We now have the arrival day, so we see
2992                        ;; whether it's old enough to be expired.
2993                        ((< fetch-date day)
2994                         'expired)
2995                        (force
2996                         'forced)))
2997
2998                 ;; I found some reason to expire this entry.
2999
3000                 (let ((actions nil))
3001                   (when (memq type '(forced expired))
3002                     (ignore-errors      ; Just being paranoid.
3003                       (let ((file-name (concat dir (number-to-string
3004                                                 article-number))))
3005                         (incf (nth 2 stats) (nth 7 (file-attributes file-name)))
3006                         (incf (nth 1 stats))
3007                         (delete-file file-name))
3008                       (push "expired cached article" actions))
3009                     (setf (nth 1 entry) nil)
3010                     )
3011
3012                   (when marker
3013                     (push "NOV entry removed" actions)
3014                     (goto-char marker)
3015
3016                     (incf (nth 0 stats))
3017
3018                     (let ((from (point-at-bol))
3019                           (to (progn (forward-line 1) (point))))
3020                       (incf (nth 2 stats) (- to from))
3021                       (delete-region from to)))
3022
3023                   ;; If considering all articles is set, I can only
3024                   ;; expire article IDs that are no longer in the
3025                   ;; active range (That is, articles that preceed the
3026                   ;; first article in the new alist).
3027                   (if (and gnus-agent-consider-all-articles
3028                            (>= article-number (car active)))
3029                       ;; I have to keep this ID in the alist
3030                       (gnus-agent-append-to-list
3031                        tail-alist (cons article-number fetch-date))
3032                     (push (format "Removed %s article number from \
3033 article alist" type) actions))
3034
3035                   (when actions
3036                     (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3037                                         group article-number
3038                                         (mapconcat 'identity actions ", ")))))
3039                (t
3040                 (gnus-agent-message
3041                  10 "gnus-agent-expire: %s:%d: Article kept as \
3042 expiration tests failed." group article-number)
3043                 (gnus-agent-append-to-list
3044                  tail-alist (cons article-number fetch-date)))
3045                )
3046
3047               ;; Clean up markers as I want to recycle this buffer
3048               ;; over several groups.
3049               (when marker
3050                 (set-marker marker nil))
3051
3052               (setq dlist (cdr dlist))))
3053
3054           (setq alist (cdr alist))
3055
3056           (let ((inhibit-quit t))
3057             (unless (equal alist gnus-agent-article-alist)
3058               (setq gnus-agent-article-alist alist)
3059               (gnus-agent-save-alist group))
3060
3061             (when (buffer-modified-p)
3062               (gnus-make-directory dir)
3063               (write-region-as-coding-system gnus-agent-file-coding-system
3064                                              (point-min) (point-max) nov-file
3065                                              nil 'silent)
3066               ;; clear the modified flag as that I'm not confused by
3067               ;; its status on the next pass through this routine.
3068               (set-buffer-modified-p nil))
3069
3070             (when (eq articles t)
3071               (gnus-summary-update-info))))))))
3072
3073 (defun gnus-agent-expire (&optional articles group force)
3074   "Expire all old articles.
3075 If you want to force expiring of certain articles, this function can
3076 take ARTICLES, GROUP and FORCE parameters as well.
3077
3078 The articles on which the expiration process runs are selected as follows:
3079   if ARTICLES is null, all read and unmarked articles.
3080   if ARTICLES is t, all articles.
3081   if ARTICLES is a list, just those articles.
3082 Setting GROUP will limit expiration to that group.
3083 FORCE is equivalent to setting the expiration predicates to true."
3084   (interactive)
3085   
3086   (if group
3087       (gnus-agent-expire-group group articles force)
3088     (if (or (not (eq articles t))
3089             (yes-or-no-p "Are you sure that you want to expire all \
3090 articles in every agentized group."))
3091         (let ((methods (gnus-agent-covered-methods))
3092               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3093               ;; of agent directories.
3094               (gnus-agent-expire-current-dirs nil)
3095               ;; Bind gnus-agent-expire-stats to enable tracking of
3096               ;; expiration statistics across all groups
3097               (gnus-agent-expire-stats (list 0 0 0.0))
3098               gnus-command-method overview orig)
3099           (setq overview (gnus-get-buffer-create " *expire overview*"))
3100           (unwind-protect
3101               (while (setq gnus-command-method (pop methods))
3102                 (let ((active-file (gnus-agent-lib-file "active")))
3103                   (when (file-exists-p active-file)
3104                     (with-temp-buffer
3105                       (nnheader-insert-file-contents active-file)
3106                       (gnus-active-to-gnus-format
3107                        gnus-command-method
3108                        (setq orig (gnus-make-hashtable
3109                                    (count-lines (point-min) (point-max))))))
3110                     (dolist (expiring-group (gnus-groups-from-server
3111                                              gnus-command-method))
3112                       (let* ((active
3113                               (gnus-gethash-safe expiring-group orig)))
3114                                         
3115                         (when active
3116                           (save-excursion
3117                             (gnus-agent-expire-group-1
3118                              expiring-group overview active articles force))))))))
3119             (kill-buffer overview))
3120           (gnus-agent-expire-unagentized-dirs)
3121           (gnus-message 4 (gnus-agent-expire-done-message))))))
3122
3123 (defun gnus-agent-expire-done-message ()
3124   (if (and (> gnus-verbose 4)
3125            (boundp 'gnus-agent-expire-stats))
3126       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3127              (size (nth 2 stats))
3128             (units '(B KB MB GB)))
3129         (while (and (> size 1024.0)
3130                     (cdr units))
3131           (setq size (/ size 1024.0)
3132                 units (cdr units)))
3133
3134         (format "Expiry recovered %d NOV entries, deleted %d files,\
3135  and freed %f %s." 
3136                 (nth 0 stats) 
3137                 (nth 1 stats) 
3138                 size (car units)))
3139     "Expiry...done"))
3140
3141 (defun gnus-agent-expire-unagentized-dirs ()
3142   (when (and gnus-agent-expire-unagentized-dirs
3143              (boundp 'gnus-agent-expire-current-dirs))
3144     (let* ((keep (gnus-make-hashtable))
3145            ;; Formally bind gnus-agent-expire-current-dirs so that the
3146            ;; compiler will not complain about free references.
3147            (gnus-agent-expire-current-dirs
3148             (symbol-value 'gnus-agent-expire-current-dirs))
3149            dir)
3150
3151       (gnus-sethash gnus-agent-directory t keep)
3152       (while gnus-agent-expire-current-dirs
3153         (setq dir (pop gnus-agent-expire-current-dirs))
3154         (when (and (stringp dir)
3155                    (file-directory-p dir))
3156           (while (not (gnus-gethash dir keep))
3157             (gnus-sethash dir t keep)
3158             (setq dir (file-name-directory (directory-file-name dir))))))
3159
3160       (let* (to-remove
3161              checker
3162              (checker
3163               (function
3164                (lambda (d)
3165                  "Given a directory, check it and its subdirectories for 
3166               membership in the keep hash.  If it isn't found, add 
3167               it to to-remove." 
3168                  (let ((files (directory-files d))
3169                        file)
3170                    (while (setq file (pop files))
3171                      (cond ((equal file ".") ; Ignore self
3172                             nil)
3173                            ((equal file "..") ; Ignore parent
3174                             nil)
3175                            ((equal file ".overview") 
3176                             ;; Directory must contain .overview to be
3177                             ;; agent's cache of a group.
3178                             (let ((d (file-name-as-directory d))
3179                                   r)
3180                               ;; Search ancestor's for last directory NOT
3181                               ;; found in keep hash.
3182                               (while (not (gnus-gethash
3183                                            (setq d (file-name-directory d)) keep))
3184                                 (setq r d
3185                                       d (directory-file-name d)))
3186                               ;; if ANY ancestor was NOT in keep hash and
3187                               ;; it it's already in to-remove, add it to
3188                               ;; to-remove.                          
3189                               (if (and r
3190                                        (not (member r to-remove)))
3191                                   (push r to-remove))))
3192                            ((file-directory-p (setq file (nnheader-concat d file)))
3193                             (funcall checker file)))))))))
3194         (funcall checker (expand-file-name gnus-agent-directory))
3195
3196         (when (and to-remove
3197                    (or gnus-expert-user
3198                        (gnus-y-or-n-p
3199                         "gnus-agent-expire has identified local directories that are\
3200  not currently required by any agentized group.  Do you wish to consider\
3201  deleting them?")))
3202           (while to-remove
3203             (let ((dir (pop to-remove)))
3204               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3205                   (let* (delete-recursive
3206                          (delete-recursive
3207                           (function
3208                            (lambda (f-or-d)
3209                              (ignore-errors
3210                                (if (file-directory-p f-or-d)
3211                                    (condition-case nil
3212                                        (delete-directory f-or-d)
3213                                      (file-error
3214                                       (mapcar (lambda (f)
3215                                                 (or (member f '("." ".."))
3216                                                     (funcall delete-recursive
3217                                                              (nnheader-concat
3218                                                               f-or-d f))))
3219                                               (directory-files f-or-d))
3220                                       (delete-directory f-or-d)))
3221                                  (delete-file f-or-d)))))))
3222                     (funcall delete-recursive dir))))))))))
3223
3224 ;;;###autoload
3225 (defun gnus-agent-batch ()
3226   "Start Gnus, send queue and fetch session."
3227   (interactive)
3228   (let ((init-file-user "")
3229         (gnus-always-read-dribble-file t))
3230     (gnus))
3231   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3232     (gnus-group-send-queue)
3233     (gnus-agent-fetch-session)))
3234
3235 (defun gnus-agent-unread-articles (group)
3236   (let* ((read (gnus-info-read (gnus-get-info group)))
3237          (known (gnus-agent-load-alist group))
3238          (unread (list nil))
3239          (tail-unread unread))
3240     (while (and known read)
3241       (let ((candidate (car (pop known))))
3242         (while (let* ((range (car read))
3243                       (min   (if (numberp range) range (car range)))
3244                       (max   (if (numberp range) range (cdr range))))
3245                  (cond ((or (not min)
3246                             (< candidate min))
3247                         (gnus-agent-append-to-list tail-unread candidate)
3248                         nil)
3249                        ((> candidate max)
3250                         (setq read (cdr read))
3251                         ;; return t so that I always loop one more
3252                         ;; time.  If I just iterated off the end of
3253                         ;; read, min will become nil and the current
3254                         ;; candidate will be added to the unread list.
3255                         t))))))
3256     (while known
3257       (gnus-agent-append-to-list tail-unread (car (pop known))))
3258     (cdr unread)))
3259
3260 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3261   "Restrict ARTICLES to numbers already fetched.
3262 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3263 that have already been fetched.
3264 If CACHED-HEADER is nil, articles are only excluded if the article itself
3265 has been fetched."
3266
3267   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3268   ;; 'car gnus-agent-article-alist))
3269
3270   ;; Functionally, I don't need to construct a temp list using mapcar.
3271
3272   (if (and (or gnus-agent-cache (not gnus-plugged))
3273            (gnus-agent-load-alist group))
3274     (let* ((ref gnus-agent-article-alist)
3275            (arts articles)
3276            (uncached (list nil))
3277            (tail-uncached uncached))
3278       (while (and ref arts)
3279         (let ((v1 (car arts))
3280               (v2 (caar ref)))
3281           (cond ((< v1 v2) ; v1 does not appear in the reference list
3282                  (gnus-agent-append-to-list tail-uncached v1)
3283                  (setq arts (cdr arts)))
3284                 ((= v1 v2)
3285                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3286                    (gnus-agent-append-to-list tail-uncached v1))
3287                  (setq arts (cdr arts))
3288                  (setq ref (cdr ref)))
3289                 (t ; reference article (v2) preceeds the list being filtered
3290                  (setq ref (cdr ref))))))
3291       (while arts
3292         (gnus-agent-append-to-list tail-uncached (pop arts)))
3293       (cdr uncached))
3294     ;; if gnus-agent-load-alist fails, no articles are cached.
3295     articles))
3296
3297 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3298   (save-excursion
3299     (gnus-agent-create-buffer)
3300     (let ((gnus-decode-encoded-word-function 'identity)
3301           (file (gnus-agent-article-name ".overview" group))
3302           cached-articles uncached-articles)
3303       (gnus-make-directory (nnheader-translate-file-chars
3304                             (file-name-directory file) t))
3305
3306       ;; Populate temp buffer with known headers
3307       (when (file-exists-p file)
3308         (with-current-buffer gnus-agent-overview-buffer
3309           (erase-buffer)
3310           (let ((nnheader-file-coding-system
3311                  gnus-agent-file-coding-system))
3312             (nnheader-insert-nov-file file (car articles)))))
3313
3314       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3315                                                                 t))
3316           (progn
3317             ;; Populate nntp-server-buffer with uncached headers
3318             (set-buffer nntp-server-buffer)
3319             (erase-buffer)
3320             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3321                                    (gnus-retrieve-headers
3322                                     uncached-articles group fetch-old))))
3323                    (nnvirtual-convert-headers))
3324                   ((eq 'nntp (car gnus-current-select-method))
3325                    ;; The author of gnus-get-newsgroup-headers-xover
3326                    ;; reports that the XOVER command is commonly
3327                    ;; unreliable. The problem is that recently
3328                    ;; posted articles may not be entered into the
3329                    ;; NOV database in time to respond to my XOVER
3330                    ;; query.
3331                    ;;
3332                    ;; I'm going to use his assumption that the NOV
3333                    ;; database is updated in order of ascending
3334                    ;; article ID.  Therefore, a response containing
3335                    ;; article ID N implies that all articles from 1
3336                    ;; to N-1 are up-to-date.  Therefore, missing
3337                    ;; articles in that range have expired.
3338
3339                    (set-buffer nntp-server-buffer)
3340                    (let* ((fetched-articles (list nil))
3341                           (tail-fetched-articles fetched-articles)
3342                           (min (cond ((numberp fetch-old)
3343                                       (max 1 (- (car articles) fetch-old)))
3344                                      (fetch-old
3345                                       1)
3346                                      (t
3347                                       (car articles))))
3348                           (max (car (last articles))))
3349
3350                      ;; Get the list of articles that were fetched
3351                      (goto-char (point-min))
3352                      (let ((pm (point-max)))
3353                        (while (< (point) pm)
3354                          (when (looking-at "[0-9]+\t")
3355                            (gnus-agent-append-to-list
3356                             tail-fetched-articles
3357                             (read (current-buffer))))
3358                          (forward-line 1)))
3359
3360                      ;; Clip this list to the headers that will
3361                      ;; actually be returned
3362                      (setq fetched-articles (gnus-list-range-intersection
3363                                              (cdr fetched-articles)
3364                                              (cons min max)))
3365
3366                      ;; Clip the uncached articles list to exclude
3367                      ;; IDs after the last FETCHED header.  The
3368                      ;; excluded IDs may be fetchable using HEAD.
3369                      (if (car tail-fetched-articles)
3370                          (setq uncached-articles
3371                                (gnus-list-range-intersection
3372                                 uncached-articles
3373                                 (cons (car uncached-articles)
3374                                       (car tail-fetched-articles)))))
3375
3376                      ;; Create the list of articles that were
3377                      ;; "successfully" fetched.  Success, in this
3378                      ;; case, means that the ID should not be
3379                      ;; fetched again.  In the case of an expired
3380                      ;; article, the header will not be fetched.
3381                      (setq uncached-articles
3382                            (gnus-sorted-nunion fetched-articles
3383                                                uncached-articles))
3384                      )))
3385
3386             ;; Erase the temp buffer
3387             (set-buffer gnus-agent-overview-buffer)
3388             (erase-buffer)
3389
3390             ;; Copy the nntp-server-buffer to the temp buffer
3391             (set-buffer nntp-server-buffer)
3392             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3393
3394             ;; Merge the temp buffer with the known headers (found on
3395             ;; disk in FILE) into the nntp-server-buffer
3396             (when (and uncached-articles (file-exists-p file))
3397               (gnus-agent-braid-nov group uncached-articles file))
3398
3399             ;; Save the new set of known headers to FILE
3400             (set-buffer nntp-server-buffer)
3401             (gnus-agent-check-overview-buffer)
3402             (write-region-as-coding-system
3403              gnus-agent-file-coding-system
3404              (point-min) (point-max) file nil 'silent)
3405
3406             ;; Update the group's article alist to include the newly
3407             ;; fetched articles.
3408             (gnus-agent-load-alist group)
3409             (gnus-agent-save-alist group uncached-articles nil)
3410             )
3411
3412         ;; Copy the temp buffer to the nntp-server-buffer
3413         (set-buffer nntp-server-buffer)
3414         (erase-buffer)
3415         (insert-buffer-substring gnus-agent-overview-buffer)))
3416
3417     (if (and fetch-old
3418              (not (numberp fetch-old)))
3419         t                               ; Don't remove anything.
3420       (nnheader-nov-delete-outside-range
3421        (if fetch-old (max 1 (- (car articles) fetch-old))
3422          (car articles))
3423        (car (last articles)))
3424       t)
3425
3426     'nov))
3427
3428 (defun gnus-agent-request-article (article group)
3429   "Retrieve ARTICLE in GROUP from the agent cache."
3430   (when (and gnus-agent
3431              (or gnus-agent-cache
3432                  (not gnus-plugged))
3433              (numberp article))
3434     (let* ((gnus-command-method (gnus-find-method-for-group group))
3435            (file (gnus-agent-article-name (number-to-string article) group))
3436            (buffer-read-only nil))
3437       (when (and (file-exists-p file)
3438                  (> (nth 7 (file-attributes file)) 0))
3439         (erase-buffer)
3440         (gnus-kill-all-overlays)
3441         (insert-file-contents-as-coding-system gnus-cache-coding-system file)
3442         t))))
3443
3444 (defun gnus-agent-regenerate-group (group &optional reread)
3445   "Regenerate GROUP.
3446 If REREAD is t, all articles in the .overview are marked as unread.
3447 If REREAD is not nil, downloaded articles are marked as unread."
3448   (interactive
3449    (list (let ((def (or (gnus-group-group-name)
3450                         gnus-newsgroup-name)))
3451            (let ((select (read-string (if def
3452                                           (concat "Group Name ("
3453                                                   def "): ")
3454                                         "Group Name: "))))
3455              (if (and (equal "" select)
3456                       def)
3457                  def
3458                select)))
3459          (catch 'mark
3460            (while (let (c
3461                         (cursor-in-echo-area t)
3462                         (echo-keystrokes 0))
3463                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3464                     (setq c (read-char-exclusive))
3465
3466                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3467                            (throw 'mark nil))
3468                           ((or (eq c ?a) (eq c ?A))
3469                            (throw 'mark t))
3470                           ((or (eq c ?d) (eq c ?D))
3471                            (throw 'mark 'some)))
3472                     (gnus-message 3 "Ignoring unexpected input")
3473                     (sit-for 1)
3474                     t)))))
3475
3476   (when group
3477       (gnus-message 5 "Regenerating in %s" group)
3478       (let* ((gnus-command-method (or gnus-command-method
3479                                       (gnus-find-method-for-group group)))
3480              (file (gnus-agent-article-name ".overview" group))
3481              (dir (file-name-directory file))
3482              point
3483              (downloaded (if (file-exists-p dir)
3484                              (sort (mapcar (lambda (name) (string-to-int name))
3485                                            (directory-files dir nil "^[0-9]+$" t))
3486                                    '>)
3487                            (progn (gnus-make-directory dir) nil)))
3488              dl nov-arts
3489              alist header
3490              regenerated)
3491
3492         (mm-with-unibyte-buffer
3493           (if (file-exists-p file)
3494               (let ((nnheader-file-coding-system
3495                      gnus-agent-file-coding-system))
3496                 (nnheader-insert-file-contents file)))
3497           (set-buffer-modified-p nil)
3498
3499           ;; Load the article IDs found in the overview file.  As a
3500           ;; side-effect, validate the file contents.
3501           (let ((load t))
3502             (while load
3503               (setq load nil)
3504               (goto-char (point-min))
3505               (while (< (point) (point-max))
3506                 (cond ((and (looking-at "[0-9]+\t")
3507                             (<= (- (match-end 0) (match-beginning 0)) 9))
3508                        (push (read (current-buffer)) nov-arts)
3509                        (forward-line 1)
3510                        (let ((l1 (car nov-arts))
3511                              (l2 (cadr nov-arts)))
3512                          (cond ((not l2)
3513                                 nil)
3514                                ((< l1 l2)
3515                                 (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3516  entries are NOT in ascending order.")
3517                                 ;; Don't sort now as I haven't verified
3518                                 ;; that every line begins with a number
3519                                 (setq load t))
3520                                ((= l1 l2)
3521                                 (forward-line -1)
3522                                 (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3523  entries contained duplicate of article %s.      Duplicate deleted." l1)
3524                                 (gnus-delete-line)
3525                                 (setq nov-arts (cdr nov-arts))))))
3526                       (t
3527                        (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3528  entries contained line that did not begin with an article number.  Deleted\
3529  line.")
3530                        (gnus-delete-line))))
3531               (if load
3532                   (progn
3533                     (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3534  entries into ascending order.")
3535                     (sort-numeric-fields 1 (point-min) (point-max))
3536                     (setq nov-arts nil)))))
3537           (gnus-agent-check-overview-buffer)
3538
3539           ;; Construct a new article alist whose nodes match every header
3540           ;; in the .overview file.  As a side-effect, missing headers are
3541           ;; reconstructed from the downloaded article file.
3542           (while (or downloaded nov-arts)
3543             (cond ((and downloaded
3544                         (or (not nov-arts)
3545                             (> (car downloaded) (car nov-arts))))
3546                    ;; This entry is missing from the overview file
3547                    (gnus-message 3 "Regenerating NOV %s %d..." group
3548                                  (car downloaded))
3549                    (let ((file (concat dir (number-to-string (car downloaded)))))
3550                      (mm-with-unibyte-buffer
3551                        (nnheader-insert-file-contents file)
3552                        (nnheader-remove-body)
3553                        (setq header (nnheader-parse-naked-head)))
3554                      (mail-header-set-number header (car downloaded))
3555                      (if nov-arts
3556                          (let ((key (concat "^" (int-to-string (car nov-arts))
3557                                             "\t")))
3558                            (or (re-search-backward key nil t)
3559                                (re-search-forward key))
3560                            (forward-line 1))
3561                        (goto-char (point-min)))
3562                      (nnheader-insert-nov header))
3563                    (setq nov-arts (cons (car downloaded) nov-arts)))
3564                   ((eq (car downloaded) (car nov-arts))
3565                    ;; This entry in the overview has been downloaded
3566                    (push (cons (car downloaded)
3567                                (time-to-days
3568                                 (nth 5 (file-attributes
3569                                         (concat dir (number-to-string
3570                                                      (car downloaded))))))) alist)
3571                    (setq downloaded (cdr downloaded))
3572                    (setq nov-arts (cdr nov-arts)))
3573                   (t
3574                    ;; This entry in the overview has not been downloaded
3575                    (push (cons (car nov-arts) nil) alist)
3576                    (setq nov-arts (cdr nov-arts)))))
3577
3578           ;; When gnus-agent-consider-all-articles is set,
3579           ;; gnus-agent-regenerate-group should NOT remove article IDs from
3580           ;; the alist.  Those IDs serve as markers to indicate that an
3581           ;; attempt has been made to fetch that article's header.
3582
3583           ;; When gnus-agent-consider-all-articles is NOT set,
3584           ;; gnus-agent-regenerate-group can remove the article ID of every
3585           ;; article (with the exception of the last ID in the list - it's
3586           ;; special) that no longer appears in the overview.  In this
3587           ;; situtation, the last article ID in the list implies that it,
3588           ;; and every article ID preceeding it, have been fetched from the
3589           ;; server.
3590
3591           (if gnus-agent-consider-all-articles
3592               ;; Restore all article IDs that were not found in the overview file.
3593               (let* ((n (cons nil alist))
3594                      (merged n)
3595                      (o (gnus-agent-load-alist group)))
3596                 (while o
3597                   (let ((nID (caadr n))
3598                         (oID (caar o)))
3599                     (cond ((not nID)
3600                            (setq n (setcdr n (list (list oID))))
3601                            (setq o (cdr o)))
3602                           ((< oID nID)
3603                            (setcdr n (cons (list oID) (cdr n)))
3604                            (setq o (cdr o)))
3605                           ((= oID nID)
3606                            (setq o (cdr o))
3607                            (setq n (cdr n)))
3608                           (t
3609                            (setq n (cdr n))))))
3610                 (setq alist (cdr merged)))
3611             ;; Restore the last article ID if it is not already in the new alist
3612             (let ((n (last alist))
3613                   (o (last (gnus-agent-load-alist group))))
3614               (cond ((not o)
3615                      nil)
3616                     ((not n)
3617                      (push (cons (caar o) nil) alist))
3618                     ((< (caar n) (caar o))
3619                      (setcdr n (list (car o)))))))
3620
3621           (let ((inhibit-quit t))
3622             (if (setq regenerated (buffer-modified-p))
3623                 (write-region-as-coding-system
3624                  gnus-agent-file-coding-system
3625                  (point-min) (point-max) file nil 'silent))
3626
3627             (setq regenerated (or regenerated
3628                                   (and reread gnus-agent-article-alist)
3629                                   (not (equal alist gnus-agent-article-alist))))
3630
3631             (setq gnus-agent-article-alist alist)
3632
3633             (when regenerated
3634               (gnus-agent-save-alist group)
3635        
3636               ;; I have to alter the group's active range NOW as
3637               ;; gnus-make-ascending-articles-unread will use it to
3638               ;; recalculate the number of unread articles in the group
3639
3640               (let ((group (gnus-group-real-name group))
3641                     (group-active (gnus-active group)))
3642                 (gnus-agent-possibly-alter-active group group-active)))))
3643
3644         (when (and reread gnus-agent-article-alist)
3645           (gnus-make-ascending-articles-unread
3646            group
3647            (delq nil (mapcar (function (lambda (c)
3648                                          (cond ((eq reread t)
3649                                                 (car c))
3650                                                ((cdr c)
3651                                                 (car c)))))
3652                              gnus-agent-article-alist)))
3653
3654           (when (gnus-buffer-live-p gnus-group-buffer)
3655             (gnus-group-update-group group t)
3656             (sit-for 0)))
3657
3658         (gnus-message 5 nil)
3659         regenerated)))
3660
3661 ;;;###autoload
3662 (defun gnus-agent-regenerate (&optional clean reread)
3663   "Regenerate all agent covered files.
3664 If CLEAN, obsolete (ignore)."
3665   (interactive "P")
3666   (let (regenerated)
3667     (gnus-message 4 "Regenerating Gnus agent files...")
3668     (dolist (gnus-command-method (gnus-agent-covered-methods))
3669         (dolist (group (gnus-groups-from-server gnus-command-method))
3670           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3671                                 regenerated))))
3672     (gnus-message 4 "Regenerating Gnus agent files...done")
3673
3674     regenerated))
3675
3676 (defun gnus-agent-go-online (&optional force)
3677   "Switch servers into online status."
3678   (interactive (list t))
3679   (dolist (server gnus-opened-servers)
3680     (when (eq (nth 1 server) 'offline)
3681       (if (if (eq force 'ask)
3682               (gnus-y-or-n-p
3683                (format "Switch %s:%s into online status? "
3684                        (caar server) (cadar server)))
3685             force)
3686           (setcar (nthcdr 1 server) 'close)))))
3687
3688 (defun gnus-agent-toggle-group-plugged (group)
3689   "Toggle the status of the server of the current group."
3690   (interactive (list (gnus-group-group-name)))
3691   (let* ((method (gnus-find-method-for-group group))
3692          (status (cadr (assoc method gnus-opened-servers))))
3693     (if (eq status 'offline)
3694         (gnus-server-set-status method 'closed)
3695       (gnus-close-server method)
3696       (gnus-server-set-status method 'offline))
3697     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3698              (if (eq status 'offline) 'offline 'online)
3699              (if (eq status 'offline) 'online 'offline))))
3700
3701 (defun gnus-agent-group-covered-p (group)
3702   (gnus-agent-method-p (gnus-group-method group)))
3703
3704 (add-hook 'gnus-group-prepare-hook
3705           (lambda ()
3706             'gnus-agent-do-once
3707
3708             (when (listp gnus-agent-expire-days)
3709               (beep)
3710               (beep)
3711               (gnus-message 1 "WARNING: gnus-agent-expire-days no longer\
3712  supports being set to a list.")(sleep-for 3)
3713               (gnus-message 1 "Change your configuration to set it to an\
3714  integer.")(sleep-for 3)
3715               (gnus-message 1 "I am now setting group parameters on each\
3716  group to match the configuration that the list offered.")
3717
3718               (save-excursion
3719                 (let ((groups (gnus-group-listed-groups)))
3720                   (while groups
3721                     (let* ((group (pop groups))
3722                            (days gnus-agent-expire-days)
3723                            (day (catch 'found
3724                                   (while days
3725                                     (when (eq 0 (string-match
3726                                                  (caar days)
3727                                                  group))
3728                                       (throw 'found (cadar days)))
3729                                     (setq days (cdr days)))
3730                                   nil)))
3731                       (when day
3732                         (gnus-group-set-parameter group 'agent-days-until-old
3733                                                   day))))))
3734
3735               (let ((h gnus-group-prepare-hook))
3736                 (while h
3737                   (let ((func (pop h)))
3738                     (when (and (listp func)
3739                                (eq (cadr (caddr func)) 'gnus-agent-do-once))
3740                       (remove-hook 'gnus-group-prepare-hook func)
3741                       (setq h nil)))))
3742
3743               (gnus-message 1 "I have finished setting group parameters on\
3744  each group. You may now customize your groups and/or topics to control the\
3745  agent."))))
3746
3747 (provide 'gnus-agent)
3748
3749 ;;; gnus-agent.el ends here