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