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