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