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