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