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