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