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