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