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