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