*** empty log message ***
[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     (save-excursion
1079       (when buffer (set-buffer buffer))
1080       (save-excursion
1081         (save-restriction
1082           (let ((deactivate-mark deactivate-mark))
1083             (widen)
1084             (goto-char (point-min))
1085             (setq prev-num (number-at-point))
1086             (while (and (zerop (forward-line 1))
1087                         (not (eobp)))
1088               (let ((cur (number-at-point)))
1089                 (cond ((= cur prev-num)
1090                        (gnus-message 10
1091                                      "Duplicate overview line for %d" cur)
1092                        (debug nil (format "Duplicate overview line for %d" cur))
1093                        (delete-region (point) (progn (forward-line 1) (point))))
1094                       ((< cur prev-num)
1095                        (gnus-message 10 "Overview buffer not sorted!")
1096                        (debug nil "Overview buffer not sorted!"))))
1097               (setq prev-num (number-at-point)))))))))
1098
1099
1100 (defun gnus-agent-flush-cache ()
1101   (save-excursion
1102     (while gnus-agent-buffer-alist
1103       (set-buffer (cdar gnus-agent-buffer-alist))
1104       (let ((coding-system-for-write
1105              gnus-agent-file-coding-system))
1106         (write-region (point-min) (point-max)
1107                       (gnus-agent-article-name ".overview"
1108                                                (caar gnus-agent-buffer-alist))
1109                       nil 'silent))
1110       (pop gnus-agent-buffer-alist))
1111     (while gnus-agent-group-alist
1112       (with-temp-file (gnus-agent-article-name ".agentview" (caar gnus-agent-group-alist))
1113         (princ (cdar gnus-agent-group-alist))
1114         (insert "\n")
1115         (princ 1 (current-buffer))
1116         (insert "\n"))
1117       (pop gnus-agent-group-alist))))
1118
1119 (defun gnus-agent-fetch-headers (group &optional force)
1120   (let* ((fetch-all (and gnus-agent-consider-all-articles
1121                          ;; Do not fetch all headers if the predicate
1122                          ;; implies that we only consider unread articles.
1123                          (not (gnus-predicate-implies-unread
1124                                (or (gnus-group-find-parameter
1125                                     group 'agent-predicate t)
1126                                    (cadr (gnus-group-category group)))))))
1127          (articles (if fetch-all
1128                        (gnus-uncompress-range (gnus-active group))
1129                      (gnus-list-of-unread-articles group)))
1130          (gnus-decode-encoded-word-function 'identity)
1131          (file (gnus-agent-article-name ".overview" group))
1132          gnus-agent-cache)
1133
1134     (unless fetch-all
1135       ;; Add articles with marks to the list of article headers we want to
1136       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1137       ;; mark, but do fetch recent or seen articles if they have other, more
1138       ;; interesting marks.  (We have to fetch articles with boring marks
1139       ;; because otherwise the agent will remove their marks.)
1140       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1141         (unless (memq (car arts) '(seen recent))
1142           (setq articles (gnus-range-add articles (cdr arts)))))
1143       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1144
1145     ;; At this point, I have the list of articles to consider for fetching.  
1146     ;; This is the list that I'll return to my caller. Some of these articles may have already 
1147     ;; been fetched.  That's OK as the fetch article code will filter those out.
1148     ;; Internally, I'll filter this list to just those articles whose headers need to be fetched.
1149     (let ((articles articles))
1150       ;; Remove known articles.
1151       (when (gnus-agent-load-alist group)
1152         ;; Remove articles marked as downloaded.
1153         (if fetch-all
1154             ;; I want to fetch all headers in the active range.  
1155             ;; Therefore, exclude only those headers that are in the article alist.
1156             ;; NOTE: This is probably NOT what I want to do after agent expiration in this group.
1157             (setq articles (gnus-agent-uncached-articles articles group))
1158
1159           ;; I want to only fetch those headers that have never been fetched. 
1160           ;; Therefore, exclude all headers that are, or WERE, in the article alist.
1161           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1162                 (high (cdr (gnus-active group))))
1163             ;; Low can be greater than High when the same group is fetched twice
1164             ;; in the same session {The first fetch will fill the article alist 
1165             ;; such that (last gnus-agent-article-alist) equals (cdr (gnus-active group))}.  
1166             ;; The addition of one(the 1+ above) then forces Low to be greater than High.  
1167             ;; When this happens, gnus-list-range-intersection returns nil which indicates 
1168             ;; that no headers need to be fetched. -- Kevin
1169             (setq articles (gnus-list-range-intersection
1170                             articles (list (cons low high)))))))
1171       (when articles
1172         (gnus-message 7 "Fetching headers for %s..." group)
1173
1174         ;; Fetch them.
1175         (gnus-make-directory (nnheader-translate-file-chars
1176                               (file-name-directory file) t))
1177
1178         (save-excursion
1179           (set-buffer nntp-server-buffer)
1180           (unless (eq 'nov (gnus-retrieve-headers articles group))
1181             (nnvirtual-convert-headers))
1182           (gnus-agent-check-overview-buffer)
1183           ;; Move these headers to the overview buffer so that gnus-agent-brand-nov can merge them
1184           ;; with the contents of FILE.
1185           (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1186           (when (file-exists-p file)
1187             (gnus-agent-braid-nov group articles file))
1188           (let ((coding-system-for-write
1189                  gnus-agent-file-coding-system))
1190           (gnus-agent-check-overview-buffer)
1191             (write-region (point-min) (point-max) file nil 'silent))
1192           (gnus-agent-save-alist group articles nil)
1193           articles)))
1194     articles))
1195
1196 (defsubst gnus-agent-copy-nov-line (article)
1197   (let (art b e)
1198     (set-buffer gnus-agent-overview-buffer)
1199     (while (and (not (eobp))
1200                 (< (setq art (read (current-buffer))) article))
1201       (forward-line 1))
1202     (beginning-of-line)
1203     (if (or (eobp)
1204             (not (eq article art)))
1205         (set-buffer nntp-server-buffer)
1206       (setq b (point))
1207       (setq e (progn (forward-line 1) (point)))
1208       (set-buffer nntp-server-buffer)
1209       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1210
1211 (defun gnus-agent-braid-nov (group articles file)
1212   "Merges the article headers identified by ARTICLES from gnus-agent-overview-buffer with the contents
1213 of FILE placing the combined headers in nntp-server-buffer."
1214   (let (start last)
1215     (set-buffer gnus-agent-overview-buffer)
1216     (goto-char (point-min))
1217     (set-buffer nntp-server-buffer)
1218     (erase-buffer)
1219     (nnheader-insert-file-contents file)
1220     (goto-char (point-max))
1221     (unless (or (= (point-min) (point-max))
1222                 (progn
1223                   (forward-line -1)
1224                   (< (setq last (read (current-buffer))) (car articles))))
1225       ;; We do it the hard way.
1226       (when (nnheader-find-nov-line (car articles))
1227         ;; Replacing existing NOV entry
1228         (delete-region (point) (progn (forward-line 1) (point))))
1229       (gnus-agent-copy-nov-line (pop articles))
1230
1231       (ignore-errors
1232         (while articles
1233           (while (let ((art (read (current-buffer))))
1234                    (cond ((< art (car articles))
1235                           (forward-line 1)
1236                           t)
1237                          ((= art (car articles))
1238                           (beginning-of-line)
1239                           (delete-region (point) (progn (forward-line 1) (point)))
1240                           nil)
1241                          (t
1242                           (beginning-of-line)
1243                           nil))))
1244             
1245           (gnus-agent-copy-nov-line (pop articles)))))
1246
1247     ;; Copy the rest lines
1248     (set-buffer nntp-server-buffer)
1249     (goto-char (point-max))
1250     (when articles
1251       (when last
1252         (set-buffer gnus-agent-overview-buffer)
1253         (ignore-errors
1254           (while (<= (read (current-buffer)) last)
1255             (forward-line 1)))
1256         (beginning-of-line)
1257         (setq start (point))
1258         (set-buffer nntp-server-buffer))
1259       (insert-buffer-substring gnus-agent-overview-buffer start))))
1260
1261 (eval-when-compile ; Keeps the compiler from warning about the free variable in gnus-agent-read-agentview
1262   (defvar gnus-agent-read-agentview))
1263
1264 (defun gnus-agent-load-alist (group)
1265   (let ((gnus-agent-read-agentview group)) ; Binds free variable that's used in gnus-agent-read-agentview
1266     "Load the article-state alist for GROUP."
1267     (setq gnus-agent-article-alist
1268           (gnus-cache-file-contents
1269            (gnus-agent-article-name ".agentview" group)
1270            'gnus-agent-file-loading-cache
1271            'gnus-agent-read-agentview))))
1272
1273 ;; 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.
1274 (defconst gnus-agent-article-alist-save-format 2)
1275
1276 (defun gnus-agent-read-agentview (file)
1277   "Load FILE and do a `read' there."
1278   (with-temp-buffer
1279     (ignore-errors
1280       (nnheader-insert-file-contents file)
1281       (goto-char (point-min))
1282       (let ((alist (read (current-buffer)))
1283             (version (condition-case nil (read (current-buffer))
1284                        (end-of-file 0)))
1285             changed-version)
1286
1287         (cond ((= version 0)
1288                (let ((inhibit-quit t)
1289                      entry)
1290                  (gnus-agent-open-history)
1291                  (set-buffer (gnus-agent-history-buffer))
1292                  (goto-char (point-min))
1293                  (while (not (eobp))
1294                    (if (and (looking-at
1295                              "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1296                             (string= (match-string 2)
1297                                      gnus-agent-read-agentview)
1298                             (setq entry (assoc (string-to-number (match-string 3)) alist)))
1299                        (setcdr entry (string-to-number (match-string 1))))
1300                    (forward-line 1))
1301                  (gnus-agent-close-history)
1302                  (setq changed-version t)))
1303               ((= version 1)
1304                (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1305               ((= version 2)
1306                (let (uncomp)
1307                  (mapcar (lambda (comp-list)
1308                            (let ((state (car comp-list))
1309                                  (sequence (gnus-uncompress-sequence (cdr comp-list))))
1310                              (mapcar (lambda (article-id)
1311                                        (setq uncomp (cons (cons article-id state) uncomp))) sequence))) alist)
1312                  (setq alist (sort uncomp (lambda (first second) (< (car first) (car second)))))
1313                  )
1314                ))
1315         (when changed-version
1316           (let ((gnus-agent-article-alist alist))
1317             (gnus-agent-save-alist gnus-agent-read-agentview)))
1318         alist))))
1319
1320 (defun gnus-agent-save-alist (group &optional articles state dir)
1321   "Save the article-state alist for GROUP."
1322   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1323          (prev (cons nil gnus-agent-article-alist))
1324          (all prev)
1325          print-level print-length item article)
1326     (while (setq article (pop articles))
1327       (while (and (cdr prev)
1328                   (< (caadr prev) article))
1329         (setq prev (cdr prev)))
1330       (cond
1331        ((not (cdr prev))
1332         (setcdr prev (list (cons article state))))
1333        ((> (caadr prev) article)
1334         (setcdr prev (cons (cons article state) (cdr prev))))
1335        ((= (caadr prev) article)
1336         (setcdr (cadr prev) state)))
1337       (setq prev (cdr prev)))
1338     (setq gnus-agent-article-alist (cdr all))
1339     (with-temp-file (if dir
1340                         (expand-file-name ".agentview" dir)
1341                       (gnus-agent-article-name ".agentview" group))
1342       (cond ((eq gnus-agent-article-alist-save-format 1)
1343              (princ gnus-agent-article-alist (current-buffer)))
1344             ((eq gnus-agent-article-alist-save-format 2)
1345              (let ((compressed nil))
1346                (mapcar (lambda (pair)
1347                          (let* ((article-id (car pair))
1348                                 (day-of-download (cdr pair))
1349                                 (comp-list (assq day-of-download compressed)))
1350                            (if comp-list
1351                                (setcdr comp-list (cons article-id (cdr comp-list)))
1352                              (setq compressed (cons (list day-of-download article-id) compressed)))
1353                            nil)) gnus-agent-article-alist)
1354                (mapcar (lambda (comp-list) (setcdr comp-list (gnus-compress-sequence (nreverse (cdr comp-list))))) compressed)
1355                (princ compressed (current-buffer))
1356                )
1357              )
1358             )
1359       (insert "\n")
1360       (princ gnus-agent-article-alist-save-format (current-buffer))
1361       (insert "\n"))))
1362
1363 (defun gnus-agent-article-name (article group)
1364   (expand-file-name (if (stringp article) article (string-to-number article))
1365                     (file-name-as-directory
1366                      (expand-file-name (gnus-agent-group-path group)
1367                                        (gnus-agent-directory)))))
1368
1369 (defun gnus-agent-batch-confirmation (msg)
1370   "Show error message and return t."
1371   (gnus-message 1 msg)
1372   t)
1373
1374 ;;;###autoload
1375 (defun gnus-agent-batch-fetch ()
1376   "Start Gnus and fetch session."
1377   (interactive)
1378   (gnus)
1379   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1380     (gnus-agent-fetch-session))
1381   (gnus-group-exit))
1382
1383 (defun gnus-agent-fetch-session ()
1384   "Fetch all articles and headers that are eligible for fetching."
1385   (interactive)
1386   (unless gnus-agent-covered-methods
1387     (error "No servers are covered by the Gnus agent"))
1388   (unless gnus-plugged
1389     (error "Can't fetch articles while Gnus is unplugged"))
1390   (let ((methods gnus-agent-covered-methods)
1391         groups group gnus-command-method)
1392     (save-excursion
1393       (while methods
1394         (condition-case err
1395             (progn
1396               (setq gnus-command-method (car methods))
1397               (when (and (or (gnus-server-opened gnus-command-method)
1398                              (gnus-open-server gnus-command-method))
1399                          (gnus-online gnus-command-method))
1400                 (setq groups (gnus-groups-from-server (car methods)))
1401                 (gnus-agent-with-fetch
1402                   (while (setq group (pop groups))
1403                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1404                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1405           (error
1406            (unless (funcall gnus-agent-confirmation-function
1407                             (format "Error %s.  Continue? " (cdr err)))
1408              (error "Cannot fetch articles into the Gnus agent")))
1409           (quit
1410            (unless (funcall gnus-agent-confirmation-function
1411                             (format "Quit fetching session %s.  Continue? "
1412                                     (cdr err)))
1413              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1414         (pop methods))
1415       (run-hooks 'gnus-agent-fetch-hook)
1416       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1417
1418 (defun gnus-agent-fetch-group-1 (group method)
1419   "Fetch GROUP."
1420   (let ((gnus-command-method method)
1421         (gnus-newsgroup-name group)
1422         gnus-newsgroup-dependencies gnus-newsgroup-headers
1423         gnus-newsgroup-scored gnus-headers gnus-score
1424         gnus-use-cache articles arts
1425         category predicate info marks score-param
1426         (gnus-summary-expunge-below gnus-summary-expunge-below)
1427         (gnus-summary-mark-below gnus-summary-mark-below)
1428         (gnus-orphan-score gnus-orphan-score)
1429         ;; Maybe some other gnus-summary local variables should also
1430         ;; be put here.
1431         )
1432     (unless (gnus-check-group group)
1433       (error "Can't open server for %s" group))
1434     ;; Fetch headers.
1435     (when (and (or (gnus-active group)
1436                    (gnus-activate-group group))
1437                (setq articles (gnus-agent-fetch-headers group))
1438                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1439                  ;; Parse them and see which articles we want to fetch.
1440                  (setq gnus-newsgroup-dependencies
1441                        (make-vector (length articles) 0))
1442                  (setq gnus-newsgroup-headers
1443                        (gnus-get-newsgroup-headers-xover articles nil nil
1444                                                          group))
1445                  ;; Some articles may not exist, so update `articles'
1446                  ;; from what was actually found.  -- kai
1447                  (setq articles
1448                        (mapcar (lambda (x) (aref x 0))
1449                                gnus-newsgroup-headers))
1450                  ;; `gnus-agent-overview-buffer' may be killed for
1451                  ;; timeout reason.  If so, recreate it.
1452                  (gnus-agent-create-buffer)))
1453       (setq category (gnus-group-category group))
1454       (setq predicate
1455             (gnus-get-predicate
1456              (or (gnus-group-find-parameter group 'agent-predicate t)
1457                  (cadr category))))
1458       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1459           ;; Simple implementation
1460           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1461         (setq arts nil)
1462         (setq score-param
1463               (or (gnus-group-get-parameter group 'agent-score t)
1464                   (caddr category)))
1465         ;; Translate score-param into real one
1466         (cond
1467          ((not score-param))
1468          ((eq score-param 'file)
1469           (setq score-param (gnus-all-score-files group)))
1470          ((stringp (car score-param)))
1471          (t
1472           (setq score-param (list (list score-param)))))
1473         (when score-param
1474           (gnus-score-headers score-param))
1475       
1476         ;; Construct arts list with same order as gnus-newsgroup-headers
1477         (let* ((a (list nil)) 
1478                (b a))
1479           (while (setq gnus-headers (pop gnus-newsgroup-headers))
1480             (setq gnus-score
1481                   (or (cdr (assq (mail-header-number gnus-headers)
1482                                  gnus-newsgroup-scored))
1483                       gnus-summary-default-score))
1484             (when (funcall predicate)
1485               (setq a (setcdr a (list (mail-header-number gnus-headers))))))
1486           (setq arts (cdr b))))
1487
1488       ;; Fetch the articles.
1489       (when arts
1490         (gnus-agent-fetch-articles group arts)))
1491     ;; Perhaps we have some additional articles to fetch.
1492     (dolist (mark gnus-agent-download-marks)
1493       (setq arts (assq mark (gnus-info-marks
1494                              (setq info (gnus-get-info group)))))
1495       (when (cdr arts)
1496         (gnus-message 8 "Agent is downloading marked articles...")
1497         (gnus-agent-fetch-articles
1498          group (gnus-uncompress-range (cdr arts)))
1499         (when (eq mark 'download)
1500           (setq marks (delq arts (gnus-info-marks info)))
1501           (gnus-info-set-marks info marks)
1502           (gnus-dribble-enter
1503            (concat "(gnus-group-set-info '"
1504                    (gnus-prin1-to-string info)
1505                    ")")))))))
1506
1507 ;;;
1508 ;;; Agent Category Mode
1509 ;;;
1510
1511 (defvar gnus-category-mode-hook nil
1512   "Hook run in `gnus-category-mode' buffers.")
1513
1514 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1515   "Format of category lines.
1516
1517 Valid specifiers include:
1518 %c  Topic name (string)
1519 %g  The number of groups in the topic (integer)
1520
1521 General format specifiers can also be used.  See Info node
1522 `(gnus)Formatting Variables'.")
1523
1524 (defvar gnus-category-mode-line-format "Gnus: %%b"
1525   "The format specification for the category mode line.")
1526
1527 (defvar gnus-agent-short-article 100
1528   "Articles that have fewer lines than this are short.")
1529
1530 (defvar gnus-agent-long-article 200
1531   "Articles that have more lines than this are long.")
1532
1533 (defvar gnus-agent-low-score 0
1534   "Articles that have a score lower than this have a low score.")
1535
1536 (defvar gnus-agent-high-score 0
1537   "Articles that have a score higher than this have a high score.")
1538
1539
1540 ;;; Internal variables.
1541
1542 (defvar gnus-category-buffer "*Agent Category*")
1543
1544 (defvar gnus-category-line-format-alist
1545   `((?c gnus-tmp-name ?s)
1546     (?g gnus-tmp-groups ?d)))
1547
1548 (defvar gnus-category-mode-line-format-alist
1549   `((?u user-defined ?s)))
1550
1551 (defvar gnus-category-line-format-spec nil)
1552 (defvar gnus-category-mode-line-format-spec nil)
1553
1554 (defvar gnus-category-mode-map nil)
1555 (put 'gnus-category-mode 'mode-class 'special)
1556
1557 (unless gnus-category-mode-map
1558   (setq gnus-category-mode-map (make-sparse-keymap))
1559   (suppress-keymap gnus-category-mode-map)
1560
1561   (gnus-define-keys gnus-category-mode-map
1562     "q" gnus-category-exit
1563     "k" gnus-category-kill
1564     "c" gnus-category-copy
1565     "a" gnus-category-add
1566     "p" gnus-category-edit-predicate
1567     "g" gnus-category-edit-groups
1568     "s" gnus-category-edit-score
1569     "l" gnus-category-list
1570
1571     "\C-c\C-i" gnus-info-find-node
1572     "\C-c\C-b" gnus-bug))
1573
1574 (defvar gnus-category-menu-hook nil
1575   "*Hook run after the creation of the menu.")
1576
1577 (defun gnus-category-make-menu-bar ()
1578   (gnus-turn-off-edit-menu 'category)
1579   (unless (boundp 'gnus-category-menu)
1580     (easy-menu-define
1581      gnus-category-menu gnus-category-mode-map ""
1582      '("Categories"
1583        ["Add" gnus-category-add t]
1584        ["Kill" gnus-category-kill t]
1585        ["Copy" gnus-category-copy t]
1586        ["Edit predicate" gnus-category-edit-predicate t]
1587        ["Edit score" gnus-category-edit-score t]
1588        ["Edit groups" gnus-category-edit-groups t]
1589        ["Exit" gnus-category-exit t]))
1590
1591     (gnus-run-hooks 'gnus-category-menu-hook)))
1592
1593 (defun gnus-category-mode ()
1594   "Major mode for listing and editing agent categories.
1595
1596 All normal editing commands are switched off.
1597 \\<gnus-category-mode-map>
1598 For more in-depth information on this mode, read the manual
1599 \(`\\[gnus-info-find-node]').
1600
1601 The following commands are available:
1602
1603 \\{gnus-category-mode-map}"
1604   (interactive)
1605   (when (gnus-visual-p 'category-menu 'menu)
1606     (gnus-category-make-menu-bar))
1607   (kill-all-local-variables)
1608   (gnus-simplify-mode-line)
1609   (setq major-mode 'gnus-category-mode)
1610   (setq mode-name "Category")
1611   (gnus-set-default-directory)
1612   (setq mode-line-process nil)
1613   (use-local-map gnus-category-mode-map)
1614   (buffer-disable-undo)
1615   (setq truncate-lines t)
1616   (setq buffer-read-only t)
1617   (gnus-run-hooks 'gnus-category-mode-hook))
1618
1619 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1620
1621 (defun gnus-category-insert-line (category)
1622   (let* ((gnus-tmp-name (format "%s" (car category)))
1623          (gnus-tmp-groups (length (cadddr category))))
1624     (beginning-of-line)
1625     (gnus-add-text-properties
1626      (point)
1627      (prog1 (1+ (point))
1628        ;; Insert the text.
1629        (eval gnus-category-line-format-spec))
1630      (list 'gnus-category gnus-tmp-name))))
1631
1632 (defun gnus-enter-category-buffer ()
1633   "Go to the Category buffer."
1634   (interactive)
1635   (gnus-category-setup-buffer)
1636   (gnus-configure-windows 'category)
1637   (gnus-category-prepare))
1638
1639 (defun gnus-category-setup-buffer ()
1640   (unless (get-buffer gnus-category-buffer)
1641     (save-excursion
1642       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1643       (gnus-category-mode))))
1644
1645 (defun gnus-category-prepare ()
1646   (gnus-set-format 'category-mode)
1647   (gnus-set-format 'category t)
1648   (let ((alist gnus-category-alist)
1649         (buffer-read-only nil))
1650     (erase-buffer)
1651     (while alist
1652       (gnus-category-insert-line (pop alist)))
1653     (goto-char (point-min))
1654     (gnus-category-position-point)))
1655
1656 (defun gnus-category-name ()
1657   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1658       (error "No category on the current line")))
1659
1660 (defun gnus-category-read ()
1661   "Read the category alist."
1662   (setq gnus-category-alist
1663         (or (gnus-agent-read-file
1664              (nnheader-concat gnus-agent-directory "lib/categories"))
1665             (list (list 'default 'short nil nil)))))
1666
1667 (defun gnus-category-write ()
1668   "Write the category alist."
1669   (setq gnus-category-predicate-cache nil
1670         gnus-category-group-cache nil)
1671   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1672   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1673     (prin1 gnus-category-alist (current-buffer))))
1674
1675 (defun gnus-category-edit-predicate (category)
1676   "Edit the predicate for CATEGORY."
1677   (interactive (list (gnus-category-name)))
1678   (let ((info (assq category gnus-category-alist)))
1679     (gnus-edit-form
1680      (cadr info) (format "Editing the predicate for category %s" category)
1681      `(lambda (predicate)
1682         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1683         (gnus-category-write)
1684         (gnus-category-list)))))
1685
1686 (defun gnus-category-edit-score (category)
1687   "Edit the score expression for CATEGORY."
1688   (interactive (list (gnus-category-name)))
1689   (let ((info (assq category gnus-category-alist)))
1690     (gnus-edit-form
1691      (caddr info)
1692      (format "Editing the score expression for category %s" category)
1693      `(lambda (groups)
1694         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1695         (gnus-category-write)
1696         (gnus-category-list)))))
1697
1698 (defun gnus-category-edit-groups (category)
1699   "Edit the group list for CATEGORY."
1700   (interactive (list (gnus-category-name)))
1701   (let ((info (assq category gnus-category-alist)))
1702     (gnus-edit-form
1703      (cadddr info) (format "Editing the group list for category %s" category)
1704      `(lambda (groups)
1705         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1706         (gnus-category-write)
1707         (gnus-category-list)))))
1708
1709 (defun gnus-category-kill (category)
1710   "Kill the current category."
1711   (interactive (list (gnus-category-name)))
1712   (let ((info (assq category gnus-category-alist))
1713         (buffer-read-only nil))
1714     (gnus-delete-line)
1715     (setq gnus-category-alist (delq info gnus-category-alist))
1716     (gnus-category-write)))
1717
1718 (defun gnus-category-copy (category to)
1719   "Copy the current category."
1720   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1721   (let ((info (assq category gnus-category-alist)))
1722     (push (list to (gnus-copy-sequence (cadr info))
1723                 (gnus-copy-sequence (caddr info)) nil)
1724           gnus-category-alist)
1725     (gnus-category-write)
1726     (gnus-category-list)))
1727
1728 (defun gnus-category-add (category)
1729   "Create a new category."
1730   (interactive "SCategory name: ")
1731   (when (assq category gnus-category-alist)
1732     (error "Category %s already exists" category))
1733   (push (list category 'false nil nil)
1734         gnus-category-alist)
1735   (gnus-category-write)
1736   (gnus-category-list))
1737
1738 (defun gnus-category-list ()
1739   "List all categories."
1740   (interactive)
1741   (gnus-category-prepare))
1742
1743 (defun gnus-category-exit ()
1744   "Return to the group buffer."
1745   (interactive)
1746   (kill-buffer (current-buffer))
1747   (gnus-configure-windows 'group t))
1748
1749 ;; To avoid having 8-bit characters in the source file.
1750 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1751
1752 (defvar gnus-category-predicate-alist
1753   '((spam . gnus-agent-spam-p)
1754     (short . gnus-agent-short-p)
1755     (long . gnus-agent-long-p)
1756     (low . gnus-agent-low-scored-p)
1757     (high . gnus-agent-high-scored-p)
1758     (read . gnus-agent-read-p)
1759     (true . gnus-agent-true)
1760     (false . gnus-agent-false))
1761   "Mapping from short score predicate symbols to predicate functions.")
1762
1763 (defun gnus-agent-spam-p ()
1764   "Say whether an article is spam or not."
1765   (unless gnus-agent-spam-hashtb
1766     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1767   (if (not (equal (mail-header-references gnus-headers) ""))
1768       nil
1769     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1770       (prog1
1771           (gnus-gethash string gnus-agent-spam-hashtb)
1772         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1773
1774 (defun gnus-agent-short-p ()
1775   "Say whether an article is short or not."
1776   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1777
1778 (defun gnus-agent-long-p ()
1779   "Say whether an article is long or not."
1780   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1781
1782 (defun gnus-agent-low-scored-p ()
1783   "Say whether an article has a low score or not."
1784   (< gnus-score gnus-agent-low-score))
1785
1786 (defun gnus-agent-high-scored-p ()
1787   "Say whether an article has a high score or not."
1788   (> gnus-score gnus-agent-high-score))
1789
1790 (defun gnus-agent-read-p ()
1791   "Say whether an article is read or not."
1792   (gnus-member-of-range (mail-header-number gnus-headers)
1793                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
1794
1795 (defun gnus-category-make-function (cat)
1796   "Make a function from category CAT."
1797   (let ((func (gnus-category-make-function-1 cat)))
1798     (if (and (= (length func) 1)
1799              (symbolp (car func)))
1800         (car func)
1801       (gnus-byte-compile `(lambda () ,func)))))
1802
1803 (defun gnus-agent-true ()
1804   "Return t."
1805   t)
1806
1807 (defun gnus-agent-false ()
1808   "Return nil."
1809   nil)
1810
1811 (defun gnus-category-make-function-1 (cat)
1812   "Make a function from category CAT."
1813   (cond
1814    ;; Functions are just returned as is.
1815    ((or (symbolp cat)
1816         (gnus-functionp cat))
1817     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1818            cat)))
1819    ;; More complex category.
1820    ((consp cat)
1821     `(,(cond
1822         ((memq (car cat) '(& and))
1823          'and)
1824         ((memq (car cat) '(| or))
1825          'or)
1826         ((memq (car cat) gnus-category-not)
1827          'not))
1828       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1829    (t
1830     (error "Unknown category type: %s" cat))))
1831
1832 (defun gnus-get-predicate (predicate)
1833   "Return the predicate for CATEGORY."
1834   (or (cdr (assoc predicate gnus-category-predicate-cache))
1835       (let ((func (gnus-category-make-function predicate)))
1836         (setq gnus-category-predicate-cache
1837               (nconc gnus-category-predicate-cache
1838                      (list (cons predicate func))))
1839         func)))
1840
1841 (defun gnus-predicate-implies-unread (predicate)
1842   "Say whether PREDICATE implies unread articles only.
1843 It is okay to miss some cases, but there must be no false positives.
1844 That is, if this function returns true, then indeed the predicate must
1845 return only unread articles."
1846   ;; Todo: make this work in more cases.
1847   (equal predicate '(not read)))
1848
1849 (defun gnus-group-category (group)
1850   "Return the category GROUP belongs to."
1851   (unless gnus-category-group-cache
1852     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1853     (let ((cs gnus-category-alist)
1854           groups cat)
1855       (while (setq cat (pop cs))
1856         (setq groups (cadddr cat))
1857         (while groups
1858           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1859   (or (gnus-gethash group gnus-category-group-cache)
1860       (assq 'default gnus-category-alist)))
1861
1862 (defun gnus-agent-expire (&optional articles group force)
1863   "Expire all old articles.
1864 If you want to force expiring of certain articles, this function can
1865 take ARTICLES, GROUP and FORCE parameters as well.
1866
1867 The articles on which the expiration process runs are selected as follows:
1868   if ARTICLES is null, all read and unmarked articles.
1869   if ARTICLES is t, all articles.
1870   if ARTICLES is a list, just those articles.
1871 Setting GROUP will limit expiration to that group.
1872 FORCE is equivalent to setting gnus-agent-expire-days to zero(0)."
1873   (interactive)
1874
1875   (if force (setq force 'forced))
1876
1877   (if (or (not (eq articles t))
1878           (yes-or-no-p (concat "Are you sure that you want to expire all articles in " (if group group "every agentized group") ".")))
1879       (let ((methods (if group
1880                          (list (gnus-find-method-for-group group))
1881                        gnus-agent-covered-methods))
1882             (day (if (numberp gnus-agent-expire-days)
1883                      (- (time-to-days (current-time)) gnus-agent-expire-days)
1884                    nil))
1885             gnus-command-method sym arts pos
1886             history overview file histories elem art nov-file low info
1887             unreads marked article orig lowest highest found days)
1888         (save-excursion
1889           (setq overview (gnus-get-buffer-create " *expire overview*"))
1890           (while (setq gnus-command-method (pop methods))
1891             (when (file-exists-p (gnus-agent-lib-file "active"))
1892               (with-temp-buffer
1893                 (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1894                 (gnus-active-to-gnus-format
1895                  gnus-command-method
1896                  (setq orig (gnus-make-hashtable
1897                              (count-lines (point-min) (point-max))))))
1898               (dolist (expiring-group (gnus-groups-from-server gnus-command-method))
1899                 (if (or (not group)
1900                         (equal group expiring-group))
1901                     (let* ((dir (concat
1902                                  (gnus-agent-directory)
1903                                  (gnus-agent-group-path expiring-group) "/")))
1904                       (cond ((gnus-gethash-safe expiring-group; KJG (gnus-group-real-name expiring-group)
1905                                                 orig)
1906                              (gnus-agent-load-alist expiring-group)
1907                              (gnus-message 5 "Expiring articles in %s" expiring-group)
1908                              (let* ((info (gnus-get-info expiring-group))
1909                                     (alist gnus-agent-article-alist)
1910                                     changed-alist
1911                                     (specials (if alist
1912                                                   (list (caar (last alist)))))
1913                                     (unreads;; Articles that are excluded from the expiration process
1914                                      (cond (gnus-agent-expire-all
1915                                             ;; All articles are marked read by global decree
1916                                             nil)
1917                                            ((eq articles t)
1918                                             ;; All articles are marked read by function parameter
1919                                             nil)
1920                                            ((not articles)
1921                                             ;; Unread articles are marked protected from expiration
1922                                             (ignore-errors (gnus-list-of-unread-articles expiring-group)))
1923                                            (t
1924                                             ;; All articles EXCEPT those named by the caller are protected from expiration
1925                                             (gnus-sorted-difference (gnus-uncompress-range (cons (caar alist) (caar (last alist)))) (sort articles '<)))))
1926                                     (marked;; More articles that are exluded from the expiration process
1927                                      (cond (gnus-agent-expire-all
1928                                             ;; All articles are unmarked by global decree
1929                                             nil)
1930                                            ((eq articles t)
1931                                             ;; All articles are unmarked by function parameter
1932                                             nil)
1933                                            (articles
1934                                             ;; All articles may as well be unmarked as the unreads list already names the articles we are going to keep
1935                                             nil)
1936                                            (t
1937                                             ;; Ticked and/or dormant articles are excluded from expiration
1938                                             (nconc
1939                                              (gnus-uncompress-range
1940                                               (cdr (assq 'tick (gnus-info-marks info))))
1941                                              (gnus-uncompress-range
1942                                               (cdr (assq 'dormant
1943                                                          (gnus-info-marks info))))))
1944                                            ))
1945                                     (keep (sort (nconc specials unreads marked) '<))
1946                                     (nov-file (concat dir ".overview"))
1947                                     (len (length alist))
1948                                     (cnt 0)
1949                                     type)
1950                                (when (file-exists-p nov-file)
1951                                  (set-buffer overview)
1952                                  (erase-buffer)
1953                                  (nnheader-insert-file-contents nov-file)
1954                                  (goto-char (point-min))
1955                                  (set-buffer-modified-p nil))
1956                                (while alist
1957                                  (let ((art (caar alist)))
1958                                    (gnus-message 9 "Processing %d of %d" (setq cnt (1+ cnt)) len)
1959                                    (while (< (or (car keep) (1+ art)) art)
1960                                      (ignore-errors
1961                                        (while (let ((nov-art (read (current-buffer))))
1962                                                 (cond ((< nov-art (car keep))
1963                                                        (gnus-delete-line)
1964                                                        t)
1965                                                       ((= nov-art (car keep))
1966                                                        (forward-line 1)
1967                                                        nil)
1968                                                       (t
1969                                                        (beginning-of-line)
1970                                                        nil)))))
1971                                      (setq keep (cdr keep)))
1972                          
1973                                    (cond ((eq art (car keep))
1974                                           (if (and (cdar alist)
1975                                                    (not (file-exists-p (concat dir (number-to-string art)))))
1976                                               (progn (setcdr (car alist) nil)
1977                                                      (gnus-message 7 "Article %d: cleared download flag as local file missing" (caar alist))
1978                                                      (setq changed-alist t)))
1979                                           (setq alist (cdr alist)
1980                                                 keep (cdr keep))
1981                                           (condition-case nil
1982                                               (while (let ((nov-art (read (current-buffer))))
1983                                                        (cond ((< nov-art art)
1984                                                               (gnus-message 7 "Article %d: NOV line removed" nov-art)
1985                                                               (gnus-delete-line)
1986                                                               t)
1987                                                              ((= nov-art art)
1988                                                               (forward-line 1)
1989                                                               nil)
1990                                                              (t
1991                                                               (beginning-of-line)
1992                                                               nil))))
1993                                             (error (forward-line 1))))
1994                                          ((setq type (let ((fetch-date (cdar alist)))
1995                                                        (or
1996                                                         ;; if read but not downloaded
1997                                                         (if (and (numberp fetch-date)
1998                                                                  (file-exists-p (concat dir (number-to-string art))))
1999                                                             nil
2000                                                           'read)
2001                                                         ;; We now have the arrival day, so we see
2002                                                         ;; whether it's old enough to be expired.
2003                                                         (if (< fetch-date
2004                                                                (if (numberp day)
2005                                                                    day
2006                                                                  (let (found
2007                                                                        (days gnus-agent-expire-days))
2008                                                                    (while (and (not found)
2009                                                                                days)
2010                                                                      (when (eq 0 (string-match (caar days) expiring-group))
2011                                                                        (setq found (cadar days)))
2012                                                                      (pop days))
2013                                                                    found)))
2014                                                             'expired)
2015                                                         force)))
2016                                           
2017                                           (if gnus-agent-consider-all-articles
2018                                               (setq alist (cdr alist)) ;; Iterate forward
2019                                             (gnus-message 7 "Article %d: Removed %s article from alist" art type)
2020                                             (setcar alist (cadr alist))
2021                                             (setcdr alist (cddr alist))
2022                                             (setq changed-alist t))
2023
2024                                           (if (memq type '(forced expired))
2025                                               (ignore-errors
2026                                                 (delete-file (concat dir (number-to-string art)))
2027                                                 (gnus-message 7 "Article %d: Expired local copy" art)))
2028                                           (ignore-errors
2029                                             (let (nov-art)
2030                                               (while (<= (setq nov-art (read (current-buffer))) art)
2031                                                 (gnus-message 7 "Article %d: NOV line removed" nov-art)
2032                                                 (gnus-delete-line)))
2033                                             (beginning-of-line))
2034                                           )
2035                                          (t
2036                                           (setq alist (cdr alist)))
2037                                          )
2038                                    )
2039                                  )
2040
2041                                (let ((inhibit-quit t))
2042                                  (if changed-alist
2043                                      (gnus-agent-save-alist expiring-group))
2044                                  (if (buffer-modified-p)
2045                                      (let ((coding-system-for-write
2046                                             gnus-agent-file-coding-system))
2047                                        (gnus-make-directory dir)
2048                                        (write-region (point-min) (point-max) nov-file nil 'silent)
2049                                        ;; clear the modified flag as that I'm not confused by its status on the next pass through this routine.
2050                                        (set-buffer-modified-p nil))
2051                                    )
2052                                  (if (eq articles t)
2053                                      (gnus-summary-update-info))
2054                                  ))))))))))))
2055   (gnus-message 4 "Expiry...done"))
2056
2057 ;;;###autoload
2058 (defun gnus-agent-batch ()
2059   "Start Gnus, send queue and fetch session."
2060   (interactive)
2061   (let ((init-file-user "")
2062         (gnus-always-read-dribble-file t))
2063     (gnus))
2064   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2065     (gnus-group-send-queue)
2066     (gnus-agent-fetch-session)))
2067
2068 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
2069   "Constructs sublist of ARTICLES that excludes those articles ids in GROUP that have already been fetched.
2070  If CACHED-HEADER is nil, articles are only excluded if the article itself has been fetched."
2071
2072 ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar 'car gnus-agent-article-alist))
2073 ;; Functionally, I don't need to construct a temp list using mapcar.
2074
2075   (when (gnus-agent-load-alist group)
2076     (let* ((ref gnus-agent-article-alist)
2077            (arts articles)
2078            (uncached (list nil))
2079            (tail uncached))
2080       (while (and ref arts)
2081         (let ((v1 (car arts))
2082               (v2 (caar ref)))
2083           (cond ((< v1 v2) ; the article (v1) does not appear in the reference list
2084                  (setq tail (setcdr tail (list v1)))
2085                  (pop arts))
2086                 ((= v1 v2)
2087                  (unless (or cached-header (cdar ref)) ; the article (v1) is already cached
2088                    (setq tail (setcdr tail (list v1))))
2089                  (pop arts)
2090                  (pop ref))
2091                 (t ; the reference article (v2) preceeds the list being filtered
2092                  (pop ref)))))
2093       (while arts
2094         (setq tail (setcdr tail (list (pop arts)))))
2095       (cdr uncached))))
2096
2097 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
2098   (save-excursion
2099     (gnus-agent-create-buffer)
2100     (let ((gnus-decode-encoded-word-function 'identity)
2101           (file (gnus-agent-article-name ".overview" group))
2102           cached-articles uncached-articles)
2103       (gnus-make-directory (nnheader-translate-file-chars
2104                             (file-name-directory file) t))
2105
2106       ;; Populate temp buffer with known headers
2107       (when (file-exists-p file)
2108         (with-current-buffer gnus-agent-overview-buffer
2109           (erase-buffer)
2110           (let ((nnheader-file-coding-system
2111                  gnus-agent-file-coding-system))
2112             (nnheader-insert-nov-file file (car articles)))))
2113
2114       (if (setq uncached-articles (gnus-agent-uncached-articles articles group t))
2115           (progn
2116             ;; Populate nntp-server-buffer with uncached headers
2117             (set-buffer nntp-server-buffer)
2118             (erase-buffer)
2119             (let (gnus-agent-cache)     ; Turn off agent cache
2120               (cond ((not (eq 'nov (gnus-retrieve-headers
2121                                     uncached-articles group fetch-old)))
2122                      (nnvirtual-convert-headers))
2123                     ((eq 'nntp (car gnus-current-select-method))
2124                      ;; The author of gnus-get-newsgroup-headers-xover reports that the XOVER command
2125                      ;; is commonly unreliable. The problem is that recently posted articles may not 
2126                      ;; be entered into the NOV database in time to respond to my XOVER query.
2127                      ;;
2128                      ;; I'm going to use his assumption that the NOV database is updated in order 
2129                      ;; of ascending article ID.  Therefore, a response containing article ID N 
2130                      ;; implies that all articles from 1 to N-1 are up-to-date.  Therefore, 
2131                      ;; missing articles in that range have expired.
2132                      
2133                      (set-buffer nntp-server-buffer)
2134                      (let* ((fetched-articles (list nil))
2135                             (tail fetched-articles)
2136                             (min (cond ((numberp fetch-old)
2137                                         (max 1 (- (car articles) fetch-old)))
2138                                        (fetch-old
2139                                         1)
2140                                        (t
2141                                         (car articles))))
2142                             (max (car (last articles))))
2143                        
2144                        ;; Get the list of articles that were fetched
2145                        (goto-char (point-min))
2146                        (ignore-errors 
2147                          (while t
2148                            (setq tail (setcdr tail (cons (read (current-buffer)) nil)))
2149                            (forward-line 1)))
2150                        
2151                        ;; Clip this list to the headers that will actually be returned
2152                        (setq fetched-articles (gnus-list-range-intersection
2153                                                (cdr fetched-articles)
2154                                                (cons min max)))
2155
2156                        ;; Clip the uncached articles list to exclude IDs after the last FETCHED header.  
2157                        ;; The excluded IDs may be fetchable using HEAD.
2158                        (if (car tail)
2159                            (setq uncached-articles (gnus-list-range-intersection 
2160                                                     uncached-articles 
2161                                                     (cons (car uncached-articles) (car tail)))))
2162
2163                        ;; Create the list of articles that were "successfully" fetched.  Success, in
2164                        ;; this case, means that the ID should not be fetched again.  In the case of 
2165                        ;; an expired article, the header will not be fetched.
2166                        (setq uncached-articles (gnus-sorted-nunion fetched-articles uncached-articles))
2167                        ))))
2168
2169             ;; Erase the temp buffer
2170             (set-buffer gnus-agent-overview-buffer)
2171             (erase-buffer)
2172
2173             ;; Copy the nntp-server-buffer to the temp buffer
2174             (set-buffer nntp-server-buffer)
2175             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
2176
2177             ;; Merge the temp buffer with the known headers (found on disk in FILE) into the nntp-server-buffer
2178             (when (and uncached-articles (file-exists-p file))
2179               (gnus-agent-braid-nov group uncached-articles file))
2180
2181             ;; Save the new set of known headers to FILE
2182             (set-buffer nntp-server-buffer)
2183             (let ((coding-system-for-write
2184                    gnus-agent-file-coding-system))
2185               (gnus-agent-check-overview-buffer)
2186               (write-region (point-min) (point-max) file nil 'silent))
2187             
2188             ;; Update the group's article alist to include the newly fetched articles.
2189             (gnus-agent-load-alist group)
2190             (gnus-agent-save-alist group uncached-articles nil)
2191             )
2192         
2193         ;; Copy the temp buffer to the nntp-server-buffer
2194         (set-buffer nntp-server-buffer)
2195         (erase-buffer)
2196         (insert-buffer-substring gnus-agent-overview-buffer)))
2197
2198     (if (and fetch-old
2199              (not (numberp fetch-old)))
2200         t                               ; Don't remove anything.
2201       (nnheader-nov-delete-outside-range
2202        (if fetch-old (max 1 (- (car articles) fetch-old))
2203          (car articles))
2204        (car (last articles)))
2205       t)
2206
2207     'nov))
2208
2209 (defun gnus-agent-request-article (article group)
2210   "Retrieve ARTICLE in GROUP from the agent cache."
2211   (let* ((gnus-command-method (gnus-find-method-for-group group))
2212          (file (concat
2213                   (gnus-agent-directory)
2214                   (gnus-agent-group-path group) "/"
2215                   (number-to-string article)))
2216          (buffer-read-only nil))
2217     (when (and (file-exists-p file)
2218                (> (nth 7 (file-attributes file)) 0))
2219       (erase-buffer)
2220       (gnus-kill-all-overlays)
2221       (let ((coding-system-for-read gnus-cache-coding-system))
2222         (insert-file-contents file))
2223       t)))
2224
2225 (defun gnus-agent-regenerate-group (group &optional reread)
2226   "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."
2227   (gnus-message 5 "Regenerating in %s" group)
2228   (let* ((gnus-command-method (or gnus-command-method
2229                                   (gnus-find-method-for-group group)))
2230          (file (gnus-agent-article-name ".overview" group))
2231          (dir (file-name-directory file))
2232          point 
2233          (downloaded (if (file-exists-p dir)
2234                          (sort (mapcar (lambda (name) (string-to-int name))
2235                                        (directory-files dir nil "^[0-9]+$" t))
2236                                '>)
2237                        (progn (gnus-make-directory dir) nil)))
2238          dl nov-arts
2239          alist header
2240          regenerated)
2241
2242     (mm-with-unibyte-buffer
2243      (if (file-exists-p file)
2244          (let ((nnheader-file-coding-system
2245                 gnus-agent-file-coding-system))
2246            (nnheader-insert-file-contents file)))
2247      (set-buffer-modified-p nil)
2248
2249      ;; Load the article IDs found in the overview file.  As a side-effect, validate the file contents.
2250      (let ((load t))
2251        (while load
2252          (setq load nil)
2253          (goto-char (point-min))
2254          (while (< (point) (point-max))
2255            (cond ((looking-at "[0-9]+\\b")
2256                   (push (read (current-buffer)) nov-arts)
2257                   (forward-line 1)
2258                   (let ((l1 (car nov-arts))
2259                         (l2 (cadr nov-arts)))
2260                     (cond ((not l2)
2261                            nil)
2262                           ((< l1 l2)
2263                            ;; Don't sort now as I haven't verified that every line begins with a number
2264                            (setq load t))
2265                           ((= l1 l2)
2266                            (forward-line -1)
2267                            (gnus-delete-line)
2268                            (pop nov-arts)))))
2269                  (t
2270                   (gnus-delete-line))))
2271          (if load
2272              (progn (sort-numeric-fields 1 (point-min) (point-max))
2273                     (setq nov-arts nil)))))
2274      (gnus-agent-check-overview-buffer)
2275
2276      ;; Construct a new article alist whose nodes match every header in the .overview file.  
2277      ;; As a side-effect, missing headers are reconstructed from the downloaded article file.
2278      (while (or downloaded nov-arts)
2279        (cond ((and downloaded 
2280                    (or (not nov-arts)
2281                        (> (car downloaded) (car nov-arts))))
2282               ;; This entry is missing from the overview file
2283               (gnus-message 6 "Regenerating NOV %s %d..." group (car downloaded))
2284               (let ((file (concat dir (number-to-string (car downloaded)))))
2285                 (mm-with-unibyte-buffer
2286                  (nnheader-insert-file-contents file)
2287                  (nnheader-remove-body)
2288                  (setq header (nnheader-parse-naked-head)))
2289                 (mail-header-set-number header (car downloaded))
2290                 (if nov-arts
2291                     (let ((key (concat "^" (int-to-string (car nov-arts)) "\t")))
2292                       (or (re-search-backward key nil t)
2293                           (re-search-forward key))
2294                       (forward-line 1))
2295                   (goto-char (point-min)))
2296                 (nnheader-insert-nov header))
2297               (setq nov-arts (cons (car downloaded) nov-arts)))
2298              ((eq (car downloaded) (car nov-arts))
2299               ;; This entry in the overview has been downloaded
2300               (push (cons (car downloaded) (time-to-days (nth 5 (file-attributes (concat dir (number-to-string (car downloaded))))))) alist)
2301               (pop downloaded)
2302               (pop nov-arts))
2303              (t
2304               ;; This entry in the overview has not been downloaded
2305               (push (cons (car nov-arts) nil) alist)
2306               (pop nov-arts))))
2307
2308      ;; When gnus-agent-consider-all-articles is set, gnus-agent-regenerate-group should NOT remove article IDs 
2309      ;; from the alist.  Those IDs serve as markers to indicate that an attempt has been made to fetch that 
2310      ;; article's header.
2311
2312      ;; When gnus-agent-consider-all-articles is NOT set, gnus-agent-regenerate-group can remove the article
2313      ;; ID of every article (with the exception of the last ID in the list - it's special) that no longer appears in the overview.
2314      ;; In this situtation, the last article ID in the list implies that it, and every article ID preceeding it, 
2315      ;; have been fetched from the server.
2316      (if gnus-agent-consider-all-articles
2317          ;; Restore all article IDs that were not found in the overview file.
2318          (let* ((n (cons nil alist))
2319                 (merged n)
2320                 (o (gnus-agent-load-alist group)))
2321            (while o
2322              (let ((nID (caadr n))
2323                    (oID (caar o)))
2324                (cond ((not nID)
2325                       (setq n (setcdr n (list (list oID))))
2326                       (pop o))
2327                      ((< oID nID)
2328                       (setcdr n (cons (list oID) (cdr n)))
2329                       (pop o))
2330                      ((= oID nID)
2331                       (pop o)
2332                       (pop n))
2333                      (t
2334                       (pop n)))))
2335            (setq alist (cdr merged)))
2336        ;; Restore the last article ID if it is not already in the new alist
2337        (let ((n (last alist))
2338              (o (last (gnus-agent-load-alist group))))
2339          (cond ((not n)
2340                 (when o
2341                   (push (cons (caar o) nil) alist)))
2342                ((< (caar n) (caar o))
2343                 (setcdr n (list (car o)))))))
2344                      
2345      (if (setq regenerated (buffer-modified-p))
2346          (let ((coding-system-for-write gnus-agent-file-coding-system))
2347            (write-region (point-min) (point-max) file nil 'silent)))
2348      )
2349
2350     (setq regenerated (or regenerated
2351                           (and reread gnus-agent-article-alist)
2352                           (not (equal alist gnus-agent-article-alist)))
2353           )
2354
2355     (setq gnus-agent-article-alist alist)
2356  
2357     (when regenerated
2358       (gnus-agent-save-alist group))
2359
2360     (when (and reread gnus-agent-article-alist)
2361       (gnus-make-ascending-articles-unread
2362        group
2363        (delq nil (mapcar (function (lambda (c)
2364                                      (cond ((eq reread t)
2365                                             (car c))
2366                                            ((cdr c)
2367                                             (car c)))))
2368                          gnus-agent-article-alist)))
2369
2370       (when (gnus-buffer-live-p gnus-group-buffer)
2371         (gnus-group-update-group group t)
2372         (sit-for 0))
2373       )
2374
2375     regenerated))
2376
2377 ;;;###autoload
2378 (defun gnus-agent-regenerate (&optional clean reread)
2379   "Regenerate all agent covered files.
2380 If CLEAN, don't read existing active files."
2381   (interactive "P")
2382   (let (regenerated)
2383     (gnus-message 4 "Regenerating Gnus agent files...")
2384     (dolist (gnus-command-method gnus-agent-covered-methods)
2385       (let ((active-file (gnus-agent-lib-file "active"))
2386             active-hashtb active-changed
2387             point)
2388         (gnus-make-directory (file-name-directory active-file))
2389         (if clean
2390             (setq active-hashtb (gnus-make-hashtable 1000))
2391           (mm-with-unibyte-buffer
2392            (if (file-exists-p active-file)
2393                (let ((nnheader-file-coding-system
2394                       gnus-agent-file-coding-system))
2395                  (nnheader-insert-file-contents active-file))
2396              (setq active-changed t))
2397            (gnus-active-to-gnus-format
2398             nil (setq active-hashtb
2399                       (gnus-make-hashtable
2400                        (count-lines (point-min) (point-max)))))))
2401         (dolist (group (gnus-groups-from-server gnus-command-method))
2402           (setq regenerated (or (gnus-agent-regenerate-group group reread)
2403                                 regenerated))
2404           (let ((min (or (caar gnus-agent-article-alist) 1))
2405                 (max (or (caar (last gnus-agent-article-alist)) 0))
2406                 (active (gnus-gethash-safe (gnus-group-real-name group)
2407                                            active-hashtb))
2408                 (read (gnus-info-read (gnus-get-info group))))
2409             (if (not active)
2410                 (progn
2411                   (setq active (cons min max)
2412                         active-changed t)
2413                   (gnus-sethash group active active-hashtb))
2414               (when (> (car active) min)
2415                 (setcar active min)
2416                 (setq active-changed t))
2417               (when (< (cdr active) max)
2418                 (setcdr active max)
2419                 (setq active-changed t)))))
2420         (when active-changed
2421           (setq regenerated t)
2422           (gnus-message 4 "Regenerate %s" active-file)
2423           (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2424             (gnus-write-active-file active-file active-hashtb)))))
2425     (gnus-message 4 "Regenerating Gnus agent files...done")
2426     regenerated))
2427
2428 (defun gnus-agent-go-online (&optional force)
2429   "Switch servers into online status."
2430   (interactive (list t))
2431   (dolist (server gnus-opened-servers)
2432     (when (eq (nth 1 server) 'offline)
2433       (if (if (eq force 'ask)
2434               (gnus-y-or-n-p
2435                (format "Switch %s:%s into online status? "
2436                        (caar server) (cadar server)))
2437             force)
2438           (setcar (nthcdr 1 server) 'close)))))
2439
2440 (defun gnus-agent-toggle-group-plugged (group)
2441   "Toggle the status of the server of the current group."
2442   (interactive (list (gnus-group-group-name)))
2443   (let* ((method (gnus-find-method-for-group group))
2444          (status (cadr (assoc method gnus-opened-servers))))
2445     (if (eq status 'offline)
2446         (gnus-server-set-status method 'closed)
2447       (gnus-close-server method)
2448       (gnus-server-set-status method 'offline))
2449     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2450              (if (eq status 'offline) 'offline 'online)
2451              (if (eq status 'offline) 'online 'offline))))
2452
2453 (provide 'gnus-agent)
2454
2455 ;;; gnus-agent.el ends here