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