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