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