Synch with Oort Gnus.
[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
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 (eval-when-compile (require 'gnus-clfns))
30
31 (require 'gnus)
32 (require 'gnus-cache)
33 (require 'nnvirtual)
34 (require 'gnus-sum)
35 (require 'gnus-score)
36 (require 'gnus-srvr)
37 (eval-when-compile
38   (if (featurep 'xemacs)
39       (require 'itimer)
40     (require 'timer))
41   (require 'gnus-group))
42
43 (eval-and-compile
44   (autoload 'gnus-server-update-server "gnus-srvr")
45   (autoload 'number-at-point "thingatpt"))
46
47 (defface gnus-agent-downloaded-article-face
48   '((((class color) (background light)) (:foreground "Orange" :bold t))
49     (((class color) (background dark)) (:foreground "Yellow" :bold t))
50     (t (:inverse-video t :bold t)))
51   "Face used for displaying downloaded articles"
52   :group 'gnus-agent)
53
54 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
55   "Where the Gnus agent will store its files."
56   :group 'gnus-agent
57   :type 'directory)
58
59 (defcustom gnus-agent-plugged-hook nil
60   "Hook run when plugging into the network."
61   :group 'gnus-agent
62   :type 'hook)
63
64 (defcustom gnus-agent-unplugged-hook nil
65   "Hook run when unplugging from the network."
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 This can also be a list of regexp/day pairs.  The regexps will
77 be matched against group names."
78   :group 'gnus-agent
79   :type 'integer)
80
81 (defcustom gnus-agent-expire-all nil
82   "If non-nil, also expire unread, ticked and dormant articles.
83 If nil, only read articles will be expired."
84   :group 'gnus-agent
85   :type 'boolean)
86
87 (defcustom gnus-agent-group-mode-hook nil
88   "Hook run in Agent group minor modes."
89   :group 'gnus-agent
90   :type 'hook)
91
92 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
93 (when (featurep 'xemacs)
94   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
95
96 (defcustom gnus-agent-summary-mode-hook nil
97   "Hook run in Agent summary minor modes."
98   :group 'gnus-agent
99   :type 'hook)
100
101 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
102 (when (featurep 'xemacs)
103   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
104
105 (defcustom gnus-agent-server-mode-hook nil
106   "Hook run in Agent summary minor modes."
107   :group 'gnus-agent
108   :type 'hook)
109
110 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
111 (when (featurep 'xemacs)
112   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
113
114 (defcustom gnus-agent-confirmation-function 'y-or-n-p
115   "Function to confirm when error happens."
116   :version "21.1"
117   :group 'gnus-agent
118   :type 'function)
119
120 (defcustom gnus-agent-large-newsgroup nil
121   "*The number of articles which indicates a large newsgroup.
122 If the number of unread articles exceeds it, The number of articles to be
123 fetched will be limited to it. If not a positive integer, never consider it."
124   :group 'gnus-agent
125   :type '(choice (const nil)
126                  (integer :tag "Number")))
127
128 (defcustom gnus-agent-synchronize-flags 'ask
129   "Indicate if flags are synchronized when you plug in.
130 If this is `ask' the hook will query the user."
131   :version "21.1"
132   :type '(choice (const :tag "Always" t)
133                  (const :tag "Never" nil)
134                  (const :tag "Ask" ask))
135   :group 'gnus-agent)
136
137 (defcustom gnus-agent-go-online 'ask
138   "Indicate if offline servers go online when you plug in.
139 If this is `ask' the hook will query the user."
140   :version "21.1"
141   :type '(choice (const :tag "Always" t)
142                  (const :tag "Never" nil)
143                  (const :tag "Ask" ask))
144   :group 'gnus-agent)
145
146 (defcustom gnus-agent-mark-unread-after-downloaded t
147   "Indicate whether to mark articles unread after downloaded."
148   :version "21.1"
149   :type 'boolean
150   :group 'gnus-agent)
151
152 (defcustom gnus-agent-download-marks '(download)
153   "Marks for downloading."
154   :version "21.1"
155   :type '(repeat (symbol :tag "Mark"))
156   :group 'gnus-agent)
157
158 (defcustom gnus-agent-consider-all-articles nil
159   "If non-nil, consider also the read articles for downloading."
160   :version "21.4"
161   :type 'boolean
162   :group 'gnus-agent)
163
164 ;;; Internal variables
165
166 (defvar gnus-agent-history-buffers nil)
167 (defvar gnus-agent-buffer-alist nil)
168 (defvar gnus-agent-article-alist nil
169 "An assoc list identifying the articles whose headers have been fetched.  
170  If successfully fetched, these headers will be stored in the group's overview file.
171  The key of each assoc pair is the article ID.
172  The value of each assoc pair is a flag indicating 
173  whether the identified article has been downloaded (gnus-agent-fetch-articles
174  sets the value to the day of the download).
175  NOTES:
176  1) The last element of this list can not be expired as some 
177     routines (for example, get-agent-fetch-headers) use the last
178     value to track which articles have had their headers retrieved.
179  2) The gnus-agent-regenerate may destructively modify the value.
180 ")
181 (defvar gnus-agent-group-alist nil)
182 (defvar gnus-category-alist nil)
183 (defvar gnus-agent-current-history nil)
184 (defvar gnus-agent-overview-buffer nil)
185 (defvar gnus-category-predicate-cache nil)
186 (defvar gnus-category-group-cache nil)
187 (defvar gnus-agent-spam-hashtb nil)
188 (defvar gnus-agent-file-name nil)
189 (defvar gnus-agent-send-mail-function nil)
190 (defvar gnus-agent-file-coding-system 'raw-text)
191 (defvar gnus-agent-file-loading-cache nil)
192 (defvar gnus-agent-file-header-cache nil)
193
194 (defvar gnus-agent-auto-agentize-methods '(nntp nnimap)
195   "Initially, all servers from these methods are agentized.
196 The user may remove or add servers using the Server buffer.  See Info
197 node `(gnus)Server Buffer'.")
198
199 ;; Dynamic variables
200 (defvar gnus-headers)
201 (defvar gnus-score)
202
203 ;;;
204 ;;; Setup
205 ;;;
206
207 (defun gnus-open-agent ()
208   (setq gnus-agent t)
209   (gnus-agent-read-servers)
210   (gnus-category-read)
211   (gnus-agent-create-buffer)
212   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
213   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
214   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
215
216 (defun gnus-agent-create-buffer ()
217   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
218       t
219     (setq gnus-agent-overview-buffer
220           (gnus-get-buffer-create " *Gnus agent overview*"))
221     (with-current-buffer gnus-agent-overview-buffer
222       (set-buffer-multibyte t))
223     nil))
224
225 (gnus-add-shutdown 'gnus-close-agent 'gnus)
226
227 (defun gnus-close-agent ()
228   (setq gnus-agent-covered-methods nil
229         gnus-category-predicate-cache nil
230         gnus-category-group-cache nil
231         gnus-agent-spam-hashtb nil)
232   (gnus-kill-buffer gnus-agent-overview-buffer))
233
234 ;;;
235 ;;; Utility functions
236 ;;;
237
238 (defun gnus-agent-read-file (file)
239   "Load FILE and do a `read' there."
240   (with-temp-buffer
241     (ignore-errors
242       (nnheader-insert-file-contents file)
243       (goto-char (point-min))
244       (read (current-buffer)))))
245
246 (defsubst gnus-agent-method ()
247   (concat (symbol-name (car gnus-command-method)) "/"
248           (if (equal (cadr gnus-command-method) "")
249               "unnamed"
250             (cadr gnus-command-method))))
251
252 (defsubst gnus-agent-directory ()
253   "Path of the Gnus agent directory."
254   (nnheader-concat gnus-agent-directory
255                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
256
257 (defun gnus-agent-lib-file (file)
258   "The full path of the Gnus agent library FILE."
259   (expand-file-name file
260                     (file-name-as-directory
261                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
262
263 ;;; Fetching setup functions.
264
265 (defun gnus-agent-start-fetch ()
266   "Initialize data structures for efficient fetching."
267   (gnus-agent-create-buffer))
268
269 (defun gnus-agent-stop-fetch ()
270   "Save all data structures and clean up."
271   (setq gnus-agent-spam-hashtb nil)
272   (save-excursion
273     (set-buffer nntp-server-buffer)
274     (widen)))
275
276 (defmacro gnus-agent-with-fetch (&rest forms)
277   "Do FORMS safely."
278   `(unwind-protect
279        (let ((gnus-agent-fetching t))
280          (gnus-agent-start-fetch)
281          ,@forms)
282      (gnus-agent-stop-fetch)))
283
284 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
285 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
286
287 ;;;
288 ;;; Mode infestation
289 ;;;
290
291 (defvar gnus-agent-mode-hook nil
292   "Hook run when installing agent mode.")
293
294 (defvar gnus-agent-mode nil)
295 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
296
297 (defun gnus-agent-mode ()
298   "Minor mode for providing a agent support in Gnus buffers."
299   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
300                                       (symbol-name major-mode))
301                         (match-string 1 (symbol-name major-mode))))
302          (mode (intern (format "gnus-agent-%s-mode" buffer))))
303     (set (make-local-variable 'gnus-agent-mode) t)
304     (set mode nil)
305     (set (make-local-variable mode) t)
306     ;; Set up the menu.
307     (when (gnus-visual-p 'agent-menu 'menu)
308       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
309     (unless (assq 'gnus-agent-mode minor-mode-alist)
310       (push gnus-agent-mode-status minor-mode-alist))
311     (unless (assq mode minor-mode-map-alist)
312       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
313                                                      buffer))))
314             minor-mode-map-alist))
315     (when (eq major-mode 'gnus-group-mode)
316       (gnus-agent-toggle-plugged gnus-plugged))
317     (gnus-run-hooks 'gnus-agent-mode-hook
318                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
319
320 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
321 (gnus-define-keys gnus-agent-group-mode-map
322   "Ju" gnus-agent-fetch-groups
323   "Jc" gnus-enter-category-buffer
324   "Jj" gnus-agent-toggle-plugged
325   "Js" gnus-agent-fetch-session
326   "JY" gnus-agent-synchronize-flags
327   "JS" gnus-group-send-queue
328   "Ja" gnus-agent-add-group
329   "Jr" gnus-agent-remove-group
330   "Jo" gnus-agent-toggle-group-plugged)
331
332 (defun gnus-agent-group-make-menu-bar ()
333   (unless (boundp 'gnus-agent-group-menu)
334     (easy-menu-define
335      gnus-agent-group-menu gnus-agent-group-mode-map ""
336      '("Agent"
337        ["Toggle plugged" gnus-agent-toggle-plugged t]
338        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
339        ["List categories" gnus-enter-category-buffer t]
340        ["Send queue" gnus-group-send-queue gnus-plugged]
341        ("Fetch"
342         ["All" gnus-agent-fetch-session gnus-plugged]
343         ["Group" gnus-agent-fetch-group gnus-plugged])))))
344
345 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
346 (gnus-define-keys gnus-agent-summary-mode-map
347   "Jj" gnus-agent-toggle-plugged
348   "Ju" gnus-agent-summary-fetch-group
349   "Js" gnus-agent-summary-fetch-series
350   "J#" gnus-agent-mark-article
351   "J\M-#" gnus-agent-unmark-article
352   "@" gnus-agent-toggle-mark
353   "Jc" gnus-agent-catchup)
354
355 (defun gnus-agent-summary-make-menu-bar ()
356   (unless (boundp 'gnus-agent-summary-menu)
357     (easy-menu-define
358      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
359      '("Agent"
360        ["Toggle plugged" gnus-agent-toggle-plugged t]
361        ["Mark as downloadable" gnus-agent-mark-article t]
362        ["Unmark as downloadable" gnus-agent-unmark-article t]
363        ["Toggle mark" gnus-agent-toggle-mark t]
364        ["Fetch downloadable" gnus-agent-summary-fetch-group t]
365        ["Catchup undownloaded" gnus-agent-catchup t]))))
366
367 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
368 (gnus-define-keys gnus-agent-server-mode-map
369   "Jj" gnus-agent-toggle-plugged
370   "Ja" gnus-agent-add-server
371   "Jr" gnus-agent-remove-server)
372
373 (defun gnus-agent-server-make-menu-bar ()
374   (unless (boundp 'gnus-agent-server-menu)
375     (easy-menu-define
376      gnus-agent-server-menu gnus-agent-server-mode-map ""
377      '("Agent"
378        ["Toggle plugged" gnus-agent-toggle-plugged t]
379        ["Add" gnus-agent-add-server t]
380        ["Remove" gnus-agent-remove-server t]))))
381
382 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
383   (if (and (fboundp 'propertize)
384            (fboundp 'make-mode-line-mouse-map))
385       (propertize string 'local-map
386                   (make-mode-line-mouse-map mouse-button mouse-func))
387     string))
388
389 (defun gnus-agent-toggle-plugged (plugged)
390   "Toggle whether Gnus is unplugged or not."
391   (interactive (list (not gnus-plugged)))
392   (if plugged
393       (progn
394         (setq gnus-plugged plugged)
395         (gnus-run-hooks 'gnus-agent-plugged-hook)
396         (setcar (cdr gnus-agent-mode-status)
397                 (gnus-agent-make-mode-line-string " Plugged"
398                                                   'mouse-2
399                                                   'gnus-agent-toggle-plugged))
400         (gnus-agent-go-online gnus-agent-go-online)
401         (gnus-agent-possibly-synchronize-flags))
402     (gnus-agent-close-connections)
403     (setq gnus-plugged plugged)
404     (gnus-run-hooks 'gnus-agent-unplugged-hook)
405     (setcar (cdr gnus-agent-mode-status)
406             (gnus-agent-make-mode-line-string " Unplugged"
407                                               'mouse-2
408                                               'gnus-agent-toggle-plugged)))
409   (force-mode-line-update)
410   (set-buffer-modified-p t))
411
412 (defun gnus-agent-close-connections ()
413   "Close all methods covered by the Gnus agent."
414   (let ((methods gnus-agent-covered-methods))
415     (while methods
416       (gnus-close-server (pop methods)))))
417
418 ;;;###autoload
419 (defun gnus-unplugged ()
420   "Start Gnus unplugged."
421   (interactive)
422   (setq gnus-plugged nil)
423   (gnus))
424
425 ;;;###autoload
426 (defun gnus-plugged ()
427   "Start Gnus plugged."
428   (interactive)
429   (setq gnus-plugged t)
430   (gnus))
431
432 ;;;###autoload
433 (defun gnus-slave-unplugged (&optional arg)
434   "Read news as a slave unplugged."
435   (interactive "P")
436   (setq gnus-plugged nil)
437   (gnus arg nil 'slave))
438
439 ;;;###autoload
440 (defun gnus-agentize ()
441   "Allow Gnus to be an offline newsreader.
442 The normal usage of this command is to put the following as the
443 last form in your `.gnus.el' file:
444
445 \(gnus-agentize)
446
447 This will modify the `gnus-setup-news-hook', and
448 `message-send-mail-real-function' variables, and install the Gnus agent
449 minor mode in all Gnus buffers."
450   (interactive)
451   (gnus-open-agent)
452   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
453   (unless gnus-agent-send-mail-function
454     (setq gnus-agent-send-mail-function (or
455                                          message-send-mail-real-function
456                                          message-send-mail-function)
457           message-send-mail-real-function 'gnus-agent-send-mail))
458   (unless gnus-agent-covered-methods
459     (mapcar
460      (lambda (server)
461        (if (memq (car (gnus-server-to-method server)) 
462                  gnus-agent-auto-agentize-methods)
463            (setq gnus-agent-covered-methods 
464                  (cons (gnus-server-to-method server)
465                        gnus-agent-covered-methods ))))
466      (append (list gnus-select-method) gnus-secondary-select-methods))))
467
468 (defun gnus-agent-queue-setup ()
469   "Make sure the queue group exists."
470   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
471     (gnus-request-create-group "queue" '(nndraft ""))
472     (let ((gnus-level-default-subscribed 1))
473       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
474     (gnus-group-set-parameter
475      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
476
477 (defun gnus-agent-send-mail ()
478   (if gnus-plugged
479       (funcall gnus-agent-send-mail-function)
480     (goto-char (point-min))
481     (re-search-forward
482      (concat "^" (regexp-quote mail-header-separator) "\n"))
483     (replace-match "\n")
484     (gnus-agent-insert-meta-information 'mail)
485     (gnus-request-accept-article "nndraft:queue" nil t t)))
486
487 (defun gnus-agent-insert-meta-information (type &optional method)
488   "Insert meta-information into the message that says how it's to be posted.
489 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
490 be a select method."
491   (save-excursion
492     (message-remove-header gnus-agent-meta-information-header)
493     (goto-char (point-min))
494     (insert gnus-agent-meta-information-header ": "
495             (symbol-name type) " " (format "%S" method)
496             "\n")
497     (forward-char -1)
498     (while (search-backward "\n" nil t)
499       (replace-match "\\n" t t))))
500
501 (defun gnus-agent-restore-gcc ()
502   "Restore GCC field from saved header."
503   (save-excursion
504     (goto-char (point-min))
505     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
506       (replace-match "Gcc:" 'fixedcase))))
507
508 (defun gnus-agent-any-covered-gcc ()
509   (save-restriction
510     (message-narrow-to-headers)
511     (let* ((gcc (mail-fetch-field "gcc" nil t))
512            (methods (and gcc
513                          (mapcar 'gnus-inews-group-method
514                                  (message-unquote-tokens
515                                   (message-tokenize-header
516                                    gcc " ,")))))
517            covered)
518       (while (and (not covered) methods)
519         (setq covered (gnus-agent-method-p (car methods))
520               methods (cdr methods)))
521       covered)))
522
523 ;;;###autoload
524 (defun gnus-agent-possibly-save-gcc ()
525   "Save GCC if Gnus is unplugged."
526   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
527     (save-excursion
528       (goto-char (point-min))
529       (let ((case-fold-search t))
530         (while (re-search-forward "^gcc:" nil t)
531           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
532
533 (defun gnus-agent-possibly-do-gcc ()
534   "Do GCC if Gnus is plugged."
535   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
536     (gnus-inews-do-gcc)))
537
538 ;;;
539 ;;; Group mode commands
540 ;;;
541
542 (defun gnus-agent-fetch-groups (n)
543   "Put all new articles in the current groups into the Agent."
544   (interactive "P")
545   (unless gnus-plugged
546     (error "Groups can't be fetched when Gnus is unplugged"))
547   (gnus-group-iterate n 'gnus-agent-fetch-group))
548
549 (defun gnus-agent-fetch-group (group)
550   "Put all new articles in GROUP into the Agent."
551   (interactive (list (gnus-group-group-name)))
552   (let ((state gnus-plugged))
553     (unwind-protect
554         (progn
555           (unless group
556             (error "No group on the current line"))
557           (unless state
558             (gnus-agent-toggle-plugged gnus-plugged))
559           (let ((gnus-command-method (gnus-find-method-for-group group)))
560             (gnus-agent-with-fetch
561               (gnus-agent-fetch-group-1 group gnus-command-method)
562               (gnus-message 5 "Fetching %s...done" group))))
563       (when (and (not state)
564                  gnus-plugged)
565         (gnus-agent-toggle-plugged gnus-plugged)))))
566
567 (defun gnus-agent-add-group (category arg)
568   "Add the current group to an agent category."
569   (interactive
570    (list
571     (intern
572      (completing-read
573       "Add to category: "
574       (mapcar (lambda (cat) (list (symbol-name (car cat))))
575               gnus-category-alist)
576       nil t))
577     current-prefix-arg))
578   (let ((cat (assq category gnus-category-alist))
579         c groups)
580     (gnus-group-iterate arg
581       (lambda (group)
582         (when (cadddr (setq c (gnus-group-category group)))
583           (setf (cadddr c) (delete group (cadddr c))))
584         (push group groups)))
585     (setf (cadddr cat) (nconc (cadddr cat) groups))
586     (gnus-category-write)))
587
588 (defun gnus-agent-remove-group (arg)
589   "Remove the current group from its agent category, if any."
590   (interactive "P")
591   (let (c)
592     (gnus-group-iterate arg
593       (lambda (group)
594         (when (cadddr (setq c (gnus-group-category group)))
595           (setf (cadddr c) (delete group (cadddr c))))))
596     (gnus-category-write)))
597
598 (defun gnus-agent-synchronize-flags ()
599   "Synchronize unplugged flags with servers."
600   (interactive)
601   (save-excursion
602     (dolist (gnus-command-method gnus-agent-covered-methods)
603       (when (file-exists-p (gnus-agent-lib-file "flags"))
604         (gnus-agent-synchronize-flags-server gnus-command-method)))))
605
606 (defun gnus-agent-possibly-synchronize-flags ()
607   "Synchronize flags according to `gnus-agent-synchronize-flags'."
608   (interactive)
609   (save-excursion
610     (dolist (gnus-command-method gnus-agent-covered-methods)
611       (when (file-exists-p (gnus-agent-lib-file "flags"))
612         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
613
614 (defun gnus-agent-synchronize-flags-server (method)
615   "Synchronize flags set when unplugged for server."
616   (let ((gnus-command-method method))
617     (when (file-exists-p (gnus-agent-lib-file "flags"))
618       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
619       (erase-buffer)
620       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
621       (if (null (gnus-check-server gnus-command-method))
622           (gnus-message 1 "Couldn't open server %s" (nth 1 gnus-command-method))
623         (while (not (eobp))
624           (if (null (eval (read (current-buffer))))
625               (progn (forward-line)
626                      (kill-line -1))
627             (write-file (gnus-agent-lib-file "flags"))
628             (error "Couldn't set flags from file %s"
629                    (gnus-agent-lib-file "flags"))))
630         (delete-file (gnus-agent-lib-file "flags")))
631       (kill-buffer nil))))
632
633 (defun gnus-agent-possibly-synchronize-flags-server (method)
634   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
635   (when (or (and gnus-agent-synchronize-flags
636                  (not (eq gnus-agent-synchronize-flags 'ask)))
637             (and (eq gnus-agent-synchronize-flags 'ask)
638                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
639                                         (cadr method)))))
640     (gnus-agent-synchronize-flags-server method)))
641
642 ;;;
643 ;;; Server mode commands
644 ;;;
645
646 (defun gnus-agent-add-server (server)
647   "Enroll SERVER in the agent program."
648   (interactive (list (gnus-server-server-name)))
649   (unless server
650     (error "No server on the current line"))
651   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
652     (when (gnus-agent-method-p method)
653       (error "Server already in the agent program"))
654     (push method gnus-agent-covered-methods)
655     (gnus-server-update-server server)
656     (gnus-agent-write-servers)
657     (gnus-message 1 "Entered %s into the Agent" server)))
658
659 (defun gnus-agent-remove-server (server)
660   "Remove SERVER from the agent program."
661   (interactive (list (gnus-server-server-name)))
662   (unless server
663     (error "No server on the current line"))
664   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
665     (unless (gnus-agent-method-p method)
666       (error "Server not in the agent program"))
667     (setq gnus-agent-covered-methods
668           (delete method gnus-agent-covered-methods))
669     (gnus-server-update-server server)
670     (gnus-agent-write-servers)
671     (gnus-message 1 "Removed %s from the agent" server)))
672
673 (defun gnus-agent-read-servers ()
674   "Read the alist of covered servers."
675   (mapcar (lambda (m)
676             (let ((method (gnus-server-get-method
677                            nil
678                            (or m "native"))))
679               (if method
680                   (unless (member method gnus-agent-covered-methods)
681                     (push method gnus-agent-covered-methods))
682                 (gnus-message 1 "Ignoring disappeared server `%s'" m)
683                 (sit-for 1))))
684           (gnus-agent-read-file
685            (nnheader-concat gnus-agent-directory "lib/methods"))))
686
687 (defun gnus-agent-write-servers ()
688   "Write the alist of covered servers."
689   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
690   (let ((coding-system-for-write nnheader-file-coding-system)
691         (output-coding-system nnheader-file-coding-system)
692         (file-name-coding-system nnmail-pathname-coding-system)
693         (pathname-coding-system nnmail-pathname-coding-system))
694     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
695       (prin1 (mapcar 'gnus-method-simplify gnus-agent-covered-methods)
696              (current-buffer)))))
697
698 ;;;
699 ;;; Summary commands
700 ;;;
701
702 (defun gnus-agent-mark-article (n &optional unmark)
703   "Mark the next N articles as downloadable.
704 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
705 the mark instead.  The difference between N and the actual number of
706 articles marked is returned."
707   (interactive "p")
708   (let ((backward (< n 0))
709         (n (abs n)))
710     (while (and
711             (> n 0)
712             (progn
713               (gnus-summary-set-agent-mark
714                (gnus-summary-article-number) unmark)
715               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
716       (setq n (1- n)))
717     (when (/= 0 n)
718       (gnus-message 7 "No more articles"))
719     (gnus-summary-recenter)
720     (gnus-summary-position-point)
721     n))
722
723 (defun gnus-agent-unmark-article (n)
724   "Remove the downloadable mark from the next N articles.
725 If N is negative, unmark backward instead.  The difference between N and
726 the actual number of articles unmarked is returned."
727   (interactive "p")
728   (gnus-agent-mark-article n t))
729
730 (defun gnus-agent-toggle-mark (n)
731   "Toggle the downloadable mark from the next N articles.
732 If N is negative, toggle backward instead.  The difference between N and
733 the actual number of articles toggled is returned."
734   (interactive "p")
735   (gnus-agent-mark-article n 'toggle))
736
737 (defun gnus-summary-set-agent-mark (article &optional unmark)
738   "Mark ARTICLE as downloadable."
739   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
740                     (memq article gnus-newsgroup-downloadable)
741                   unmark))
742         (new-mark gnus-downloadable-mark))
743     (if unmark
744         (let ((agent-articles gnus-agent-article-alist))
745           (setq gnus-newsgroup-downloadable
746                 (delq article gnus-newsgroup-downloadable))
747           (while (and agent-articles (< (caar agent-articles) article))
748             (setq agent-articles (cdr agent-articles)))
749           (if (and (eq (caar agent-articles) article)
750                    (cdar agent-articles))
751               (setq new-mark 32)
752             (progn (setq new-mark gnus-undownloaded-mark)
753                    (push article gnus-newsgroup-undownloaded))))
754       (setq gnus-newsgroup-undownloaded
755             (delq article gnus-newsgroup-undownloaded))
756       (setq gnus-newsgroup-downloadable
757             (gnus-add-to-sorted-list gnus-newsgroup-downloadable article)))
758     (gnus-summary-update-mark
759      new-mark
760      'unread)))
761
762 ;; Check history - this may make sense if the agent is configured to pre-fetch every article.
763 (defun gnus-agent-get-undownloaded-list ()
764   "Mark all unfetched articles as read."
765   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
766     (when (and 
767            (not (gnus-online gnus-command-method))
768            (gnus-agent-method-p gnus-command-method))
769       (gnus-agent-load-alist gnus-newsgroup-name)
770       ;; First mark all undownloaded articles as undownloaded.
771       ;; CCC kaig: Maybe change here to consider all headers.
772       (let ((articles (delq nil (mapcar (lambda (header) (if (equal (mail-header-from header) "Gnus Agent")
773                                                              nil
774                                                            (mail-header-number header)))
775                                         gnus-newsgroup-headers)))
776             (agent-articles gnus-agent-article-alist)
777             candidates article)
778         (while (setq article (pop articles))
779           (while (and agent-articles
780                       (< (caar agent-articles) article))
781             (setq agent-articles (cdr agent-articles)))
782           (when (or (not (cdar agent-articles))
783                     (not (= (caar agent-articles) article)))
784             (push article candidates)))
785         (dolist (article candidates)
786           (unless (or (memq article gnus-newsgroup-downloadable)
787                       (memq article gnus-newsgroup-cached))
788             (push article gnus-newsgroup-undownloaded))))
789       ;; Then mark downloaded downloadable as not-downloadable,
790       ;; if you get my drift.
791       (dolist (article gnus-newsgroup-downloadable)
792         (when (cdr (assq article gnus-agent-article-alist))
793           (setq gnus-newsgroup-downloadable
794                 (delq article gnus-newsgroup-downloadable)))))))
795
796 (defun gnus-agent-catchup ()
797   "Mark all undownloaded articles as read."
798   (interactive)
799   (save-excursion
800     (while gnus-newsgroup-undownloaded
801       (gnus-summary-mark-article
802        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
803   (gnus-summary-position-point))
804
805 (defun gnus-agent-summary-fetch-series ()
806   (interactive)
807   (let ((dl gnus-newsgroup-downloadable))
808     (while gnus-newsgroup-processable
809       (let* ((art (car (last gnus-newsgroup-processable)))
810              (gnus-newsgroup-downloadable (list art)))
811         (gnus-summary-goto-subject art)
812         (sit-for 0)
813         (gnus-agent-summary-fetch-group)
814         (setq dl (delq art dl))
815         (gnus-summary-remove-process-mark art)
816         (sit-for 0)))
817     (setq gnus-newsgroup-downloadable dl)))
818
819 (defun gnus-agent-summary-fetch-group (&optional all)
820   "Fetch the downloadable articles in the group.
821 Optional arg ALL, if non-nil, means to fetch all articles."
822   (interactive "P")
823   (let ((articles
824          (if all gnus-newsgroup-articles
825            gnus-newsgroup-downloadable))
826         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
827         (state gnus-plugged))
828     (unwind-protect
829         (progn
830           (unless state
831             (gnus-agent-toggle-plugged t))
832           (unless articles
833             (error "No articles to download"))
834           (gnus-agent-with-fetch
835             (gnus-agent-fetch-articles gnus-newsgroup-name articles))
836           (save-excursion
837             (dolist (article articles)
838               (setq gnus-newsgroup-downloadable
839                     (delq article gnus-newsgroup-downloadable))
840               (if gnus-agent-mark-unread-after-downloaded
841                   (gnus-summary-mark-article article gnus-unread-mark)))))
842       (when (and (not state)
843                  gnus-plugged)
844         (gnus-agent-toggle-plugged nil)))))
845
846 (defun gnus-agent-fetch-selected-article ()
847   "Fetch the current article as it is selected.
848 This can be added to `gnus-select-article-hook' or
849 `gnus-mark-article-hook'."
850   (let ((gnus-command-method gnus-current-select-method))
851     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
852       (gnus-agent-fetch-articles
853        gnus-newsgroup-name
854        (list gnus-current-article)))))
855
856 ;;;
857 ;;; Internal functions
858 ;;;
859
860 (defun gnus-agent-save-active (method)
861   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
862
863 (defun gnus-agent-save-active-1 (method function)
864   (when (gnus-agent-method-p method)
865     (let* ((gnus-command-method method)
866            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
867            (file (gnus-agent-lib-file "active")))
868       (funcall function nil new)
869       (gnus-agent-write-active file new)
870       (erase-buffer)
871       (nnheader-insert-file-contents file))))
872
873 (defun gnus-agent-write-active (file new)
874   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
875         (file (gnus-agent-lib-file "active"))
876         elem osym)
877     (when (file-exists-p file)
878       (with-temp-buffer
879         (nnheader-insert-file-contents file)
880         (gnus-active-to-gnus-format nil orig))
881       (mapatoms
882        (lambda (sym)
883          (when (and sym (boundp sym))
884            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
885                     (setq elem (symbol-value osym)))
886                (progn
887                  (if (and (integerp (car (symbol-value sym)))
888                           (> (car elem) (car (symbol-value sym))))
889                      (setcar elem (car (symbol-value sym))))
890                  (if (integerp (cdr (symbol-value sym)))
891                      (setcdr elem (cdr (symbol-value sym)))))
892              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
893        new))
894     (gnus-make-directory (file-name-directory file))
895     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
896       ;; The hashtable contains real names of groups,  no more prefix
897       ;; removing, so set `full' to `t'.
898       (gnus-write-active-file file orig t))))
899
900 (defun gnus-agent-save-groups (method)
901   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
902
903 (defun gnus-agent-save-group-info (method group active)
904   (when (gnus-agent-method-p method)
905     (let* ((gnus-command-method method)
906            (coding-system-for-write nnheader-file-coding-system)
907            (output-coding-system nnheader-file-coding-system)
908            (file-name-coding-system nnmail-pathname-coding-system)
909            (pathname-coding-system nnmail-pathname-coding-system)
910            (file (gnus-agent-lib-file "active"))
911            oactive-min)
912       (gnus-make-directory (file-name-directory file))
913       (with-temp-file file
914         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
915         (set-buffer-multibyte nil)
916         (when (file-exists-p file)
917           (nnheader-insert-file-contents file))
918         (goto-char (point-min))
919         (when (re-search-forward
920                (concat "^" (regexp-quote group) " ") nil t)
921           (save-excursion
922             (read (current-buffer))                      ;; max
923             (setq oactive-min (read (current-buffer))))  ;; min
924           (gnus-delete-line))
925         (insert (format "%S %d %d y\n" (intern group)
926                         (cdr active)
927                         (or oactive-min (car active))))
928         (goto-char (point-max))
929         (while (search-backward "\\." nil t)
930           (delete-char 1))))))
931
932 (defun gnus-agent-group-path (group)
933   "Translate GROUP into a path."
934   (if nnmail-use-long-file-names
935       (gnus-group-real-name group)
936     (nnheader-translate-file-chars
937      (nnheader-replace-chars-in-string
938       (nnheader-replace-duplicate-chars-in-string
939        (nnheader-replace-chars-in-string
940         (gnus-group-real-name group)
941         ?/ ?_)
942        ?. ?_)
943       ?. ?/))))
944
945 \f
946
947 (defun gnus-agent-get-function (method)
948   (if (gnus-online method)
949       (car method)
950     (require 'nnagent)
951     'nnagent))
952
953 ;;; History functions
954
955 (defun gnus-agent-history-buffer ()
956   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
957
958 (defun gnus-agent-open-history ()
959   (save-excursion
960     (push (cons (gnus-agent-method)
961                 (set-buffer (gnus-get-buffer-create
962                              (format " *Gnus agent %s history*"
963                                      (gnus-agent-method)))))
964           gnus-agent-history-buffers)
965     (set-buffer-multibyte nil) ;; everything is binary
966     (erase-buffer)
967     (insert "\n")
968     (let ((file (gnus-agent-lib-file "history")))
969       (when (file-exists-p file)
970         (nnheader-insert-file-contents file))
971       (set (make-local-variable 'gnus-agent-file-name) file))))
972
973 (defun gnus-agent-close-history ()
974   (when (gnus-buffer-live-p gnus-agent-current-history)
975     (kill-buffer gnus-agent-current-history)
976     (setq gnus-agent-history-buffers
977           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
978                 gnus-agent-history-buffers))))
979
980 ;;;
981 ;;; Fetching
982 ;;;
983
984 (defun gnus-agent-fetch-articles (group articles)
985   "Fetch ARTICLES from GROUP and put them into the Agent."
986   (gnus-agent-load-alist group)
987   (when articles
988     ;; Prune off articles that we have already fetched.
989     (while (and articles
990                 (cdr (assq (car articles) gnus-agent-article-alist)))
991       (pop articles))
992     (let ((arts articles))
993       (while (cdr arts)
994         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
995             (setcdr arts (cddr arts))
996           (setq arts (cdr arts)))))
997     (when articles
998       (let ((dir (concat
999                   (gnus-agent-directory)
1000                   (gnus-agent-group-path group) "/"))
1001             (date (time-to-days (current-time)))
1002             (case-fold-search t)
1003             pos crosses id elem)
1004         (gnus-make-directory dir)
1005         (gnus-message 7 "Fetching articles for %s..." group)
1006         ;; Fetch the articles from the backend.
1007         (if (gnus-check-backend-function 'retrieve-articles group)
1008             (setq pos (gnus-retrieve-articles articles group))
1009           (with-temp-buffer
1010             (let (article)
1011               (while (setq article (pop articles))
1012                 (gnus-message 10 "Fetching article %s for %s..."
1013                               article group)
1014                 (when (or
1015                        (gnus-backlog-request-article group article
1016                                                      nntp-server-buffer)
1017                        (gnus-request-article article group))
1018                   (goto-char (point-max))
1019                   (push (cons article (point)) pos)
1020                   (insert-buffer-substring nntp-server-buffer)))
1021               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
1022               (setq pos (nreverse pos)))))
1023         ;; Then save these articles into the Agent.
1024         (save-excursion
1025           (set-buffer nntp-server-buffer)
1026           (while pos
1027             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1028             (goto-char (point-min))
1029             (unless (eobp)  ;; Don't save empty articles.
1030               (when (search-forward "\n\n" nil t)
1031                 (when (search-backward "\nXrefs: " nil t)
1032                   ;; Handle cross posting.
1033                   (goto-char (match-end 0)) ; move to end of header name
1034                   (skip-chars-forward "^ ") ; skip server name
1035                   (skip-chars-forward " ")
1036                   (setq crosses nil)
1037                   (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1038                     (push (cons (buffer-substring (match-beginning 1)
1039                                                   (match-end 1))
1040                                 (string-to-int (buffer-substring (match-beginning 2)
1041                                                                  (match-end 2))))
1042                           crosses)
1043                     (goto-char (match-end 0)))
1044                   (gnus-agent-crosspost crosses (caar pos) date)))
1045               (goto-char (point-min))
1046               (if (not (re-search-forward
1047                         "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1048                   (setq id "No-Message-ID-in-article")
1049                 (setq id (buffer-substring (match-beginning 1) (match-end 1))))
1050               (write-region-as-coding-system
1051                gnus-agent-file-coding-system (point-min) (point-max)
1052                (concat dir (number-to-string (caar pos))) nil 'silent)
1053               (when (setq elem (assq (caar pos) gnus-agent-article-alist))
1054                 (setcdr elem date)))
1055             (widen)
1056             (pop pos)))
1057         (gnus-agent-save-alist group)))))
1058
1059 (defun gnus-agent-crosspost (crosses article &optional date)
1060   (setq date (or date t))
1061
1062   (let (gnus-agent-article-alist group alist beg end)
1063     (save-excursion
1064       (set-buffer gnus-agent-overview-buffer)
1065       (when (nnheader-find-nov-line article)
1066         (forward-word 1)
1067         (setq beg (point))
1068         (setq end (progn (forward-line 1) (point)))))
1069     (while crosses
1070       (setq group (caar crosses))
1071       (unless (setq alist (assoc group gnus-agent-group-alist))
1072         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1073               gnus-agent-group-alist))
1074       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1075       (save-excursion
1076         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1077                                                     group)))
1078         (when (= (point-max) (point-min))
1079           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1080           (ignore-errors
1081             (nnheader-insert-file-contents
1082              (gnus-agent-article-name ".overview" group))))
1083         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1084         (insert (string-to-number (cdar crosses)))
1085         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1086         (gnus-agent-check-overview-buffer))
1087       (pop crosses))))
1088
1089 (defun gnus-agent-check-overview-buffer (&optional buffer)
1090   "Check the overview file given for sanity.
1091 In particular, checks that the file is sorted by article number
1092 and that there are no duplicates."
1093   (let (prev-num)
1094     (save-excursion
1095       (when buffer (set-buffer buffer))
1096       (save-excursion
1097         (save-restriction
1098           (let ((deactivate-mark (if (boundp 'deactivate-mark)
1099                                      (symbol-value 'deactivate-mark)
1100                                    nil)))
1101             (widen)
1102             (goto-char (point-min))
1103             (setq prev-num (number-at-point))
1104             (while (and (zerop (forward-line 1))
1105                         (not (eobp)))
1106               (let ((cur (number-at-point)))
1107                 (cond ((= cur prev-num)
1108                        (gnus-message 10
1109                                      "Duplicate overview line for %d" cur)
1110                        (debug nil (format "Duplicate overview line for %d" cur))
1111                        (delete-region (point) (progn (forward-line 1) (point))))
1112                       ((< cur prev-num)
1113                        (gnus-message 10 "Overview buffer not sorted!")
1114                        (debug nil "Overview buffer not sorted!"))))
1115               (setq prev-num (number-at-point)))))))))
1116
1117
1118 (defun gnus-agent-flush-cache ()
1119   (save-excursion
1120     (while gnus-agent-buffer-alist
1121       (set-buffer (cdar gnus-agent-buffer-alist))
1122       (write-region-as-coding-system
1123        gnus-agent-file-coding-system
1124        (point-min) (point-max)
1125        (gnus-agent-article-name ".overview"
1126                                 (caar gnus-agent-buffer-alist))
1127        nil 'silent)
1128       (pop gnus-agent-buffer-alist))
1129     (while gnus-agent-group-alist
1130       (with-temp-file (gnus-agent-article-name ".agentview" (caar gnus-agent-group-alist))
1131         (princ (cdar gnus-agent-group-alist))
1132         (insert "\n")
1133         (princ 1 (current-buffer))
1134         (insert "\n"))
1135       (pop gnus-agent-group-alist))))
1136
1137 (defun gnus-agent-fetch-headers (group &optional force)
1138   (let* ((fetch-all (and gnus-agent-consider-all-articles
1139                          ;; Do not fetch all headers if the predicate
1140                          ;; implies that we only consider unread articles.
1141                          (not (gnus-predicate-implies-unread
1142                                (or (gnus-group-find-parameter
1143                                     group 'agent-predicate t)
1144                                    (cadr (gnus-group-category group)))))))
1145          (articles (if fetch-all
1146                        (gnus-uncompress-range (gnus-active group))
1147                      (gnus-list-of-unread-articles group)))
1148          (gnus-decode-encoded-word-function 'identity)
1149          (file (gnus-agent-article-name ".overview" group))
1150          gnus-agent-cache)
1151     ;; Check whether the number of articles is not too large.
1152     (when (and (integerp gnus-agent-large-newsgroup)
1153                (> gnus-agent-large-newsgroup 0))
1154       (setq articles (nthcdr (max (- (length articles)
1155                                      gnus-agent-large-newsgroup)
1156                                   0)
1157                              articles)))
1158     (unless fetch-all
1159       ;; Add articles with marks to the list of article headers we want to
1160       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1161       ;; mark, but do fetch recent or seen articles if they have other, more
1162       ;; interesting marks.  (We have to fetch articles with boring marks
1163       ;; because otherwise the agent will remove their marks.)
1164       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1165         (unless (memq (car arts) '(seen recent))
1166           (setq articles (gnus-range-add articles (cdr arts)))))
1167       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1168
1169     ;; At this point, I have the list of articles to consider for fetching.  
1170     ;; This is the list that I'll return to my caller. Some of these articles may have already 
1171     ;; been fetched.  That's OK as the fetch article code will filter those out.
1172     ;; Internally, I'll filter this list to just those articles whose headers need to be fetched.
1173     (let ((articles articles))
1174       ;; Remove known articles.
1175       (when (gnus-agent-load-alist group)
1176         ;; Remove articles marked as downloaded.
1177         (if fetch-all
1178             ;; I want to fetch all headers in the active range.  
1179             ;; Therefore, exclude only those headers that are in the article alist.
1180             ;; NOTE: This is probably NOT what I want to do after agent expiration in this group.
1181             (setq articles (gnus-agent-uncached-articles articles group))
1182
1183           ;; I want to only fetch those headers that have never been fetched. 
1184           ;; Therefore, exclude all headers that are, or WERE, in the article alist.
1185           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1186                 (high (cdr (gnus-active group))))
1187             ;; Low can be greater than High when the same group is fetched twice
1188             ;; in the same session {The first fetch will fill the article alist 
1189             ;; such that (last gnus-agent-article-alist) equals (cdr (gnus-active group))}.  
1190             ;; The addition of one(the 1+ above) then forces Low to be greater than High.  
1191             ;; When this happens, gnus-list-range-intersection returns nil which indicates 
1192             ;; that no headers need to be fetched. -- Kevin
1193             (setq articles (gnus-list-range-intersection
1194                             articles (list (cons low high)))))))
1195       (when articles
1196         (gnus-message 7 "Fetching headers for %s..." group)
1197
1198         ;; Fetch them.
1199         (gnus-make-directory (nnheader-translate-file-chars
1200                               (file-name-directory file) t))
1201
1202         (save-excursion
1203           (set-buffer nntp-server-buffer)
1204           (unless (eq 'nov (gnus-retrieve-headers articles group))
1205             (nnvirtual-convert-headers))
1206           (gnus-agent-check-overview-buffer)
1207           ;; Move these headers to the overview buffer so that gnus-agent-brand-nov can merge them
1208           ;; with the contents of FILE.
1209           (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1210           (when (file-exists-p file)
1211             (gnus-agent-braid-nov group articles file))
1212           (gnus-agent-check-overview-buffer)
1213           (write-region-as-coding-system
1214            gnus-agent-file-coding-system
1215            (1+ (point-min)) (point-max) file nil 'silent)
1216           (gnus-agent-save-alist group articles nil)
1217           articles)))
1218     articles))
1219
1220 (defsubst gnus-agent-copy-nov-line (article)
1221   (let (art b e)
1222     (set-buffer gnus-agent-overview-buffer)
1223     (while (and (not (eobp))
1224                 (< (setq art (read (current-buffer))) article))
1225       (forward-line 1))
1226     (beginning-of-line)
1227     (if (or (eobp)
1228             (not (eq article art)))
1229         (set-buffer nntp-server-buffer)
1230       (setq b (point))
1231       (setq e (progn (forward-line 1) (point)))
1232       (set-buffer nntp-server-buffer)
1233       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1234
1235 (defun gnus-agent-braid-nov (group articles file)
1236   "Merges the article headers identified by ARTICLES from gnus-agent-overview-buffer with the contents
1237 of FILE placing the combined headers in nntp-server-buffer."
1238   (let (start last)
1239     (set-buffer gnus-agent-overview-buffer)
1240     (goto-char (point-min))
1241     (set-buffer nntp-server-buffer)
1242     (erase-buffer)
1243     (nnheader-insert-file-contents file)
1244     (goto-char (point-max))
1245     (forward-line -1)
1246     (unless (looking-at "[0-9]+\t")
1247       ;; Remove corrupted lines
1248       (gnus-message 1 "Overview %s is corrupted. Removing corrupted lines..." file)
1249       (goto-char (point-min))
1250       (while (not (eobp))
1251         (if (looking-at "[0-9]+\t")
1252             (forward-line 1)
1253           (delete-region (point) (progn (forward-line 1) (point)))))
1254       (forward-line -1))
1255     (unless (or (= (point-min) (point-max))
1256                 (< (setq last (read (current-buffer))) (car articles)))
1257       ;; We do it the hard way.
1258       (when (nnheader-find-nov-line (car articles))
1259         ;; Replacing existing NOV entry
1260         (delete-region (point) (progn (forward-line 1) (point))))
1261       (gnus-agent-copy-nov-line (pop articles))
1262
1263       (ignore-errors
1264         (while articles
1265           (while (let ((art (read (current-buffer))))
1266                    (cond ((< art (car articles))
1267                           (forward-line 1)
1268                           t)
1269                          ((= art (car articles))
1270                           (beginning-of-line)
1271                           (delete-region (point) (progn (forward-line 1) (point)))
1272                           nil)
1273                          (t
1274                           (beginning-of-line)
1275                           nil))))
1276             
1277           (gnus-agent-copy-nov-line (pop articles)))))
1278
1279     ;; Copy the rest lines
1280     (set-buffer nntp-server-buffer)
1281     (goto-char (point-max))
1282     (when articles
1283       (when last
1284         (set-buffer gnus-agent-overview-buffer)
1285         (ignore-errors
1286           (while (<= (read (current-buffer)) last)
1287             (forward-line 1)))
1288         (beginning-of-line)
1289         (setq start (point))
1290         (set-buffer nntp-server-buffer))
1291       (insert-buffer-substring gnus-agent-overview-buffer start))))
1292
1293 (eval-when-compile ; Keeps the compiler from warning about the free variable in gnus-agent-read-agentview
1294   (defvar gnus-agent-read-agentview))
1295
1296 (defun gnus-agent-load-alist (group)
1297   (let ((gnus-agent-read-agentview group)) ; Binds free variable that's used in gnus-agent-read-agentview
1298     "Load the article-state alist for GROUP."
1299     (setq gnus-agent-article-alist
1300           (gnus-cache-file-contents
1301            (gnus-agent-article-name ".agentview" group)
1302            'gnus-agent-file-loading-cache
1303            'gnus-agent-read-agentview))))
1304
1305 ;; Save format may be either 1 or 2.  Two is the new, compressed format that is still being tested.  Format 1 is uncompressed but known to be reliable.
1306 (defconst gnus-agent-article-alist-save-format 2)
1307
1308 (defun gnus-agent-read-agentview (file)
1309   "Load FILE and do a `read' there."
1310   (with-temp-buffer
1311     (ignore-errors
1312       (nnheader-insert-file-contents file)
1313       (goto-char (point-min))
1314       (let ((alist (read (current-buffer)))
1315             (version (condition-case nil (read (current-buffer))
1316                        (end-of-file 0)))
1317             changed-version)
1318
1319         (cond ((= version 0)
1320                (let ((inhibit-quit t)
1321                      entry)
1322                  (gnus-agent-open-history)
1323                  (set-buffer (gnus-agent-history-buffer))
1324                  (goto-char (point-min))
1325                  (while (not (eobp))
1326                    (if (and (looking-at
1327                              "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1328                             (string= (match-string 2)
1329                                      gnus-agent-read-agentview)
1330                             (setq entry (assoc (string-to-number (match-string 3)) alist)))
1331                        (setcdr entry (string-to-number (match-string 1))))
1332                    (forward-line 1))
1333                  (gnus-agent-close-history)
1334                  (setq changed-version t)))
1335               ((= version 1)
1336                (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1337               ((= version 2)
1338                (let (uncomp)
1339                  (mapcar (lambda (comp-list)
1340                            (let ((state (car comp-list))
1341                                  (sequence (gnus-uncompress-sequence (cdr comp-list))))
1342                              (mapcar (lambda (article-id)
1343                                        (setq uncomp (cons (cons article-id state) uncomp))) sequence))) alist)
1344                  (setq alist (sort uncomp (lambda (first second) (< (car first) (car second)))))
1345                  )
1346                ))
1347         (when changed-version
1348           (let ((gnus-agent-article-alist alist))
1349             (gnus-agent-save-alist gnus-agent-read-agentview)))
1350         alist))))
1351
1352 (defun gnus-agent-save-alist (group &optional articles state dir)
1353   "Save the article-state alist for GROUP."
1354   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1355          (pathname-coding-system nnmail-pathname-coding-system)
1356          (prev (cons nil gnus-agent-article-alist))
1357          (all prev)
1358          print-level print-length item article)
1359     (while (setq article (pop articles))
1360       (while (and (cdr prev)
1361                   (< (caadr prev) article))
1362         (setq prev (cdr prev)))
1363       (cond
1364        ((not (cdr prev))
1365         (setcdr prev (list (cons article state))))
1366        ((> (caadr prev) article)
1367         (setcdr prev (cons (cons article state) (cdr prev))))
1368        ((= (caadr prev) article)
1369         (setcdr (cadr prev) state)))
1370       (setq prev (cdr prev)))
1371     (setq gnus-agent-article-alist (cdr all))
1372     (with-temp-file (if dir
1373                         (expand-file-name ".agentview" dir)
1374                       (gnus-agent-article-name ".agentview" group))
1375       (cond ((eq gnus-agent-article-alist-save-format 1)
1376              (princ gnus-agent-article-alist (current-buffer)))
1377             ((eq gnus-agent-article-alist-save-format 2)
1378              (let ((compressed nil))
1379                (mapcar (lambda (pair)
1380                          (let* ((article-id (car pair))
1381                                 (day-of-download (cdr pair))
1382                                 (comp-list (assq day-of-download compressed)))
1383                            (if comp-list
1384                                (setcdr comp-list (cons article-id (cdr comp-list)))
1385                              (setq compressed (cons (list day-of-download article-id) compressed)))
1386                            nil)) gnus-agent-article-alist)
1387                (mapcar (lambda (comp-list) (setcdr comp-list (gnus-compress-sequence (nreverse (cdr comp-list))))) compressed)
1388                (princ compressed (current-buffer))
1389                )
1390              )
1391             )
1392       (insert "\n")
1393       (princ gnus-agent-article-alist-save-format (current-buffer))
1394       (insert "\n"))))
1395
1396 (defun gnus-agent-article-name (article group)
1397   (expand-file-name (if (stringp article) article (string-to-number article))
1398                     (file-name-as-directory
1399                      (expand-file-name (gnus-agent-group-path group)
1400                                        (gnus-agent-directory)))))
1401
1402 (defun gnus-agent-batch-confirmation (msg)
1403   "Show error message and return t."
1404   (gnus-message 1 msg)
1405   t)
1406
1407 ;;;###autoload
1408 (defun gnus-agent-batch-fetch ()
1409   "Start Gnus and fetch session."
1410   (interactive)
1411   (gnus)
1412   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1413     (gnus-agent-fetch-session))
1414   (gnus-group-exit))
1415
1416 (defun gnus-agent-fetch-session ()
1417   "Fetch all articles and headers that are eligible for fetching."
1418   (interactive)
1419   (unless gnus-agent-covered-methods
1420     (error "No servers are covered by the Gnus agent"))
1421   (unless gnus-plugged
1422     (error "Can't fetch articles while Gnus is unplugged"))
1423   (let ((methods gnus-agent-covered-methods)
1424         groups group gnus-command-method)
1425     (save-excursion
1426       (while methods
1427         (condition-case err
1428             (progn
1429               (setq gnus-command-method (car methods))
1430               (when (and (or (gnus-server-opened gnus-command-method)
1431                              (gnus-open-server gnus-command-method))
1432                          (gnus-online gnus-command-method))
1433                 (setq groups (gnus-groups-from-server (car methods)))
1434                 (gnus-agent-with-fetch
1435                   (while (setq group (pop groups))
1436                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1437                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1438           (error
1439            (unless (funcall gnus-agent-confirmation-function
1440                             (format "Error %s.  Continue? " (cdr err)))
1441              (error "Cannot fetch articles into the Gnus agent")))
1442           (quit
1443            (unless (funcall gnus-agent-confirmation-function
1444                             (format "Quit fetching session %s.  Continue? "
1445                                     (cdr err)))
1446              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1447         (pop methods))
1448       (run-hooks 'gnus-agent-fetch-hook)
1449       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1450
1451 (defun gnus-agent-fetch-group-1 (group method)
1452   "Fetch GROUP."
1453   (let ((gnus-command-method method)
1454         (gnus-newsgroup-name group)
1455         gnus-newsgroup-dependencies gnus-newsgroup-headers
1456         gnus-newsgroup-scored gnus-headers gnus-score
1457         gnus-use-cache articles arts
1458         category predicate info marks score-param
1459         (gnus-summary-expunge-below gnus-summary-expunge-below)
1460         (gnus-summary-mark-below gnus-summary-mark-below)
1461         (gnus-orphan-score gnus-orphan-score)
1462         ;; Maybe some other gnus-summary local variables should also
1463         ;; be put here.
1464         )
1465     (unless (gnus-check-group group)
1466       (error "Can't open server for %s" group))
1467     ;; Fetch headers.
1468     (when (and (or (gnus-active group)
1469                    (gnus-activate-group group))
1470                (setq articles (gnus-agent-fetch-headers group))
1471                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1472                  ;; Parse them and see which articles we want to fetch.
1473                  (setq gnus-newsgroup-dependencies
1474                        (make-vector (length articles) 0))
1475                  (setq gnus-newsgroup-headers
1476                        (gnus-get-newsgroup-headers-xover articles nil nil
1477                                                          group))
1478                  ;; Some articles may not exist, so update `articles'
1479                  ;; from what was actually found.  -- kai
1480                  (setq articles
1481                        (mapcar (lambda (x) (mail-header-number x))
1482                                gnus-newsgroup-headers))
1483                  ;; `gnus-agent-overview-buffer' may be killed for
1484                  ;; timeout reason.  If so, recreate it.
1485                  (gnus-agent-create-buffer)))
1486       (setq category (gnus-group-category group))
1487       (setq predicate
1488             (gnus-get-predicate
1489              (or (gnus-group-find-parameter group 'agent-predicate t)
1490                  (cadr category))))
1491       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1492           ;; Simple implementation
1493           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1494         (setq arts nil)
1495         (setq score-param
1496               (or (gnus-group-get-parameter group 'agent-score t)
1497                   (caddr category)))
1498         ;; Translate score-param into real one
1499         (cond
1500          ((not score-param))
1501          ((eq score-param 'file)
1502           (setq score-param (gnus-all-score-files group)))
1503          ((stringp (car score-param)))
1504          (t
1505           (setq score-param (list (list score-param)))))
1506         (when score-param
1507           (gnus-score-headers score-param))
1508       
1509         ;; Construct arts list with same order as gnus-newsgroup-headers
1510         (let* ((a (list nil)) 
1511                (b a))
1512           (while (setq gnus-headers (pop gnus-newsgroup-headers))
1513             (setq gnus-score
1514                   (or (cdr (assq (mail-header-number gnus-headers)
1515                                  gnus-newsgroup-scored))
1516                       gnus-summary-default-score))
1517             (when (funcall predicate)
1518               (setq a (setcdr a (list (mail-header-number gnus-headers))))))
1519           (setq arts (cdr b))))
1520
1521       ;; Fetch the articles.
1522       (when arts
1523         (gnus-agent-fetch-articles group arts)))
1524     ;; Perhaps we have some additional articles to fetch.
1525     (dolist (mark gnus-agent-download-marks)
1526       (setq arts (assq mark (gnus-info-marks
1527                              (setq info (gnus-get-info group)))))
1528       (when (cdr arts)
1529         (gnus-message 8 "Agent is downloading marked articles...")
1530         (gnus-agent-fetch-articles
1531          group (gnus-uncompress-range (cdr arts)))
1532         (when (eq mark 'download)
1533           (setq marks (delq arts (gnus-info-marks info)))
1534           (gnus-info-set-marks info marks)
1535           (gnus-dribble-enter
1536            (concat "(gnus-group-set-info '"
1537                    (gnus-prin1-to-string info)
1538                    ")")))))))
1539
1540 ;;;
1541 ;;; Agent Category Mode
1542 ;;;
1543
1544 (defvar gnus-category-mode-hook nil
1545   "Hook run in `gnus-category-mode' buffers.")
1546
1547 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1548   "Format of category lines.
1549
1550 Valid specifiers include:
1551 %c  Topic name (string)
1552 %g  The number of groups in the topic (integer)
1553
1554 General format specifiers can also be used.  See Info node
1555 `(gnus)Formatting Variables'.")
1556
1557 (defvar gnus-category-mode-line-format "Gnus: %%b"
1558   "The format specification for the category mode line.")
1559
1560 (defvar gnus-agent-short-article 100
1561   "Articles that have fewer lines than this are short.")
1562
1563 (defvar gnus-agent-long-article 200
1564   "Articles that have more lines than this are long.")
1565
1566 (defvar gnus-agent-low-score 0
1567   "Articles that have a score lower than this have a low score.")
1568
1569 (defvar gnus-agent-high-score 0
1570   "Articles that have a score higher than this have a high score.")
1571
1572
1573 ;;; Internal variables.
1574
1575 (defvar gnus-category-buffer "*Agent Category*")
1576
1577 (defvar gnus-category-line-format-alist
1578   `((?c gnus-tmp-name ?s)
1579     (?g gnus-tmp-groups ?d)))
1580
1581 (defvar gnus-category-mode-line-format-alist
1582   `((?u user-defined ?s)))
1583
1584 (defvar gnus-category-line-format-spec nil)
1585 (defvar gnus-category-mode-line-format-spec nil)
1586
1587 (defvar gnus-category-mode-map nil)
1588 (put 'gnus-category-mode 'mode-class 'special)
1589
1590 (unless gnus-category-mode-map
1591   (setq gnus-category-mode-map (make-sparse-keymap))
1592   (suppress-keymap gnus-category-mode-map)
1593
1594   (gnus-define-keys gnus-category-mode-map
1595     "q" gnus-category-exit
1596     "k" gnus-category-kill
1597     "c" gnus-category-copy
1598     "a" gnus-category-add
1599     "p" gnus-category-edit-predicate
1600     "g" gnus-category-edit-groups
1601     "s" gnus-category-edit-score
1602     "l" gnus-category-list
1603
1604     "\C-c\C-i" gnus-info-find-node
1605     "\C-c\C-b" gnus-bug))
1606
1607 (defvar gnus-category-menu-hook nil
1608   "*Hook run after the creation of the menu.")
1609
1610 (defun gnus-category-make-menu-bar ()
1611   (gnus-turn-off-edit-menu 'category)
1612   (unless (boundp 'gnus-category-menu)
1613     (easy-menu-define
1614      gnus-category-menu gnus-category-mode-map ""
1615      '("Categories"
1616        ["Add" gnus-category-add t]
1617        ["Kill" gnus-category-kill t]
1618        ["Copy" gnus-category-copy t]
1619        ["Edit predicate" gnus-category-edit-predicate t]
1620        ["Edit score" gnus-category-edit-score t]
1621        ["Edit groups" gnus-category-edit-groups t]
1622        ["Exit" gnus-category-exit t]))
1623
1624     (gnus-run-hooks 'gnus-category-menu-hook)))
1625
1626 (defun gnus-category-mode ()
1627   "Major mode for listing and editing agent categories.
1628
1629 All normal editing commands are switched off.
1630 \\<gnus-category-mode-map>
1631 For more in-depth information on this mode, read the manual
1632 \(`\\[gnus-info-find-node]').
1633
1634 The following commands are available:
1635
1636 \\{gnus-category-mode-map}"
1637   (interactive)
1638   (when (gnus-visual-p 'category-menu 'menu)
1639     (gnus-category-make-menu-bar))
1640   (kill-all-local-variables)
1641   (gnus-simplify-mode-line)
1642   (setq major-mode 'gnus-category-mode)
1643   (setq mode-name "Category")
1644   (gnus-set-default-directory)
1645   (setq mode-line-process nil)
1646   (use-local-map gnus-category-mode-map)
1647   (buffer-disable-undo)
1648   (setq truncate-lines t)
1649   (setq buffer-read-only t)
1650   (gnus-run-hooks 'gnus-category-mode-hook))
1651
1652 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1653
1654 (defun gnus-category-insert-line (category)
1655   (let* ((gnus-tmp-name (format "%s" (car category)))
1656          (gnus-tmp-groups (length (cadddr category))))
1657     (beginning-of-line)
1658     (gnus-add-text-properties
1659      (point)
1660      (prog1 (1+ (point))
1661        ;; Insert the text.
1662        (eval gnus-category-line-format-spec))
1663      (list 'gnus-category gnus-tmp-name))))
1664
1665 (defun gnus-enter-category-buffer ()
1666   "Go to the Category buffer."
1667   (interactive)
1668   (gnus-category-setup-buffer)
1669   (gnus-configure-windows 'category)
1670   (gnus-category-prepare))
1671
1672 (defun gnus-category-setup-buffer ()
1673   (unless (get-buffer gnus-category-buffer)
1674     (save-excursion
1675       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1676       (gnus-category-mode))))
1677
1678 (defun gnus-category-prepare ()
1679   (gnus-set-format 'category-mode)
1680   (gnus-set-format 'category t)
1681   (let ((alist gnus-category-alist)
1682         (buffer-read-only nil))
1683     (erase-buffer)
1684     (while alist
1685       (gnus-category-insert-line (pop alist)))
1686     (goto-char (point-min))
1687     (gnus-category-position-point)))
1688
1689 (defun gnus-category-name ()
1690   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1691       (error "No category on the current line")))
1692
1693 (defun gnus-category-read ()
1694   "Read the category alist."
1695   (setq gnus-category-alist
1696         (or (gnus-agent-read-file
1697              (nnheader-concat gnus-agent-directory "lib/categories"))
1698             (list (list 'default 'short nil nil)))))
1699
1700 (defun gnus-category-write ()
1701   "Write the category alist."
1702   (setq gnus-category-predicate-cache nil
1703         gnus-category-group-cache nil)
1704   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1705   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1706     (prin1 gnus-category-alist (current-buffer))))
1707
1708 (defun gnus-category-edit-predicate (category)
1709   "Edit the predicate for CATEGORY."
1710   (interactive (list (gnus-category-name)))
1711   (let ((info (assq category gnus-category-alist)))
1712     (gnus-edit-form
1713      (cadr info) (format "Editing the predicate for category %s" category)
1714      `(lambda (predicate)
1715         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1716         (gnus-category-write)
1717         (gnus-category-list)))))
1718
1719 (defun gnus-category-edit-score (category)
1720   "Edit the score expression for CATEGORY."
1721   (interactive (list (gnus-category-name)))
1722   (let ((info (assq category gnus-category-alist)))
1723     (gnus-edit-form
1724      (caddr info)
1725      (format "Editing the score expression for category %s" category)
1726      `(lambda (groups)
1727         (setcar (nthcdr 2 (assq ',category gnus-category-alist)) groups)
1728         (gnus-category-write)
1729         (gnus-category-list)))))
1730
1731 (defun gnus-category-edit-groups (category)
1732   "Edit the group list for CATEGORY."
1733   (interactive (list (gnus-category-name)))
1734   (let ((info (assq category gnus-category-alist)))
1735     (gnus-edit-form
1736      (cadddr info) (format "Editing the group list for category %s" category)
1737      `(lambda (groups)
1738         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1739         (gnus-category-write)
1740         (gnus-category-list)))))
1741
1742 (defun gnus-category-kill (category)
1743   "Kill the current category."
1744   (interactive (list (gnus-category-name)))
1745   (let ((info (assq category gnus-category-alist))
1746         (buffer-read-only nil))
1747     (gnus-delete-line)
1748     (setq gnus-category-alist (delq info gnus-category-alist))
1749     (gnus-category-write)))
1750
1751 (defun gnus-category-copy (category to)
1752   "Copy the current category."
1753   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1754   (let ((info (assq category gnus-category-alist)))
1755     (push (list to (gnus-copy-sequence (cadr info))
1756                 (gnus-copy-sequence (caddr info)) nil)
1757           gnus-category-alist)
1758     (gnus-category-write)
1759     (gnus-category-list)))
1760
1761 (defun gnus-category-add (category)
1762   "Create a new category."
1763   (interactive "SCategory name: ")
1764   (when (assq category gnus-category-alist)
1765     (error "Category %s already exists" category))
1766   (push (list category 'false nil nil)
1767         gnus-category-alist)
1768   (gnus-category-write)
1769   (gnus-category-list))
1770
1771 (defun gnus-category-list ()
1772   "List all categories."
1773   (interactive)
1774   (gnus-category-prepare))
1775
1776 (defun gnus-category-exit ()
1777   "Return to the group buffer."
1778   (interactive)
1779   (kill-buffer (current-buffer))
1780   (gnus-configure-windows 'group t))
1781
1782 ;; To avoid having 8-bit characters in the source file.
1783 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1784
1785 (defvar gnus-category-predicate-alist
1786   '((spam . gnus-agent-spam-p)
1787     (short . gnus-agent-short-p)
1788     (long . gnus-agent-long-p)
1789     (low . gnus-agent-low-scored-p)
1790     (high . gnus-agent-high-scored-p)
1791     (read . gnus-agent-read-p)
1792     (true . gnus-agent-true)
1793     (false . gnus-agent-false))
1794   "Mapping from short score predicate symbols to predicate functions.")
1795
1796 (defun gnus-agent-spam-p ()
1797   "Say whether an article is spam or not."
1798   (unless gnus-agent-spam-hashtb
1799     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1800   (if (not (equal (mail-header-references gnus-headers) ""))
1801       nil
1802     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1803       (prog1
1804           (gnus-gethash string gnus-agent-spam-hashtb)
1805         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1806
1807 (defun gnus-agent-short-p ()
1808   "Say whether an article is short or not."
1809   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1810
1811 (defun gnus-agent-long-p ()
1812   "Say whether an article is long or not."
1813   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1814
1815 (defun gnus-agent-low-scored-p ()
1816   "Say whether an article has a low score or not."
1817   (< gnus-score gnus-agent-low-score))
1818
1819 (defun gnus-agent-high-scored-p ()
1820   "Say whether an article has a high score or not."
1821   (> gnus-score gnus-agent-high-score))
1822
1823 (defun gnus-agent-read-p ()
1824   "Say whether an article is read or not."
1825   (gnus-member-of-range (mail-header-number gnus-headers)
1826                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
1827
1828 (defun gnus-category-make-function (cat)
1829   "Make a function from category CAT."
1830   (let ((func (gnus-category-make-function-1 cat)))
1831     (if (and (= (length func) 1)
1832              (symbolp (car func)))
1833         (car func)
1834       (gnus-byte-compile `(lambda () ,func)))))
1835
1836 (defun gnus-agent-true ()
1837   "Return t."
1838   t)
1839
1840 (defun gnus-agent-false ()
1841   "Return nil."
1842   nil)
1843
1844 (defun gnus-category-make-function-1 (cat)
1845   "Make a function from category CAT."
1846   (cond
1847    ;; Functions are just returned as is.
1848    ((or (symbolp cat)
1849         (gnus-functionp cat))
1850     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1851            cat)))
1852    ;; More complex category.
1853    ((consp cat)
1854     `(,(cond
1855         ((memq (car cat) '(& and))
1856          'and)
1857         ((memq (car cat) '(| or))
1858          'or)
1859         ((memq (car cat) gnus-category-not)
1860          'not))
1861       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1862    (t
1863     (error "Unknown category type: %s" cat))))
1864
1865 (defun gnus-get-predicate (predicate)
1866   "Return the predicate for CATEGORY."
1867   (or (cdr (assoc predicate gnus-category-predicate-cache))
1868       (let ((func (gnus-category-make-function predicate)))
1869         (setq gnus-category-predicate-cache
1870               (nconc gnus-category-predicate-cache
1871                      (list (cons predicate func))))
1872         func)))
1873
1874 (defun gnus-predicate-implies-unread (predicate)
1875   "Say whether PREDICATE implies unread articles only.
1876 It is okay to miss some cases, but there must be no false positives.
1877 That is, if this function returns true, then indeed the predicate must
1878 return only unread articles."
1879   ;; Todo: make this work in more cases.
1880   (equal predicate '(not read)))
1881
1882 (defun gnus-group-category (group)
1883   "Return the category GROUP belongs to."
1884   (unless gnus-category-group-cache
1885     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1886     (let ((cs gnus-category-alist)
1887           groups cat)
1888       (while (setq cat (pop cs))
1889         (setq groups (cadddr cat))
1890         (while groups
1891           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1892   (or (gnus-gethash group gnus-category-group-cache)
1893       (assq 'default gnus-category-alist)))
1894
1895 (defun gnus-agent-expire (&optional articles group force)
1896   "Expire all old articles.
1897 If you want to force expiring of certain articles, this function can
1898 take ARTICLES, GROUP and FORCE parameters as well.
1899
1900 The articles on which the expiration process runs are selected as follows:
1901   if ARTICLES is null, all read and unmarked articles.
1902   if ARTICLES is t, all articles.
1903   if ARTICLES is a list, just those articles.
1904 Setting GROUP will limit expiration to that group.
1905 FORCE is equivalent to setting gnus-agent-expire-days to zero(0)."
1906   (interactive)
1907
1908   (if force (setq force 'forced))
1909
1910   (if (or (not (eq articles t))
1911           (yes-or-no-p (concat "Are you sure that you want to expire all articles in " (if group group "every agentized group") ".")))
1912       (let ((methods (if group
1913                          (list (gnus-find-method-for-group group))
1914                        gnus-agent-covered-methods))
1915             (day (if (numberp gnus-agent-expire-days)
1916                      (- (time-to-days (current-time)) gnus-agent-expire-days)
1917                    nil))
1918             gnus-command-method sym arts pos
1919             history overview file histories elem art nov-file low info
1920             unreads marked article orig lowest highest found days)
1921         (save-excursion
1922           (setq overview (gnus-get-buffer-create " *expire overview*"))
1923           (while (setq gnus-command-method (pop methods))
1924             (when (file-exists-p (gnus-agent-lib-file "active"))
1925               (with-temp-buffer
1926                 (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1927                 (gnus-active-to-gnus-format
1928                  gnus-command-method
1929                  (setq orig (gnus-make-hashtable
1930                              (count-lines (point-min) (point-max))))))
1931               (dolist (expiring-group (gnus-groups-from-server gnus-command-method))
1932                 (if (or (not group)
1933                         (equal group expiring-group))
1934                     (let* ((dir (concat
1935                                  (gnus-agent-directory)
1936                                  (gnus-agent-group-path expiring-group) "/")))
1937                       (cond ((gnus-gethash-safe expiring-group; KJG (gnus-group-real-name expiring-group)
1938                                                 orig)
1939                              (gnus-agent-load-alist expiring-group)
1940                              (gnus-message 5 "Expiring articles in %s" expiring-group)
1941                              (let* ((info (gnus-get-info expiring-group))
1942                                     (alist gnus-agent-article-alist)
1943                                     changed-alist
1944                                     (specials (if alist
1945                                                   (list (caar (last alist)))))
1946                                     (unreads;; Articles that are excluded from the expiration process
1947                                      (cond (gnus-agent-expire-all
1948                                             ;; All articles are marked read by global decree
1949                                             nil)
1950                                            ((eq articles t)
1951                                             ;; All articles are marked read by function parameter
1952                                             nil)
1953                                            ((not articles)
1954                                             ;; Unread articles are marked protected from expiration
1955                                             (ignore-errors (gnus-list-of-unread-articles expiring-group)))
1956                                            (t
1957                                             ;; All articles EXCEPT those named by the caller are protected from expiration
1958                                             (gnus-sorted-difference (gnus-uncompress-range (cons (caar alist) (caar (last alist)))) (sort articles '<)))))
1959                                     (marked;; More articles that are exluded from the expiration process
1960                                      (cond (gnus-agent-expire-all
1961                                             ;; All articles are unmarked by global decree
1962                                             nil)
1963                                            ((eq articles t)
1964                                             ;; All articles are unmarked by function parameter
1965                                             nil)
1966                                            (articles
1967                                             ;; All articles may as well be unmarked as the unreads list already names the articles we are going to keep
1968                                             nil)
1969                                            (t
1970                                             ;; Ticked and/or dormant articles are excluded from expiration
1971                                             (nconc
1972                                              (gnus-uncompress-range
1973                                               (cdr (assq 'tick (gnus-info-marks info))))
1974                                              (gnus-uncompress-range
1975                                               (cdr (assq 'dormant
1976                                                          (gnus-info-marks info))))))
1977                                            ))
1978                                     (keep (sort (nconc specials unreads marked) '<))
1979                                     (nov-file (concat dir ".overview"))
1980                                     (len (length alist))
1981                                     (cnt 0)
1982                                     type)
1983                                (when (file-exists-p nov-file)
1984                                  (set-buffer overview)
1985                                  (erase-buffer)
1986                                  (nnheader-insert-file-contents nov-file)
1987                                  (goto-char (point-min))
1988                                  (set-buffer-modified-p nil))
1989                                (while alist
1990                                  (let ((art (caar alist)))
1991                                    (gnus-message 9 "Processing %d of %d" (setq cnt (1+ cnt)) len)
1992                                    (while (< (or (car keep) (1+ art)) art)
1993                                      (ignore-errors
1994                                        (while (let ((nov-art (read (current-buffer))))
1995                                                 (cond ((< nov-art (car keep))
1996                                                        (gnus-delete-line)
1997                                                        t)
1998                                                       ((= nov-art (car keep))
1999                                                        (forward-line 1)
2000                                                        nil)
2001                                                       (t
2002                                                        (beginning-of-line)
2003                                                        nil)))))
2004                                      (setq keep (cdr keep)))
2005                          
2006                                    (cond ((eq art (car keep))
2007                                           (if (and (cdar alist)
2008                                                    (not (file-exists-p (concat dir (number-to-string art)))))
2009                                               (progn (setcdr (car alist) nil)
2010                                                      (gnus-message 7 "Article %d: cleared download flag as local file missing" (caar alist))
2011                                                      (setq changed-alist t)))
2012                                           (setq alist (cdr alist)
2013                                                 keep (cdr keep))
2014                                           (condition-case nil
2015                                               (while (let ((nov-art (read (current-buffer))))
2016                                                        (cond ((< nov-art art)
2017                                                               (gnus-message 7 "Article %d: NOV line removed" nov-art)
2018                                                               (gnus-delete-line)
2019                                                               t)
2020                                                              ((= nov-art art)
2021                                                               (forward-line 1)
2022                                                               nil)
2023                                                              (t
2024                                                               (beginning-of-line)
2025                                                               nil))))
2026                                             (error (forward-line 1))))
2027                                          ((setq type (let ((fetch-date (cdar alist)))
2028                                                        (or
2029                                                         ;; if read but not downloaded
2030                                                         (if (and (numberp fetch-date)
2031                                                                  (file-exists-p (concat dir (number-to-string art))))
2032                                                             nil
2033                                                           'read)
2034                                                         ;; We now have the arrival day, so we see
2035                                                         ;; whether it's old enough to be expired.
2036                                                         (if (< fetch-date
2037                                                                (if (numberp day)
2038                                                                    day
2039                                                                  (let (found
2040                                                                        (days gnus-agent-expire-days))
2041                                                                    (while (and (not found)
2042                                                                                days)
2043                                                                      (when (eq 0 (string-match (caar days) expiring-group))
2044                                                                        (setq found (cadar days)))
2045                                                                      (pop days))
2046                                                                    found)))
2047                                                             'expired)
2048                                                         force)))
2049                                           
2050                                           (if gnus-agent-consider-all-articles
2051                                               (setq alist (cdr alist)) ;; Iterate forward
2052                                             (gnus-message 7 "Article %d: Removed %s article from alist" art type)
2053                                             (setcar alist (cadr alist))
2054                                             (setcdr alist (cddr alist))
2055                                             (setq changed-alist t))
2056
2057                                           (if (memq type '(forced expired))
2058                                               (ignore-errors
2059                                                 (delete-file (concat dir (number-to-string art)))
2060                                                 (gnus-message 7 "Article %d: Expired local copy" art)))
2061                                           (ignore-errors
2062                                             (let (nov-art)
2063                                               (while (<= (setq nov-art (read (current-buffer))) art)
2064                                                 (gnus-message 7 "Article %d: NOV line removed" nov-art)
2065                                                 (gnus-delete-line)))
2066                                             (beginning-of-line))
2067                                           )
2068                                          (t
2069                                           (setq alist (cdr alist)))
2070                                          )
2071                                    )
2072                                  )
2073
2074                                (let ((inhibit-quit t))
2075                                  (if changed-alist
2076                                      (gnus-agent-save-alist expiring-group))
2077                                  (if (buffer-modified-p)
2078                                      (progn
2079                                        (gnus-make-directory dir)
2080                                        (write-region-as-coding-system
2081                                         gnus-agent-file-coding-system
2082                                         (point-min) (point-max) nov-file
2083                                         nil 'silent)
2084                                        ;; clear the modified flag as that I'm not confused by its status on the next pass through this routine.
2085                                        (set-buffer-modified-p nil))
2086                                    )
2087                                  (if (eq articles t)
2088                                      (gnus-summary-update-info))
2089                                  ))))))))))))
2090   (gnus-message 4 "Expiry...done"))
2091
2092 ;;;###autoload
2093 (defun gnus-agent-batch ()
2094   "Start Gnus, send queue and fetch session."
2095   (interactive)
2096   (let ((init-file-user "")
2097         (gnus-always-read-dribble-file t))
2098     (gnus))
2099   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2100     (gnus-group-send-queue)
2101     (gnus-agent-fetch-session)))
2102
2103 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
2104   "Constructs sublist of ARTICLES that excludes those articles ids in GROUP that have already been fetched.
2105  If CACHED-HEADER is nil, articles are only excluded if the article itself has been fetched."
2106
2107 ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar 'car gnus-agent-article-alist))
2108 ;; Functionally, I don't need to construct a temp list using mapcar.
2109
2110   (if (gnus-agent-load-alist group)
2111     (let* ((ref gnus-agent-article-alist)
2112            (arts articles)
2113            (uncached (list nil))
2114            (tail uncached))
2115       (while (and ref arts)
2116         (let ((v1 (car arts))
2117               (v2 (caar ref)))
2118           (cond ((< v1 v2) ; the article (v1) does not appear in the reference list
2119                  (setq tail (setcdr tail (list v1)))
2120                  (pop arts))
2121                 ((= v1 v2)
2122                  (unless (or cached-header (cdar ref)) ; the article (v1) is already cached
2123                    (setq tail (setcdr tail (list v1))))
2124                  (pop arts)
2125                  (pop ref))
2126                 (t ; the reference article (v2) preceeds the list being filtered
2127                  (pop ref)))))
2128       (while arts
2129         (setq tail (setcdr tail (list (pop arts)))))
2130       (cdr uncached))
2131     ;; if gnus-agent-load-alist fails, no articles are cached.
2132     articles))
2133
2134 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
2135   (save-excursion
2136     (gnus-agent-create-buffer)
2137     (let ((gnus-decode-encoded-word-function 'identity)
2138           (file (gnus-agent-article-name ".overview" group))
2139           cached-articles uncached-articles)
2140       (gnus-make-directory (nnheader-translate-file-chars
2141                             (file-name-directory file) t))
2142
2143       ;; Populate temp buffer with known headers
2144       (when (file-exists-p file)
2145         (with-current-buffer gnus-agent-overview-buffer
2146           (erase-buffer)
2147           (let ((nnheader-file-coding-system
2148                  gnus-agent-file-coding-system))
2149             (nnheader-insert-nov-file file (car articles)))))
2150
2151       (if (setq uncached-articles (gnus-agent-uncached-articles articles group t))
2152           (progn
2153             ;; Populate nntp-server-buffer with uncached headers
2154             (set-buffer nntp-server-buffer)
2155             (erase-buffer)
2156             (let (gnus-agent-cache)     ; Turn off agent cache
2157               (cond ((not (eq 'nov (gnus-retrieve-headers
2158                                     uncached-articles group fetch-old)))
2159                      (nnvirtual-convert-headers))
2160                     ((eq 'nntp (car gnus-current-select-method))
2161                      ;; The author of gnus-get-newsgroup-headers-xover reports that the XOVER command
2162                      ;; is commonly unreliable. The problem is that recently posted articles may not 
2163                      ;; be entered into the NOV database in time to respond to my XOVER query.
2164                      ;;
2165                      ;; I'm going to use his assumption that the NOV database is updated in order 
2166                      ;; of ascending article ID.  Therefore, a response containing article ID N 
2167                      ;; implies that all articles from 1 to N-1 are up-to-date.  Therefore, 
2168                      ;; missing articles in that range have expired.
2169                      
2170                      (set-buffer nntp-server-buffer)
2171                      (let* ((fetched-articles (list nil))
2172                             (tail fetched-articles)
2173                             (min (cond ((numberp fetch-old)
2174                                         (max 1 (- (car articles) fetch-old)))
2175                                        (fetch-old
2176                                         1)
2177                                        (t
2178                                         (car articles))))
2179                             (max (car (last articles))))
2180                        
2181                        ;; Get the list of articles that were fetched
2182                        (goto-char (point-min))
2183                        (ignore-errors 
2184                          (while t
2185                            (setq tail (setcdr tail (cons (read (current-buffer)) nil)))
2186                            (forward-line 1)))
2187                        
2188                        ;; Clip this list to the headers that will actually be returned
2189                        (setq fetched-articles (gnus-list-range-intersection
2190                                                (cdr fetched-articles)
2191                                                (cons min max)))
2192
2193                        ;; Clip the uncached articles list to exclude IDs after the last FETCHED header.  
2194                        ;; The excluded IDs may be fetchable using HEAD.
2195                        (if (car tail)
2196                            (setq uncached-articles (gnus-list-range-intersection 
2197                                                     uncached-articles 
2198                                                     (cons (car uncached-articles) (car tail)))))
2199
2200                        ;; Create the list of articles that were "successfully" fetched.  Success, in
2201                        ;; this case, means that the ID should not be fetched again.  In the case of 
2202                        ;; an expired article, the header will not be fetched.
2203                        (setq uncached-articles (gnus-sorted-nunion fetched-articles uncached-articles))
2204                        ))))
2205
2206             ;; Erase the temp buffer
2207             (set-buffer gnus-agent-overview-buffer)
2208             (erase-buffer)
2209
2210             ;; Copy the nntp-server-buffer to the temp buffer
2211             (set-buffer nntp-server-buffer)
2212             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
2213
2214             ;; Merge the temp buffer with the known headers (found on disk in FILE) into the nntp-server-buffer
2215             (when (and uncached-articles (file-exists-p file))
2216               (gnus-agent-braid-nov group uncached-articles file))
2217
2218             ;; Save the new set of known headers to FILE
2219             (set-buffer nntp-server-buffer)
2220             (gnus-agent-check-overview-buffer)
2221             (write-region-as-coding-system
2222              gnus-agent-file-coding-system
2223              (point-min) (point-max) file nil 'silent)
2224             
2225             ;; Update the group's article alist to include the newly fetched articles.
2226             (gnus-agent-load-alist group)
2227             (gnus-agent-save-alist group uncached-articles nil)
2228             )
2229         
2230         ;; Copy the temp buffer to the nntp-server-buffer
2231         (set-buffer nntp-server-buffer)
2232         (erase-buffer)
2233         (insert-buffer-substring gnus-agent-overview-buffer)))
2234
2235     (if (and fetch-old
2236              (not (numberp fetch-old)))
2237         t                               ; Don't remove anything.
2238       (nnheader-nov-delete-outside-range
2239        (if fetch-old (max 1 (- (car articles) fetch-old))
2240          (car articles))
2241        (car (last articles)))
2242       t)
2243
2244     'nov))
2245
2246 (defun gnus-agent-request-article (article group)
2247   "Retrieve ARTICLE in GROUP from the agent cache."
2248   (let* ((gnus-command-method (gnus-find-method-for-group group))
2249          (file (concat
2250                   (gnus-agent-directory)
2251                   (gnus-agent-group-path group) "/"
2252                   (number-to-string article)))
2253          (buffer-read-only nil))
2254     (when (and (file-exists-p file)
2255                (> (nth 7 (file-attributes file)) 0))
2256       (erase-buffer)
2257       (gnus-kill-all-overlays)
2258       (insert-file-contents-as-coding-system gnus-cache-coding-system file)
2259       t)))
2260
2261 (defun gnus-agent-regenerate-group (group &optional reread)
2262   "Regenerate GROUP.  If REREAD is t, all articles in the .overview are marked as unread.  If REREAD is not nil, downloaded articles are marked as unread."
2263   (gnus-message 5 "Regenerating in %s" group)
2264   (let* ((gnus-command-method (or gnus-command-method
2265                                   (gnus-find-method-for-group group)))
2266          (file (gnus-agent-article-name ".overview" group))
2267          (dir (file-name-directory file))
2268          point 
2269          (downloaded (if (file-exists-p dir)
2270                          (sort (mapcar (lambda (name) (string-to-int name))
2271                                        (directory-files dir nil "^[0-9]+$" t))
2272                                '>)
2273                        (progn (gnus-make-directory dir) nil)))
2274          dl nov-arts
2275          alist header
2276          regenerated)
2277
2278     (mm-with-unibyte-buffer
2279      (if (file-exists-p file)
2280          (let ((nnheader-file-coding-system
2281                 gnus-agent-file-coding-system))
2282            (nnheader-insert-file-contents file)))
2283      (set-buffer-modified-p nil)
2284
2285      ;; Load the article IDs found in the overview file.  As a side-effect, validate the file contents.
2286      (let ((load t))
2287        (while load
2288          (setq load nil)
2289          (goto-char (point-min))
2290          (while (< (point) (point-max))
2291            (cond ((looking-at "[0-9]+\\b")
2292                   (push (read (current-buffer)) nov-arts)
2293                   (forward-line 1)
2294                   (let ((l1 (car nov-arts))
2295                         (l2 (cadr nov-arts)))
2296                     (cond ((not l2)
2297                            nil)
2298                           ((< l1 l2)
2299                            ;; Don't sort now as I haven't verified that every line begins with a number
2300                            (setq load t))
2301                           ((= l1 l2)
2302                            (forward-line -1)
2303                            (gnus-delete-line)
2304                            (pop nov-arts)))))
2305                  (t
2306                   (gnus-delete-line))))
2307          (if load
2308              (progn (sort-numeric-fields 1 (point-min) (point-max))
2309                     (setq nov-arts nil)))))
2310      (gnus-agent-check-overview-buffer)
2311
2312      ;; Construct a new article alist whose nodes match every header in the .overview file.  
2313      ;; As a side-effect, missing headers are reconstructed from the downloaded article file.
2314      (while (or downloaded nov-arts)
2315        (cond ((and downloaded 
2316                    (or (not nov-arts)
2317                        (> (car downloaded) (car nov-arts))))
2318               ;; This entry is missing from the overview file
2319               (gnus-message 6 "Regenerating NOV %s %d..." group (car downloaded))
2320               (let ((file (concat dir (number-to-string (car downloaded)))))
2321                 (mm-with-unibyte-buffer
2322                  (nnheader-insert-file-contents file)
2323                  (nnheader-remove-body)
2324                  (setq header (nnheader-parse-naked-head)))
2325                 (mail-header-set-number header (car downloaded))
2326                 (if nov-arts
2327                     (let ((key (concat "^" (int-to-string (car nov-arts)) "\t")))
2328                       (or (re-search-backward key nil t)
2329                           (re-search-forward key))
2330                       (forward-line 1))
2331                   (goto-char (point-min)))
2332                 (nnheader-insert-nov header))
2333               (setq nov-arts (cons (car downloaded) nov-arts)))
2334              ((eq (car downloaded) (car nov-arts))
2335               ;; This entry in the overview has been downloaded
2336               (push (cons (car downloaded) (time-to-days (nth 5 (file-attributes (concat dir (number-to-string (car downloaded))))))) alist)
2337               (pop downloaded)
2338               (pop nov-arts))
2339              (t
2340               ;; This entry in the overview has not been downloaded
2341               (push (cons (car nov-arts) nil) alist)
2342               (pop nov-arts))))
2343
2344      ;; When gnus-agent-consider-all-articles is set, gnus-agent-regenerate-group should NOT remove article IDs 
2345      ;; from the alist.  Those IDs serve as markers to indicate that an attempt has been made to fetch that 
2346      ;; article's header.
2347
2348      ;; When gnus-agent-consider-all-articles is NOT set, gnus-agent-regenerate-group can remove the article
2349      ;; ID of every article (with the exception of the last ID in the list - it's special) that no longer appears in the overview.
2350      ;; In this situtation, the last article ID in the list implies that it, and every article ID preceeding it, 
2351      ;; have been fetched from the server.
2352      (if gnus-agent-consider-all-articles
2353          ;; Restore all article IDs that were not found in the overview file.
2354          (let* ((n (cons nil alist))
2355                 (merged n)
2356                 (o (gnus-agent-load-alist group)))
2357            (while o
2358              (let ((nID (caadr n))
2359                    (oID (caar o)))
2360                (cond ((not nID)
2361                       (setq n (setcdr n (list (list oID))))
2362                       (pop o))
2363                      ((< oID nID)
2364                       (setcdr n (cons (list oID) (cdr n)))
2365                       (pop o))
2366                      ((= oID nID)
2367                       (pop o)
2368                       (pop n))
2369                      (t
2370                       (pop n)))))
2371            (setq alist (cdr merged)))
2372        ;; Restore the last article ID if it is not already in the new alist
2373        (let ((n (last alist))
2374              (o (last (gnus-agent-load-alist group))))
2375          (cond ((not n)
2376                 (when o
2377                   (push (cons (caar o) nil) alist)))
2378                ((< (caar n) (caar o))
2379                 (setcdr n (list (car o)))))))
2380                      
2381      (if (setq regenerated (buffer-modified-p))
2382          (write-region-as-coding-system
2383           gnus-agent-file-coding-system
2384           (point-min) (point-max) file nil 'silent))
2385      )
2386
2387     (setq regenerated (or regenerated
2388                           (and reread gnus-agent-article-alist)
2389                           (not (equal alist gnus-agent-article-alist)))
2390           )
2391
2392     (setq gnus-agent-article-alist alist)
2393  
2394     (when regenerated
2395       (gnus-agent-save-alist group))
2396
2397     (when (and reread gnus-agent-article-alist)
2398       (gnus-make-ascending-articles-unread
2399        group
2400        (delq nil (mapcar (function (lambda (c)
2401                                      (cond ((eq reread t)
2402                                             (car c))
2403                                            ((cdr c)
2404                                             (car c)))))
2405                          gnus-agent-article-alist)))
2406
2407       (when (gnus-buffer-live-p gnus-group-buffer)
2408         (gnus-group-update-group group t)
2409         (sit-for 0))
2410       )
2411
2412     regenerated))
2413
2414 ;;;###autoload
2415 (defun gnus-agent-regenerate (&optional clean reread)
2416   "Regenerate all agent covered files.
2417 If CLEAN, don't read existing active files."
2418   (interactive "P")
2419   (let (regenerated)
2420     (gnus-message 4 "Regenerating Gnus agent files...")
2421     (dolist (gnus-command-method gnus-agent-covered-methods)
2422       (let ((active-file (gnus-agent-lib-file "active"))
2423             active-hashtb active-changed
2424             point)
2425         (gnus-make-directory (file-name-directory active-file))
2426         (if clean
2427             (setq active-hashtb (gnus-make-hashtable 1000))
2428           (mm-with-unibyte-buffer
2429            (if (file-exists-p active-file)
2430                (let ((nnheader-file-coding-system
2431                       gnus-agent-file-coding-system))
2432                  (nnheader-insert-file-contents active-file))
2433              (setq active-changed t))
2434            (gnus-active-to-gnus-format
2435             nil (setq active-hashtb
2436                       (gnus-make-hashtable
2437                        (count-lines (point-min) (point-max)))))))
2438         (dolist (group (gnus-groups-from-server gnus-command-method))
2439           (setq regenerated (or (gnus-agent-regenerate-group group reread)
2440                                 regenerated))
2441           (let ((min (or (caar gnus-agent-article-alist) 1))
2442                 (max (or (caar (last gnus-agent-article-alist)) 0))
2443                 (active (gnus-gethash-safe (gnus-group-real-name group)
2444                                            active-hashtb))
2445                 (read (gnus-info-read (gnus-get-info group))))
2446             (if (not active)
2447                 (progn
2448                   (setq active (cons min max)
2449                         active-changed t)
2450                   (gnus-sethash group active active-hashtb))
2451               (when (> (car active) min)
2452                 (setcar active min)
2453                 (setq active-changed t))
2454               (when (< (cdr active) max)
2455                 (setcdr active max)
2456                 (setq active-changed t)))))
2457         (when active-changed
2458           (setq regenerated t)
2459           (gnus-message 4 "Regenerate %s" active-file)
2460           (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2461             (gnus-write-active-file active-file active-hashtb)))))
2462     (gnus-message 4 "Regenerating Gnus agent files...done")
2463     regenerated))
2464
2465 (defun gnus-agent-go-online (&optional force)
2466   "Switch servers into online status."
2467   (interactive (list t))
2468   (dolist (server gnus-opened-servers)
2469     (when (eq (nth 1 server) 'offline)
2470       (if (if (eq force 'ask)
2471               (gnus-y-or-n-p
2472                (format "Switch %s:%s into online status? "
2473                        (caar server) (cadar server)))
2474             force)
2475           (setcar (nthcdr 1 server) 'close)))))
2476
2477 (defun gnus-agent-toggle-group-plugged (group)
2478   "Toggle the status of the server of the current group."
2479   (interactive (list (gnus-group-group-name)))
2480   (let* ((method (gnus-find-method-for-group group))
2481          (status (cadr (assoc method gnus-opened-servers))))
2482     (if (eq status 'offline)
2483         (gnus-server-set-status method 'closed)
2484       (gnus-close-server method)
2485       (gnus-server-set-status method 'offline))
2486     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2487              (if (eq status 'offline) 'offline 'online)
2488              (if (eq status 'offline) 'online 'offline))))
2489
2490 (provide 'gnus-agent)
2491
2492 ;;; gnus-agent.el ends here