c80cbb1eb68f22e2fb75dc0515d04e3d06dc099f
[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     (ignore-errors
1735         (nnheader-insert-file-contents file)
1736         (goto-char (point-min))
1737         (let ((alist (read (current-buffer)))
1738               (version (condition-case nil (read (current-buffer))
1739                          (end-of-file 0)))
1740               changed-version)
1741
1742           (cond
1743            ((= version 0)
1744             (let ((inhibit-quit t)
1745                   entry)
1746               (gnus-agent-open-history)
1747               (set-buffer (gnus-agent-history-buffer))
1748               (goto-char (point-min))
1749               (while (not (eobp))
1750                 (if (and (looking-at
1751                           "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1752                          (string= (match-string 2)
1753                                   gnus-agent-read-agentview)
1754                          (setq entry (assoc (string-to-number (match-string 3)) alist)))
1755                     (setcdr entry (string-to-number (match-string 1))))
1756                 (forward-line 1))
1757               (gnus-agent-close-history)
1758               (setq changed-version t)))
1759            ((= version 1)
1760             (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1761            ((= version 2)
1762             (let (uncomp)
1763               (mapcar
1764                (lambda (comp-list)
1765                  (let ((state (car comp-list))
1766                        (sequence (gnus-uncompress-sequence
1767                                   (cdr comp-list))))
1768                    (mapcar (lambda (article-id)
1769                              (setq uncomp (cons (cons article-id state) uncomp)))
1770                            sequence)))
1771                alist)
1772               (setq alist (sort uncomp 'car-less-than-car)))))
1773           (when changed-version
1774             (let ((gnus-agent-article-alist alist))
1775               (gnus-agent-save-alist gnus-agent-read-agentview)))
1776         alist))))
1777
1778 (defun gnus-agent-save-alist (group &optional articles state)
1779   "Save the article-state alist for GROUP."
1780   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1781          (prev (cons nil gnus-agent-article-alist))
1782          (all prev)
1783          print-level print-length item article)
1784     (while (setq article (pop articles))
1785       (while (and (cdr prev)
1786                   (< (caadr prev) article))
1787         (setq prev (cdr prev)))
1788       (cond
1789        ((not (cdr prev))
1790         (setcdr prev (list (cons article state))))
1791        ((> (caadr prev) article)
1792         (setcdr prev (cons (cons article state) (cdr prev))))
1793        ((= (caadr prev) article)
1794         (setcdr (cadr prev) state)))
1795       (setq prev (cdr prev)))
1796     (setq gnus-agent-article-alist (cdr all))
1797
1798     (gnus-agent-set-local group 
1799                           (caar gnus-agent-article-alist) 
1800                           (caar (last gnus-agent-article-alist)))
1801
1802     (gnus-make-directory (gnus-agent-article-name "" group))
1803     (with-temp-file (gnus-agent-article-name ".agentview" group)
1804       (cond ((eq gnus-agent-article-alist-save-format 1)
1805              (princ gnus-agent-article-alist (current-buffer)))
1806             ((eq gnus-agent-article-alist-save-format 2)
1807              (let ((compressed nil))
1808                (mapcar (lambda (pair)
1809                          (let* ((article-id (car pair))
1810                                 (day-of-download (cdr pair))
1811                                 (comp-list (assq day-of-download compressed)))
1812                            (if comp-list
1813                                (setcdr comp-list
1814                                        (cons article-id (cdr comp-list)))
1815                              (setq compressed
1816                                    (cons (list day-of-download article-id)
1817                                          compressed)))
1818                            nil)) gnus-agent-article-alist)
1819                (mapcar (lambda (comp-list)
1820                          (setcdr comp-list
1821                                  (gnus-compress-sequence
1822                                   (nreverse (cdr comp-list)))))
1823                        compressed)
1824                (princ compressed (current-buffer)))))
1825       (insert "\n")
1826       (princ gnus-agent-article-alist-save-format (current-buffer))
1827       (insert "\n"))))
1828
1829 (defvar gnus-agent-article-local nil)
1830 (defvar gnus-agent-file-loading-local nil)
1831
1832 (defun gnus-agent-load-local (&optional method)
1833   "Load the METHOD'S local file.  The local file contains min/max
1834 article counts for each of the method's subscribed groups."
1835   (let ((gnus-command-method (or method gnus-command-method)))
1836     (setq gnus-agent-article-local
1837           (gnus-cache-file-contents
1838            (gnus-agent-lib-file "local")
1839            'gnus-agent-file-loading-local
1840            'gnus-agent-read-and-cache-local))))
1841
1842 (defun gnus-agent-read-and-cache-local (file)
1843   "Load and read FILE then bind its contents to
1844 gnus-agent-article-local.  If that variable had `dirty' (also known as
1845 modified) original contents, they are first saved to their own file."
1846
1847   (if (and gnus-agent-article-local
1848            (symbol-value (intern "+dirty" gnus-agent-article-local)))
1849       (gnus-agent-save-local))
1850   (gnus-agent-read-local file))
1851
1852 (defun gnus-agent-read-local (file)
1853   "Load FILE and do a `read' there."
1854   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min) 
1855                                                       (point-max))))
1856         (line 1))
1857     (with-temp-buffer
1858       (condition-case nil
1859           (nnheader-insert-file-contents file)
1860         (file-error))
1861
1862       (goto-char (point-min))
1863       ;; Skip any comments at the beginning of the file (the only place where they may appear)
1864       (while (= (following-char) ?\;)
1865         (forward-line 1)
1866         (setq line (1+ line)))
1867
1868       (while (not (eobp))
1869         (condition-case err
1870             (let (group 
1871                   min
1872                   max
1873                   (cur (current-buffer)))
1874               (setq group (read cur)
1875                     min (read cur)
1876                     max (read cur))
1877
1878               (when (stringp group)
1879                 (setq group (intern group my-obarray)))
1880
1881               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
1882               (set group (cons (+ 0 min) (+ 0 max))))
1883           (error
1884            (gnus-message 3 "Warning - invalid agent local: %s on line %d: "
1885                          file line (error-message-string err))))
1886         (forward-line 1)
1887         (setq line (1+ line))))
1888       
1889     (set (intern "+dirty" my-obarray) nil)
1890     (set (intern "+method" my-obarray) gnus-command-method)
1891     my-obarray))
1892
1893 (defun gnus-agent-save-local (&optional force)
1894   "Save gnus-agent-article-local under it method's agent.lib directory."
1895   (let ((my-obarray gnus-agent-article-local))
1896     (when (and my-obarray
1897                (or force (symbol-value (intern "+dirty" my-obarray))))
1898       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
1899              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
1900              (dest (gnus-agent-lib-file "local")))
1901         (gnus-make-directory (gnus-agent-lib-file ""))
1902         (with-temp-file dest
1903           (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
1904                 (file-name-coding-system nnmail-pathname-coding-system)
1905                 (coding-system-for-write
1906                  gnus-agent-file-coding-system)
1907                 print-level print-length item article
1908                 (standard-output (current-buffer)))
1909             (mapatoms (lambda (symbol)
1910                         (cond ((not (boundp symbol))
1911                                nil)
1912                               ((member (symbol-name symbol) '("+dirty" "+method"))
1913                                nil)
1914                               (t
1915                                (prin1 symbol)
1916                                (let ((range (symbol-value symbol)))
1917                                  (princ " ")
1918                                  (princ (car range))
1919                                  (princ " ")
1920                                  (princ (cdr range))
1921                                  (princ "\n"))))) 
1922                       my-obarray)))))))
1923
1924 (defun gnus-agent-get-local (group)
1925   (let* ((gmane (gnus-group-real-name group))
1926          (gnus-command-method (gnus-find-method-for-group group))
1927          (local (gnus-agent-load-local))
1928          (symb (intern gmane local))
1929          (minmax (and (boundp symb) (symbol-value symb))))
1930     (unless minmax
1931       ;; Bind these so that gnus-agent-load-alist doesn't change the
1932       ;; current alist (i.e. gnus-agent-article-alist)
1933       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
1934              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
1935              (alist (gnus-agent-load-alist group)))
1936         (when alist
1937           (setq minmax
1938                 (cons (caar alist)
1939                       (caar (last alist))))
1940           (gnus-agent-set-local group (car minmax) (cdr minmax) 
1941                                 gmane gnus-command-method local))))
1942     minmax))
1943
1944 (defun gnus-agent-set-local (group min max &optional gmane method local)
1945   (let* ((gmane (or gmane (gnus-group-real-name group)))
1946          (gnus-command-method (or method (gnus-find-method-for-group group)))
1947          (local (or local (gnus-agent-load-local)))
1948          (symb (intern gmane local))
1949          (minmax (and (boundp symb) (symbol-value symb))))
1950     
1951     (if (cond ((and minmax
1952                     (or (not (eq min (car minmax)))
1953                         (not (eq max (cdr minmax)))))
1954                (setcar minmax min)
1955                (setcdr minmax max)
1956                t)
1957               (minmax
1958                nil)
1959               ((and min max)
1960                (set symb (cons min max))
1961                t))
1962         (set (intern "+dirty" local) t))))
1963
1964 (defun gnus-agent-article-name (article group)
1965   (expand-file-name article
1966                     (file-name-as-directory
1967                      (gnus-agent-group-pathname group))))
1968
1969 (defun gnus-agent-batch-confirmation (msg)
1970   "Show error message and return t."
1971   (gnus-message 1 msg)
1972   t)
1973
1974 ;;;###autoload
1975 (defun gnus-agent-batch-fetch ()
1976   "Start Gnus and fetch session."
1977   (interactive)
1978   (gnus)
1979   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1980     (gnus-agent-fetch-session))
1981   (gnus-group-exit))
1982
1983 (defun gnus-agent-fetch-session ()
1984   "Fetch all articles and headers that are eligible for fetching."
1985   (interactive)
1986   (unless gnus-agent-covered-methods
1987     (error "No servers are covered by the Gnus agent"))
1988   (unless gnus-plugged
1989     (error "Can't fetch articles while Gnus is unplugged"))
1990   (let ((methods (gnus-agent-covered-methods))
1991         groups group gnus-command-method)
1992     (save-excursion
1993       (while methods
1994         (setq gnus-command-method (car methods))
1995         (when (and (or (gnus-server-opened gnus-command-method)
1996                        (gnus-open-server gnus-command-method))
1997                    (gnus-online gnus-command-method))
1998           (setq groups (gnus-groups-from-server (car methods)))
1999           (gnus-agent-with-fetch
2000             (while (setq group (pop groups))
2001               (when (<= (gnus-group-level group)
2002                         gnus-agent-handle-level)
2003                 (if (or debug-on-error debug-on-quit)
2004                     (gnus-agent-fetch-group-1
2005                      group gnus-command-method)
2006                   (condition-case err
2007                       (gnus-agent-fetch-group-1
2008                        group gnus-command-method)
2009                     (error
2010                      (unless (funcall gnus-agent-confirmation-function
2011                                       (format "Error %s.  Continue? "
2012                                               (error-message-string err)))
2013                        (error "Cannot fetch articles into the Gnus agent")))
2014                     (quit
2015                      (unless (funcall gnus-agent-confirmation-function
2016                                       (format
2017                                        "Quit fetching session %s.  Continue? "
2018                                        (error-message-string err)))
2019                        (signal 'quit
2020                                "Cannot fetch articles into the Gnus agent")))))))))
2021         (setq methods (cdr methods)))
2022       (gnus-run-hooks 'gnus-agent-fetched-hook)
2023       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2024
2025 (defun gnus-agent-fetch-group-1 (group method)
2026   "Fetch GROUP."
2027   (let ((gnus-command-method method)
2028         (gnus-newsgroup-name group)
2029         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2030         (gnus-newsgroup-headers gnus-newsgroup-headers)
2031         (gnus-newsgroup-scored gnus-newsgroup-scored)
2032         (gnus-use-cache gnus-use-cache)
2033         (gnus-summary-expunge-below gnus-summary-expunge-below)
2034         (gnus-summary-mark-below gnus-summary-mark-below)
2035         (gnus-orphan-score gnus-orphan-score)
2036         ;; Maybe some other gnus-summary local variables should also
2037         ;; be put here.
2038
2039         gnus-headers
2040         gnus-score
2041         articles arts
2042         category predicate info marks score-param
2043         )
2044     (unless (gnus-check-group group)
2045       (error "Can't open server for %s" group))
2046
2047     ;; Fetch headers.
2048     (when (or gnus-newsgroup-active
2049               (gnus-active group)
2050               (gnus-activate-group group))
2051       (let ((marked-articles gnus-newsgroup-downloadable))
2052         ;; Identify the articles marked for download
2053         (unless gnus-newsgroup-active
2054           ;; The variable gnus-newsgroup-active was selected as I need
2055           ;; a gnus-summary local variable that is NOT bound to any
2056           ;; value (its global value should default to nil).
2057           (dolist (mark gnus-agent-download-marks)
2058             (let ((arts (cdr (assq mark (gnus-info-marks
2059                                          (setq info (gnus-get-info group)))))))
2060               (when arts
2061                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2062                                              marked-articles))
2063                 ))))
2064         (setq marked-articles (sort marked-articles '<))
2065
2066         ;; Fetch any new articles from the server
2067         (setq articles (gnus-agent-fetch-headers group))
2068
2069         ;; Merge new articles with marked
2070         (setq articles (sort (append marked-articles articles) '<))
2071
2072         (when articles
2073           ;; Parse them and see which articles we want to fetch.
2074           (setq gnus-newsgroup-dependencies
2075                 (or gnus-newsgroup-dependencies
2076                     (make-vector (length articles) 0)))
2077           (setq gnus-newsgroup-headers
2078                 (or gnus-newsgroup-headers
2079                     (gnus-get-newsgroup-headers-xover articles nil nil
2080                                                       group)))
2081           ;; `gnus-agent-overview-buffer' may be killed for
2082           ;; timeout reason.  If so, recreate it.
2083           (gnus-agent-create-buffer)
2084
2085           ;; Figure out how to select articles in this group
2086           (setq category (gnus-group-category group))
2087
2088           (setq predicate
2089                 (gnus-get-predicate
2090                  (gnus-agent-find-parameter group 'agent-predicate)))
2091
2092           ;; If the selection predicate requires scoring, score each header
2093           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2094             (let ((score-param
2095                    (gnus-agent-find-parameter group 'agent-score-file)))
2096               ;; Translate score-param into real one
2097               (cond
2098                ((not score-param))
2099                ((eq score-param 'file)
2100                 (setq score-param (gnus-all-score-files group)))
2101                ((stringp (car score-param)))
2102                (t
2103                 (setq score-param (list (list score-param)))))
2104               (when score-param
2105                 (gnus-score-headers score-param))))
2106
2107           (unless (and (eq predicate 'gnus-agent-false)
2108                        (not marked-articles))
2109             (let ((arts (list nil)))
2110               (let ((arts-tail arts)
2111                     (alist (gnus-agent-load-alist group))
2112                     (marked-articles marked-articles)
2113                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2114                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2115                   (let ((num (mail-header-number gnus-headers)))
2116                     ;; Determine if this article is already in the cache
2117                     (while (and alist
2118                                 (> num (caar alist)))
2119                       (setq alist (cdr alist)))
2120
2121                     (unless (and (eq num (caar alist))
2122                                  (cdar alist))
2123
2124                       ;; Determine if this article was marked for download.
2125                       (while (and marked-articles
2126                                   (> num (car marked-articles)))
2127                         (setq marked-articles
2128                               (cdr marked-articles)))
2129
2130                       ;; When this article is marked, or selected by the
2131                       ;; predicate, add it to the download list
2132                       (when (or (eq num (car marked-articles))
2133                                 (let ((gnus-score
2134                                        (or (cdr
2135                                             (assq num gnus-newsgroup-scored))
2136                                            gnus-summary-default-score))
2137                                       (gnus-agent-long-article
2138                                        (gnus-agent-find-parameter
2139                                         group 'agent-long-article))
2140                                       (gnus-agent-short-article
2141                                        (gnus-agent-find-parameter
2142                                         group 'agent-short-article))
2143                                       (gnus-agent-low-score
2144                                        (gnus-agent-find-parameter
2145                                         group 'agent-low-score))
2146                                       (gnus-agent-high-score
2147                                        (gnus-agent-find-parameter
2148                                         group 'agent-high-score))
2149                                       (gnus-agent-expire-days
2150                                        (gnus-agent-find-parameter
2151                                         group 'agent-days-until-old)))
2152                                   (funcall predicate)))
2153                         (gnus-agent-append-to-list arts-tail num))))))
2154
2155               (let (fetched-articles)
2156                 ;; Fetch all selected articles
2157                 (setq gnus-newsgroup-undownloaded
2158                       (gnus-sorted-ndifference
2159                        gnus-newsgroup-undownloaded
2160                        (setq fetched-articles
2161                              (if (cdr arts)
2162                                  (gnus-agent-fetch-articles group (cdr arts))
2163                                nil))))
2164
2165                 (let ((unfetched-articles
2166                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2167                   (if gnus-newsgroup-active
2168                       ;; Update the summary buffer
2169                       (progn
2170                         (dolist (article marked-articles)
2171                           (gnus-summary-set-agent-mark article t))
2172                         (dolist (article fetched-articles)
2173                           (if gnus-agent-mark-unread-after-downloaded
2174                               (gnus-summary-mark-article
2175                                article gnus-unread-mark))
2176                           (when (gnus-summary-goto-subject article nil t)
2177                             (gnus-summary-update-download-mark article)))
2178                         (dolist (article unfetched-articles)
2179                           (gnus-summary-mark-article
2180                            article gnus-canceled-mark)))
2181
2182                     ;; Update the group buffer.
2183
2184                     ;; When some, or all, of the marked articles came
2185                     ;; from the download mark.  Remove that mark.  I
2186                     ;; didn't do this earlier as I only want to remove
2187                     ;; the marks after the fetch is completed.
2188
2189                     (dolist (mark gnus-agent-download-marks)
2190                       (when (eq mark 'download)
2191                         (let ((marked-arts
2192                                (assq mark (gnus-info-marks
2193                                            (setq info (gnus-get-info group))))))
2194                           (when (cdr marked-arts)
2195                             (setq marks
2196                                   (delq marked-arts (gnus-info-marks info)))
2197                             (gnus-info-set-marks info marks)))))
2198                     (let ((read (gnus-info-read
2199                                  (or info (setq info (gnus-get-info group))))))
2200                       (gnus-info-set-read
2201                        info (gnus-add-to-range read unfetched-articles)))
2202
2203                     (gnus-group-update-group group t)
2204                     (sit-for 0)
2205
2206                     (gnus-dribble-enter
2207                      (concat "(gnus-group-set-info '"
2208                              (gnus-prin1-to-string info)
2209                              ")"))))))))))))
2210
2211 ;;;
2212 ;;; Agent Category Mode
2213 ;;;
2214
2215 (defvar gnus-category-mode-hook nil
2216   "Hook run in `gnus-category-mode' buffers.")
2217
2218 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2219   "Format of category lines.
2220
2221 Valid specifiers include:
2222 %c  Topic name (string)
2223 %g  The number of groups in the topic (integer)
2224
2225 General format specifiers can also be used.  See Info node
2226 `(gnus)Formatting Variables'.")
2227
2228 (defvar gnus-category-mode-line-format "Gnus: %%b"
2229   "The format specification for the category mode line.")
2230
2231 (defvar gnus-agent-predicate 'false
2232   "The selection predicate used when no other source is available.")
2233
2234 (defvar gnus-agent-short-article 100
2235   "Articles that have fewer lines than this are short.")
2236
2237 (defvar gnus-agent-long-article 200
2238   "Articles that have more lines than this are long.")
2239
2240 (defvar gnus-agent-low-score 0
2241   "Articles that have a score lower than this have a low score.")
2242
2243 (defvar gnus-agent-high-score 0
2244   "Articles that have a score higher than this have a high score.")
2245
2246
2247 ;;; Internal variables.
2248
2249 (defvar gnus-category-buffer "*Agent Category*")
2250
2251 (defvar gnus-category-line-format-alist
2252   `((?c gnus-tmp-name ?s)
2253     (?g gnus-tmp-groups ?d)))
2254
2255 (defvar gnus-category-mode-line-format-alist
2256   `((?u user-defined ?s)))
2257
2258 (defvar gnus-category-line-format-spec nil)
2259 (defvar gnus-category-mode-line-format-spec nil)
2260
2261 (defvar gnus-category-mode-map nil)
2262 (put 'gnus-category-mode 'mode-class 'special)
2263
2264 (unless gnus-category-mode-map
2265   (setq gnus-category-mode-map (make-sparse-keymap))
2266   (suppress-keymap gnus-category-mode-map)
2267
2268   (gnus-define-keys gnus-category-mode-map
2269     "q" gnus-category-exit
2270     "k" gnus-category-kill
2271     "c" gnus-category-copy
2272     "a" gnus-category-add
2273     "e" gnus-agent-customize-category
2274     "p" gnus-category-edit-predicate
2275     "g" gnus-category-edit-groups
2276     "s" gnus-category-edit-score
2277     "l" gnus-category-list
2278
2279     "\C-c\C-i" gnus-info-find-node
2280     "\C-c\C-b" gnus-bug))
2281
2282 (defvar gnus-category-menu-hook nil
2283   "*Hook run after the creation of the menu.")
2284
2285 (defun gnus-category-make-menu-bar ()
2286   (gnus-turn-off-edit-menu 'category)
2287   (unless (boundp 'gnus-category-menu)
2288     (easy-menu-define
2289      gnus-category-menu gnus-category-mode-map ""
2290      '("Categories"
2291        ["Add" gnus-category-add t]
2292        ["Kill" gnus-category-kill t]
2293        ["Copy" gnus-category-copy t]
2294        ["Edit category" gnus-agent-customize-category t]
2295        ["Edit predicate" gnus-category-edit-predicate t]
2296        ["Edit score" gnus-category-edit-score t]
2297        ["Edit groups" gnus-category-edit-groups t]
2298        ["Exit" gnus-category-exit t]))
2299
2300     (gnus-run-hooks 'gnus-category-menu-hook)))
2301
2302 (defun gnus-category-mode ()
2303   "Major mode for listing and editing agent categories.
2304
2305 All normal editing commands are switched off.
2306 \\<gnus-category-mode-map>
2307 For more in-depth information on this mode, read the manual
2308 \(`\\[gnus-info-find-node]').
2309
2310 The following commands are available:
2311
2312 \\{gnus-category-mode-map}"
2313   (interactive)
2314   (when (gnus-visual-p 'category-menu 'menu)
2315     (gnus-category-make-menu-bar))
2316   (kill-all-local-variables)
2317   (gnus-simplify-mode-line)
2318   (setq major-mode 'gnus-category-mode)
2319   (setq mode-name "Category")
2320   (gnus-set-default-directory)
2321   (setq mode-line-process nil)
2322   (use-local-map gnus-category-mode-map)
2323   (buffer-disable-undo)
2324   (setq truncate-lines t)
2325   (setq buffer-read-only t)
2326   (gnus-run-hooks 'gnus-category-mode-hook))
2327
2328 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2329
2330 (defun gnus-category-insert-line (category)
2331   (let* ((gnus-tmp-name (format "%s" (car category)))
2332          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2333     (beginning-of-line)
2334     (gnus-add-text-properties
2335      (point)
2336      (prog1 (1+ (point))
2337        ;; Insert the text.
2338        (eval gnus-category-line-format-spec))
2339      (list 'gnus-category gnus-tmp-name))))
2340
2341 (defun gnus-enter-category-buffer ()
2342   "Go to the Category buffer."
2343   (interactive)
2344   (gnus-category-setup-buffer)
2345   (gnus-configure-windows 'category)
2346   (gnus-category-prepare))
2347
2348 (defun gnus-category-setup-buffer ()
2349   (unless (get-buffer gnus-category-buffer)
2350     (save-excursion
2351       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2352       (gnus-category-mode))))
2353
2354 (defun gnus-category-prepare ()
2355   (gnus-set-format 'category-mode)
2356   (gnus-set-format 'category t)
2357   (let ((alist gnus-category-alist)
2358         (buffer-read-only nil))
2359     (erase-buffer)
2360     (while alist
2361       (gnus-category-insert-line (pop alist)))
2362     (goto-char (point-min))
2363     (gnus-category-position-point)))
2364
2365 (defun gnus-category-name ()
2366   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2367       (error "No category on the current line")))
2368
2369 (defun gnus-category-read ()
2370   "Read the category alist."
2371   (setq gnus-category-alist
2372         (or
2373          (with-temp-buffer
2374            (ignore-errors
2375             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2376             (goto-char (point-min))
2377             ;; This code isn't temp, it will be needed so long as
2378             ;; anyone may be migrating from an older version.
2379
2380             ;; Once we're certain that people will not revert to an
2381             ;; earlier version, we can take out the old-list code in
2382             ;; gnus-category-write.
2383             (let* ((old-list (read (current-buffer)))
2384                    (new-list (ignore-errors (read (current-buffer)))))
2385               (if new-list
2386                   new-list
2387                 ;; Convert from a positional list to an alist.
2388                 (mapcar
2389                  (lambda (c)
2390                    (setcdr c
2391                            (delq nil
2392                                  (gnus-mapcar
2393                                   (lambda (valu symb)
2394                                     (if valu
2395                                         (cons symb valu)))
2396                                   (cdr c)
2397                                   '(agent-predicate agent-score-file agent-groups))))
2398                    c)
2399                  old-list)))))
2400          (list (gnus-agent-cat-make 'default 'short)))))
2401
2402 (defun gnus-category-write ()
2403   "Write the category alist."
2404   (setq gnus-category-predicate-cache nil
2405         gnus-category-group-cache nil)
2406   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2407   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2408     ;; This prin1 is temporary.  It exists so that people can revert
2409     ;; to an earlier version of gnus-agent.
2410     (prin1 (mapcar (lambda (c)
2411               (list (car c)
2412                     (cdr (assoc 'agent-predicate c))
2413                     (cdr (assoc 'agent-score-file c))
2414                     (cdr (assoc 'agent-groups c))))
2415                    gnus-category-alist)
2416            (current-buffer))
2417     (newline)
2418     (prin1 gnus-category-alist (current-buffer))))
2419
2420 (defun gnus-category-edit-predicate (category)
2421   "Edit the predicate for CATEGORY."
2422   (interactive (list (gnus-category-name)))
2423   (let ((info (assq category gnus-category-alist)))
2424     (gnus-edit-form
2425      (gnus-agent-cat-predicate info)
2426      (format "Editing the select predicate for category %s" category)
2427      `(lambda (predicate)
2428         ;; Avoid run-time execution of setf form
2429         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2430         ;;       predicate)
2431         ;; use its expansion instead:
2432         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2433                                      'agent-predicate predicate)
2434
2435         (gnus-category-write)
2436         (gnus-category-list)))))
2437
2438 (defun gnus-category-edit-score (category)
2439   "Edit the score expression for CATEGORY."
2440   (interactive (list (gnus-category-name)))
2441   (let ((info (assq category gnus-category-alist)))
2442     (gnus-edit-form
2443      (gnus-agent-cat-score-file info)
2444      (format "Editing the score expression for category %s" category)
2445      `(lambda (score-file)
2446         ;; Avoid run-time execution of setf form
2447         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2448         ;;       score-file)
2449         ;; use its expansion instead:
2450         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2451                                      'agent-score-file score-file)
2452
2453         (gnus-category-write)
2454         (gnus-category-list)))))
2455
2456 (defun gnus-category-edit-groups (category)
2457   "Edit the group list for CATEGORY."
2458   (interactive (list (gnus-category-name)))
2459   (let ((info (assq category gnus-category-alist)))
2460     (gnus-edit-form
2461      (gnus-agent-cat-groups info)
2462      (format "Editing the group list for category %s" category)
2463      `(lambda (groups)
2464         ;; Avoid run-time execution of setf form
2465         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2466         ;;       groups)
2467         ;; use its expansion instead:
2468         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2469                                    groups)
2470
2471         (gnus-category-write)
2472         (gnus-category-list)))))
2473
2474 (defun gnus-category-kill (category)
2475   "Kill the current category."
2476   (interactive (list (gnus-category-name)))
2477   (let ((info (assq category gnus-category-alist))
2478         (buffer-read-only nil))
2479     (gnus-delete-line)
2480     (setq gnus-category-alist (delq info gnus-category-alist))
2481     (gnus-category-write)))
2482
2483 (defun gnus-category-copy (category to)
2484   "Copy the current category."
2485   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2486   (let ((info (assq category gnus-category-alist)))
2487     (push (let ((newcat (gnus-copy-sequence info)))
2488             (setf (gnus-agent-cat-name newcat) to)
2489             (setf (gnus-agent-cat-groups newcat) nil)
2490             newcat)
2491           gnus-category-alist)
2492     (gnus-category-write)
2493     (gnus-category-list)))
2494
2495 (defun gnus-category-add (category)
2496   "Create a new category."
2497   (interactive "SCategory name: ")
2498   (when (assq category gnus-category-alist)
2499     (error "Category %s already exists" category))
2500   (push (gnus-agent-cat-make category)
2501         gnus-category-alist)
2502   (gnus-category-write)
2503   (gnus-category-list))
2504
2505 (defun gnus-category-list ()
2506   "List all categories."
2507   (interactive)
2508   (gnus-category-prepare))
2509
2510 (defun gnus-category-exit ()
2511   "Return to the group buffer."
2512   (interactive)
2513   (kill-buffer (current-buffer))
2514   (gnus-configure-windows 'group t))
2515
2516 ;; To avoid having 8-bit characters in the source file.
2517 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2518
2519 (defvar gnus-category-predicate-alist
2520   '((spam . gnus-agent-spam-p)
2521     (short . gnus-agent-short-p)
2522     (long . gnus-agent-long-p)
2523     (low . gnus-agent-low-scored-p)
2524     (high . gnus-agent-high-scored-p)
2525     (read . gnus-agent-read-p)
2526     (true . gnus-agent-true)
2527     (false . gnus-agent-false))
2528   "Mapping from short score predicate symbols to predicate functions.")
2529
2530 (defun gnus-agent-spam-p ()
2531   "Say whether an article is spam or not."
2532   (unless gnus-agent-spam-hashtb
2533     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2534   (if (not (equal (mail-header-references gnus-headers) ""))
2535       nil
2536     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2537       (prog1
2538           (gnus-gethash string gnus-agent-spam-hashtb)
2539         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2540
2541 (defun gnus-agent-short-p ()
2542   "Say whether an article is short or not."
2543   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2544
2545 (defun gnus-agent-long-p ()
2546   "Say whether an article is long or not."
2547   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2548
2549 (defun gnus-agent-low-scored-p ()
2550   "Say whether an article has a low score or not."
2551   (< gnus-score gnus-agent-low-score))
2552
2553 (defun gnus-agent-high-scored-p ()
2554   "Say whether an article has a high score or not."
2555   (> gnus-score gnus-agent-high-score))
2556
2557 (defun gnus-agent-read-p ()
2558   "Say whether an article is read or not."
2559   (gnus-member-of-range (mail-header-number gnus-headers)
2560                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2561
2562 (defun gnus-category-make-function (predicate)
2563   "Make a function from PREDICATE."
2564   (let ((func (gnus-category-make-function-1 predicate)))
2565     (if (and (= (length func) 1)
2566              (symbolp (car func)))
2567         (car func)
2568       (gnus-byte-compile `(lambda () ,func)))))
2569
2570 (defun gnus-agent-true ()
2571   "Return t."
2572   t)
2573
2574 (defun gnus-agent-false ()
2575   "Return nil."
2576   nil)
2577
2578 (defun gnus-category-make-function-1 (predicate)
2579   "Make a function from PREDICATE."
2580   (cond
2581    ;; Functions are just returned as is.
2582    ((or (symbolp predicate)
2583         (functionp predicate))
2584     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2585            predicate)))
2586    ;; More complex predicate.
2587    ((consp predicate)
2588     `(,(cond
2589         ((memq (car predicate) '(& and))
2590          'and)
2591         ((memq (car predicate) '(| or))
2592          'or)
2593         ((memq (car predicate) gnus-category-not)
2594          'not))
2595       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2596    (t
2597     (error "Unknown predicate type: %s" predicate))))
2598
2599 (defun gnus-get-predicate (predicate)
2600   "Return the function implementing PREDICATE."
2601   (or (cdr (assoc predicate gnus-category-predicate-cache))
2602       (let ((func (gnus-category-make-function predicate)))
2603         (setq gnus-category-predicate-cache
2604               (nconc gnus-category-predicate-cache
2605                      (list (cons predicate func))))
2606         func)))
2607
2608 (defun gnus-predicate-implies-unread (predicate)
2609   "Say whether PREDICATE implies unread articles only.
2610 It is okay to miss some cases, but there must be no false positives.
2611 That is, if this predicate returns true, then indeed the predicate must
2612 return only unread articles."
2613   (eq t (gnus-function-implies-unread-1 
2614          (gnus-category-make-function-1 predicate))))
2615
2616 (defun gnus-function-implies-unread-1 (function)
2617   "Recursively evaluate a predicate function to determine whether it can select
2618 any read articles.  Returns t if the function is known to never
2619 return read articles, nil when it is known to always return read
2620 articles, and t_nil when the function may return both read and unread
2621 articles."
2622   (let ((func (car function))
2623         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2624     (cond ((eq func 'and)
2625            (cond ((memq t args) ; if any argument returns only unread articles
2626                   ;; then that argument constrains the result to only unread articles.
2627                   t)
2628                  ((memq 't_nil args) ; if any argument is indeterminate
2629                   ;; then the result is indeterminate
2630                   't_nil)))
2631           ((eq func 'or)
2632            (cond ((memq nil args) ; if any argument returns read articles
2633                   ;; then that argument ensures that the results includes read articles.
2634                   nil)
2635                  ((memq 't_nil args) ; if any argument is indeterminate
2636                   ;; then that argument ensures that the results are indeterminate
2637                   't_nil)
2638                  (t ; if all arguments return only unread articles
2639                   ;; then the result returns only unread articles
2640                   t)))
2641           ((eq func 'not)
2642            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2643                   ; then the result is indeterminate
2644                   (car args))
2645                  (t ; otherwise
2646                   ; toggle the result to be the opposite of the argument
2647                   (not (car args)))))
2648           ((eq func 'gnus-agent-read-p)
2649            nil) ; The read predicate NEVER returns unread articles
2650           ((eq func 'gnus-agent-false)
2651            t) ; The false predicate returns t as the empty set excludes all read articles
2652           ((eq func 'gnus-agent-true)
2653            nil) ; The true predicate ALWAYS returns read articles
2654           ((catch 'found-match
2655              (let ((alist gnus-category-predicate-alist))
2656                (while alist
2657                  (if (eq func (cdar alist))
2658                      (throw 'found-match t)
2659                    (setq alist (cdr alist))))))
2660            't_nil) ; All other predicates return read and unread articles
2661           (t
2662            (error "Unknown predicate function: %s" function)))))
2663
2664 (defun gnus-group-category (group)
2665   "Return the category GROUP belongs to."
2666   (unless gnus-category-group-cache
2667     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2668     (let ((cs gnus-category-alist)
2669           groups cat)
2670       (while (setq cat (pop cs))
2671         (setq groups (gnus-agent-cat-groups cat))
2672         (while groups
2673           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2674   (or (gnus-gethash group gnus-category-group-cache)
2675       (assq 'default gnus-category-alist)))
2676
2677 (defun gnus-agent-expire-group (group &optional articles force)
2678   "Expire all old articles in GROUP.
2679 If you want to force expiring of certain articles, this function can
2680 take ARTICLES, and FORCE parameters as well.
2681
2682 The articles on which the expiration process runs are selected as follows:
2683   if ARTICLES is null, all read and unmarked articles.
2684   if ARTICLES is t, all articles.
2685   if ARTICLES is a list, just those articles.
2686 FORCE is equivalent to setting the expiration predicates to true."
2687   (interactive
2688    (list (let ((def (or (gnus-group-group-name)
2689                         gnus-newsgroup-name)))
2690            (let ((select (read-string (if def
2691                                           (concat "Group Name ("
2692                                                   def "): ")
2693                                         "Group Name: "))))
2694              (if (and (equal "" select)
2695                       def)
2696                  def
2697                select)))))
2698
2699   (if (not group)
2700       (gnus-agent-expire articles group force)
2701     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2702            ;; expiration statistics of this single group
2703           (gnus-agent-expire-stats (list 0 0 0.0)))
2704       (if (or (not (eq articles t))
2705               (yes-or-no-p
2706                (concat "Are you sure that you want to "
2707                        "expire all articles in " group ".")))
2708           (let ((gnus-command-method (gnus-find-method-for-group group))
2709                 (overview (gnus-get-buffer-create " *expire overview*"))
2710                 orig)
2711             (unwind-protect
2712                 (let ((active-file (gnus-agent-lib-file "active")))
2713                   (when (file-exists-p active-file)
2714                     (with-temp-buffer
2715                       (nnheader-insert-file-contents active-file)
2716                       (gnus-active-to-gnus-format
2717                        gnus-command-method
2718                        (setq orig (gnus-make-hashtable
2719                                    (count-lines (point-min) (point-max))))))
2720                     (save-excursion
2721                       (gnus-agent-expire-group-1
2722                        group overview (gnus-gethash-safe group orig)
2723                        articles force))))
2724               (kill-buffer overview))))
2725       (gnus-message 4 (gnus-agent-expire-done-message)))))
2726
2727 (defun gnus-agent-expire-group-1 (group overview active articles force)
2728   ;; Internal function - requires caller to have set
2729   ;; gnus-command-method, initialized overview buffer, and to have
2730   ;; provided a non-nil active
2731
2732   (let ((dir (gnus-agent-group-pathname group)))
2733     (when (boundp 'gnus-agent-expire-current-dirs)
2734       (set 'gnus-agent-expire-current-dirs 
2735            (cons dir 
2736                  (symbol-value 'gnus-agent-expire-current-dirs))))
2737
2738     (if (and (not force)
2739              (eq 'DISABLE (gnus-agent-find-parameter group 
2740                                                      'agent-enable-expiration)))
2741         (gnus-message 5 "Expiry skipping over %s" group)
2742       (gnus-message 5 "Expiring articles in %s" group)
2743       (gnus-agent-load-alist group)
2744       (let* ((stats (if (boundp 'gnus-agent-expire-stats)
2745                         ;; Use the list provided by my caller
2746                         (symbol-value 'gnus-agent-expire-stats)
2747                       ;; otherwise use my own temporary list
2748                       (list 0 0 0.0)))
2749              (info (gnus-get-info group))
2750              (alist gnus-agent-article-alist)
2751              (day (- (time-to-days (current-time))
2752                      (gnus-agent-find-parameter group 'agent-days-until-old)))
2753              (specials (if (and alist
2754                                 (not force))
2755                            ;; This could be a bit of a problem.  I need to
2756                            ;; keep the last article to avoid refetching
2757                            ;; headers when using nntp in the backend.  At
2758                            ;; the same time, if someone uses a backend
2759                            ;; that supports article moving then I may have
2760                            ;; to remove the last article to complete the
2761                            ;; move.  Right now, I'm going to assume that
2762                            ;; FORCE overrides specials.
2763                            (list (caar (last alist)))))
2764              (unreads ;; Articles that are excluded from the
2765               ;; expiration process
2766               (cond (gnus-agent-expire-all
2767                      ;; All articles are marked read by global decree
2768                      nil)
2769                     ((eq articles t)
2770                      ;; All articles are marked read by function
2771                      ;; parameter
2772                      nil)
2773                     ((not articles)
2774                      ;; Unread articles are marked protected from
2775                      ;; expiration Don't call
2776                      ;; gnus-list-of-unread-articles as it returns
2777                      ;; articles that have not been fetched into the
2778                      ;; agent.
2779                      (ignore-errors
2780                        (gnus-agent-unread-articles group)))
2781                     (t
2782                      ;; All articles EXCEPT those named by the caller
2783                      ;; are protected from expiration
2784                      (gnus-sorted-difference
2785                       (gnus-uncompress-range
2786                        (cons (caar alist)
2787                              (caar (last alist))))
2788                       (sort articles '<)))))
2789              (marked ;; More articles that are excluded from the
2790               ;; expiration process
2791               (cond (gnus-agent-expire-all
2792                      ;; All articles are unmarked by global decree
2793                      nil)
2794                     ((eq articles t)
2795                      ;; All articles are unmarked by function
2796                      ;; parameter
2797                      nil)
2798                     (articles
2799                      ;; All articles may as well be unmarked as the
2800                      ;; unreads list already names the articles we are
2801                      ;; going to keep
2802                      nil)
2803                     (t
2804                      ;; Ticked and/or dormant articles are excluded
2805                      ;; from expiration
2806                      (nconc
2807                       (gnus-uncompress-range
2808                        (cdr (assq 'tick (gnus-info-marks info))))
2809                       (gnus-uncompress-range
2810                        (cdr (assq 'dormant
2811                                   (gnus-info-marks info))))))))
2812              (nov-file (concat dir ".overview"))
2813              (cnt 0)
2814              (completed -1)
2815              dlist
2816              type)
2817
2818         ;; The normal article alist contains elements that look like
2819         ;; (article# .  fetch_date) I need to combine other
2820         ;; information with this list.  For example, a flag indicating
2821         ;; that a particular article MUST BE KEPT.  To do this, I'm
2822         ;; going to transform the elements to look like (article#
2823         ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2824         ;; the process to generate the expired article alist.
2825
2826         ;; Convert the alist elements to (article# fetch_date nil
2827         ;; nil).
2828         (setq dlist (mapcar (lambda (e)
2829                               (list (car e) (cdr e) nil nil)) alist))
2830
2831         ;; Convert the keep lists to elements that look like (article#
2832         ;; nil keep_flag nil) then append it to the expanded dlist
2833         ;; These statements are sorted by ascending precidence of the
2834         ;; keep_flag.
2835         (setq dlist (nconc dlist
2836                            (mapcar (lambda (e)
2837                                      (list e nil 'unread  nil))
2838                                    unreads)))
2839         (setq dlist (nconc dlist
2840                            (mapcar (lambda (e)
2841                                      (list e nil 'marked  nil))
2842                                    marked)))
2843         (setq dlist (nconc dlist
2844                            (mapcar (lambda (e)
2845                                      (list e nil 'special nil))
2846                                    specials)))
2847
2848         (set-buffer overview)
2849         (erase-buffer)
2850         (buffer-disable-undo)
2851         (when (file-exists-p nov-file)
2852           (gnus-message 7 "gnus-agent-expire: Loading overview...")
2853           (nnheader-insert-file-contents nov-file)
2854           (goto-char (point-min))
2855
2856           (let (p)
2857             (while (< (setq p (point)) (point-max))
2858               (condition-case nil
2859                   ;; If I successfully read an integer (the plus zero
2860                   ;; ensures a numeric type), prepend a marker entry
2861                   ;; to the list
2862                   (push (list (+ 0 (read (current-buffer))) nil nil
2863                               (set-marker (make-marker) p))
2864                         dlist)
2865                 (error
2866                  (gnus-message 1 "gnus-agent-expire: read error \
2867 occurred when reading expression at %s in %s.  Skipping to next \
2868 line." (point) nov-file)))
2869               ;; Whether I succeeded, or failed, it doesn't matter.
2870               ;; Move to the next line then try again.
2871               (forward-line 1)))
2872
2873           (gnus-message
2874            7 "gnus-agent-expire: Loading overview... Done"))
2875         (set-buffer-modified-p nil)
2876
2877         ;; At this point, all of the information is in dlist.  The
2878         ;; only problem is that much of it is spread across multiple
2879         ;; entries.  Sort then MERGE!!
2880         (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2881         ;; If two entries have the same article-number then sort by
2882         ;; ascending keep_flag.
2883         (let ((special 0)
2884               (marked 1)
2885               (unread 2))
2886           (setq dlist
2887                 (sort dlist
2888                       (lambda (a b)
2889                         (cond ((< (nth 0 a) (nth 0 b))
2890                                t)
2891                               ((> (nth 0 a) (nth 0 b))
2892                                nil)
2893                               (t
2894                                (let ((a (or (symbol-value (nth 2 a))
2895                                             3))
2896                                      (b (or (symbol-value (nth 2 b))
2897                                             3)))
2898                                  (<= a b))))))))
2899         (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2900         (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2901         (let ((dlist dlist))
2902           (while (cdr dlist)            ; I'm not at the end-of-list
2903             (if (eq (caar dlist) (caadr dlist))
2904                 (let ((first (cdr (car dlist)))
2905                       (secnd (cdr (cadr dlist))))
2906                   (setcar first (or (car first)
2907                                     (car secnd))) ; fetch_date
2908                   (setq first (cdr first)
2909                         secnd (cdr secnd))
2910                   (setcar first (or (car first)
2911                                     (car secnd))) ; Keep_flag
2912                   (setq first (cdr first)
2913                         secnd (cdr secnd))
2914                   (setcar first (or (car first)
2915                                     (car secnd))) ; NOV_entry_marker
2916
2917                   (setcdr dlist (cddr dlist)))
2918               (setq dlist (cdr dlist)))))
2919         (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2920
2921         (let* ((len (float (length dlist)))
2922                (alist (list nil))
2923                (tail-alist alist))
2924           (while dlist
2925             (let ((new-completed (truncate (* 100.0
2926                                               (/ (setq cnt (1+ cnt))
2927                                                  len))))
2928                   message-log-max)
2929               (when (> new-completed completed)
2930                 (setq completed new-completed)
2931                 (gnus-message 7 "%3d%% completed..."  completed)))
2932             (let* ((entry          (car dlist))
2933                    (article-number (nth 0 entry))
2934                    (fetch-date     (nth 1 entry))
2935                    (keep           (nth 2 entry))
2936                    (marker         (nth 3 entry)))
2937
2938               (cond
2939                ;; Kept articles are unread, marked, or special.
2940                (keep
2941                 (gnus-agent-message 10
2942                                     "gnus-agent-expire: %s:%d: Kept %s article%s."
2943                                     group article-number keep (if fetch-date " and file" ""))
2944                 (when fetch-date
2945                   (unless (file-exists-p
2946                            (concat dir (number-to-string
2947                                         article-number)))
2948                     (setf (nth 1 entry) nil)
2949                     (gnus-agent-message 3 "gnus-agent-expire cleared \
2950 download flag on %s:%d as the cached article file is missing."
2951                                         group (caar dlist)))
2952                   (unless marker
2953                     (gnus-message 1 "gnus-agent-expire detected a \
2954 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
2955                 (gnus-agent-append-to-list
2956                  tail-alist
2957                  (cons article-number fetch-date)))
2958
2959                ;; The following articles are READ, UNMARKED, and
2960                ;; ORDINARY.  See if they can be EXPIRED!!!
2961                ((setq type
2962                       (cond
2963                        ((not (integerp fetch-date))
2964                         'read) ;; never fetched article (may expire
2965                        ;; right now)
2966                        ((not (file-exists-p
2967                               (concat dir (number-to-string
2968                                            article-number))))
2969                         (setf (nth 1 entry) nil)
2970                         'externally-expired) ;; Can't find the cached
2971                        ;; article.  Handle case
2972                        ;; as though this article
2973                        ;; was never fetched.
2974
2975                        ;; We now have the arrival day, so we see
2976                        ;; whether it's old enough to be expired.
2977                        ((< fetch-date day)
2978                         'expired)
2979                        (force
2980                         'forced)))
2981
2982                 ;; I found some reason to expire this entry.
2983
2984                 (let ((actions nil))
2985                   (when (memq type '(forced expired))
2986                     (ignore-errors      ; Just being paranoid.
2987                       (let ((file-name (concat dir (number-to-string
2988                                                 article-number))))
2989                         (incf (nth 2 stats) (nth 7 (file-attributes file-name)))
2990                         (incf (nth 1 stats))
2991                         (delete-file file-name))
2992                       (push "expired cached article" actions))
2993                     (setf (nth 1 entry) nil)
2994                     )
2995
2996                   (when marker
2997                     (push "NOV entry removed" actions)
2998                     (goto-char marker)
2999
3000                     (incf (nth 0 stats))
3001
3002                     (let ((from (point-at-bol))
3003                           (to (progn (forward-line 1) (point))))
3004                       (incf (nth 2 stats) (- to from))
3005                       (delete-region from to)))
3006
3007                   ;; If considering all articles is set, I can only
3008                   ;; expire article IDs that are no longer in the
3009                   ;; active range (That is, articles that preceed the
3010                   ;; first article in the new alist).
3011                   (if (and gnus-agent-consider-all-articles
3012                            (>= article-number (car active)))
3013                       ;; I have to keep this ID in the alist
3014                       (gnus-agent-append-to-list
3015                        tail-alist (cons article-number fetch-date))
3016                     (push (format "Removed %s article number from \
3017 article alist" type) actions))
3018
3019                   (when actions
3020                     (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3021                                         group article-number
3022                                         (mapconcat 'identity actions ", ")))))
3023                (t
3024                 (gnus-agent-message
3025                  10 "gnus-agent-expire: %s:%d: Article kept as \
3026 expiration tests failed." group article-number)
3027                 (gnus-agent-append-to-list
3028                  tail-alist (cons article-number fetch-date)))
3029                )
3030
3031               ;; Clean up markers as I want to recycle this buffer
3032               ;; over several groups.
3033               (when marker
3034                 (set-marker marker nil))
3035
3036               (setq dlist (cdr dlist))))
3037
3038           (setq alist (cdr alist))
3039
3040           (let ((inhibit-quit t))
3041             (unless (equal alist gnus-agent-article-alist)
3042               (setq gnus-agent-article-alist alist)
3043               (gnus-agent-save-alist group))
3044
3045             (when (buffer-modified-p)
3046               (let ((coding-system-for-write
3047                      gnus-agent-file-coding-system))
3048                 (gnus-make-directory dir)
3049                 (write-region (point-min) (point-max) nov-file nil
3050                               'silent)
3051                 ;; clear the modified flag as that I'm not confused by
3052                 ;; its status on the next pass through this routine.
3053                 (set-buffer-modified-p nil)))
3054
3055             (when (eq articles t)
3056               (gnus-summary-update-info))))))))
3057
3058 (defun gnus-agent-expire (&optional articles group force)
3059   "Expire all old articles.
3060 If you want to force expiring of certain articles, this function can
3061 take ARTICLES, GROUP and FORCE parameters as well.
3062
3063 The articles on which the expiration process runs are selected as follows:
3064   if ARTICLES is null, all read and unmarked articles.
3065   if ARTICLES is t, all articles.
3066   if ARTICLES is a list, just those articles.
3067 Setting GROUP will limit expiration to that group.
3068 FORCE is equivalent to setting the expiration predicates to true."
3069   (interactive)
3070   
3071   (if group
3072       (gnus-agent-expire-group group articles force)
3073     (if (or (not (eq articles t))
3074             (yes-or-no-p "Are you sure that you want to expire all \
3075 articles in every agentized group."))
3076         (let ((methods (gnus-agent-covered-methods))
3077               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3078               ;; of agent directories.
3079               (gnus-agent-expire-current-dirs nil)
3080               ;; Bind gnus-agent-expire-stats to enable tracking of
3081               ;; expiration statistics across all groups
3082               (gnus-agent-expire-stats (list 0 0 0.0))
3083               gnus-command-method overview orig)
3084           (setq overview (gnus-get-buffer-create " *expire overview*"))
3085           (unwind-protect
3086               (while (setq gnus-command-method (pop methods))
3087                 (let ((active-file (gnus-agent-lib-file "active")))
3088                   (when (file-exists-p active-file)
3089                     (with-temp-buffer
3090                       (nnheader-insert-file-contents active-file)
3091                       (gnus-active-to-gnus-format
3092                        gnus-command-method
3093                        (setq orig (gnus-make-hashtable
3094                                    (count-lines (point-min) (point-max))))))
3095                     (dolist (expiring-group (gnus-groups-from-server
3096                                              gnus-command-method))
3097                       (let* ((active
3098                               (gnus-gethash-safe expiring-group orig)))
3099                                         
3100                         (when active
3101                           (save-excursion
3102                             (gnus-agent-expire-group-1
3103                              expiring-group overview active articles force))))))))
3104             (kill-buffer overview))
3105           (gnus-agent-expire-unagentized-dirs)
3106           (gnus-message 4 (gnus-agent-expire-done-message))))))
3107
3108 (defun gnus-agent-expire-done-message ()
3109   (if (and (> gnus-verbose 4)
3110            (boundp 'gnus-agent-expire-stats))
3111       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3112              (size (nth 2 stats))
3113             (units '(B KB MB GB)))
3114         (while (and (> size 1024.0)
3115                     (cdr units))
3116           (setq size (/ size 1024.0)
3117                 units (cdr units)))
3118
3119         (format "Expiry recovered %d NOV entries, deleted %d files,\
3120  and freed %f %s." 
3121                 (nth 0 stats) 
3122                 (nth 1 stats) 
3123                 size (car units)))
3124     "Expiry...done"))
3125
3126 (defun gnus-agent-expire-unagentized-dirs ()
3127   (when (and gnus-agent-expire-unagentized-dirs
3128              (boundp 'gnus-agent-expire-current-dirs))
3129     (let* ((keep (gnus-make-hashtable))
3130            ;; Formally bind gnus-agent-expire-current-dirs so that the
3131            ;; compiler will not complain about free references.
3132            (gnus-agent-expire-current-dirs
3133             (symbol-value 'gnus-agent-expire-current-dirs))
3134            dir)
3135
3136       (gnus-sethash gnus-agent-directory t keep)
3137       (while gnus-agent-expire-current-dirs
3138         (setq dir (pop gnus-agent-expire-current-dirs))
3139         (when (and (stringp dir)
3140                    (file-directory-p dir))
3141           (while (not (gnus-gethash dir keep))
3142             (gnus-sethash dir t keep)
3143             (setq dir (file-name-directory (directory-file-name dir))))))
3144
3145       (let* (to-remove
3146              checker
3147              (checker
3148               (function
3149                (lambda (d)
3150                  "Given a directory, check it and its subdirectories for 
3151               membership in the keep hash.  If it isn't found, add 
3152               it to to-remove." 
3153                  (let ((files (directory-files d))
3154                        file)
3155                    (while (setq file (pop files))
3156                      (cond ((equal file ".") ; Ignore self
3157                             nil)
3158                            ((equal file "..") ; Ignore parent
3159                             nil)
3160                            ((equal file ".overview") 
3161                             ;; Directory must contain .overview to be
3162                             ;; agent's cache of a group.
3163                             (let ((d (file-name-as-directory d))
3164                                   r)
3165                               ;; Search ancestor's for last directory NOT
3166                               ;; found in keep hash.
3167                               (while (not (gnus-gethash
3168                                            (setq d (file-name-directory d)) keep))
3169                                 (setq r d
3170                                       d (directory-file-name d)))
3171                               ;; if ANY ancestor was NOT in keep hash and
3172                               ;; it it's already in to-remove, add it to
3173                               ;; to-remove.                          
3174                               (if (and r
3175                                        (not (member r to-remove)))
3176                                   (push r to-remove))))
3177                            ((file-directory-p (setq file (nnheader-concat d file)))
3178                             (funcall checker file)))))))))
3179         (funcall checker (expand-file-name gnus-agent-directory))
3180
3181         (when (and to-remove
3182                    (or gnus-expert-user
3183                        (gnus-y-or-n-p
3184                         "gnus-agent-expire has identified local directories that are\
3185  not currently required by any agentized group.  Do you wish to consider\
3186  deleting them?")))
3187           (while to-remove
3188             (let ((dir (pop to-remove)))
3189               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3190                   (let* (delete-recursive
3191                          (delete-recursive
3192                           (function
3193                            (lambda (f-or-d)
3194                              (ignore-errors
3195                                (if (file-directory-p f-or-d)
3196                                    (condition-case nil
3197                                        (delete-directory f-or-d)
3198                                      (file-error
3199                                       (mapcar (lambda (f)
3200                                                 (or (member f '("." ".."))
3201                                                     (funcall delete-recursive
3202                                                              (nnheader-concat
3203                                                               f-or-d f))))
3204                                               (directory-files f-or-d))
3205                                       (delete-directory f-or-d)))
3206                                  (delete-file f-or-d)))))))
3207                     (funcall delete-recursive dir))))))))))
3208
3209 ;;;###autoload
3210 (defun gnus-agent-batch ()
3211   "Start Gnus, send queue and fetch session."
3212   (interactive)
3213   (let ((init-file-user "")
3214         (gnus-always-read-dribble-file t))
3215     (gnus))
3216   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3217     (gnus-group-send-queue)
3218     (gnus-agent-fetch-session)))
3219
3220 (defun gnus-agent-unread-articles (group)
3221   (let* ((read (gnus-info-read (gnus-get-info group)))
3222          (known (gnus-agent-load-alist group))
3223          (unread (list nil))
3224          (tail-unread unread))
3225     (while (and known read)
3226       (let ((candidate (car (pop known))))
3227         (while (let* ((range (car read))
3228                       (min   (if (numberp range) range (car range)))
3229                       (max   (if (numberp range) range (cdr range))))
3230                  (cond ((or (not min)
3231                             (< candidate min))
3232                         (gnus-agent-append-to-list tail-unread candidate)
3233                         nil)
3234                        ((> candidate max)
3235                         (setq read (cdr read))
3236                         ;; return t so that I always loop one more
3237                         ;; time.  If I just iterated off the end of
3238                         ;; read, min will become nil and the current
3239                         ;; candidate will be added to the unread list.
3240                         t))))))
3241     (while known
3242       (gnus-agent-append-to-list tail-unread (car (pop known))))
3243     (cdr unread)))
3244
3245 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3246   "Restrict ARTICLES to numbers already fetched.
3247 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3248 that have already been fetched.
3249 If CACHED-HEADER is nil, articles are only excluded if the article itself
3250 has been fetched."
3251
3252   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3253   ;; 'car gnus-agent-article-alist))
3254
3255   ;; Functionally, I don't need to construct a temp list using mapcar.
3256
3257   (if (and (or gnus-agent-cache (not gnus-plugged))
3258            (gnus-agent-load-alist group))
3259     (let* ((ref gnus-agent-article-alist)
3260            (arts articles)
3261            (uncached (list nil))
3262            (tail-uncached uncached))
3263       (while (and ref arts)
3264         (let ((v1 (car arts))
3265               (v2 (caar ref)))
3266           (cond ((< v1 v2) ; v1 does not appear in the reference list
3267                  (gnus-agent-append-to-list tail-uncached v1)
3268                  (setq arts (cdr arts)))
3269                 ((= v1 v2)
3270                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3271                    (gnus-agent-append-to-list tail-uncached v1))
3272                  (setq arts (cdr arts))
3273                  (setq ref (cdr ref)))
3274                 (t ; reference article (v2) preceeds the list being filtered
3275                  (setq ref (cdr ref))))))
3276       (while arts
3277         (gnus-agent-append-to-list tail-uncached (pop arts)))
3278       (cdr uncached))
3279     ;; if gnus-agent-load-alist fails, no articles are cached.
3280     articles))
3281
3282 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3283   (save-excursion
3284     (gnus-agent-create-buffer)
3285     (let ((gnus-decode-encoded-word-function 'identity)
3286           (file (gnus-agent-article-name ".overview" group))
3287           cached-articles uncached-articles)
3288       (gnus-make-directory (nnheader-translate-file-chars
3289                             (file-name-directory file) t))
3290
3291       ;; Populate temp buffer with known headers
3292       (when (file-exists-p file)
3293         (with-current-buffer gnus-agent-overview-buffer
3294           (erase-buffer)
3295           (let ((nnheader-file-coding-system
3296                  gnus-agent-file-coding-system))
3297             (nnheader-insert-nov-file file (car articles)))))
3298
3299       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3300                                                                 t))
3301           (progn
3302             ;; Populate nntp-server-buffer with uncached headers
3303             (set-buffer nntp-server-buffer)
3304             (erase-buffer)
3305             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3306                                    (gnus-retrieve-headers
3307                                     uncached-articles group fetch-old))))
3308                    (nnvirtual-convert-headers))
3309                   ((eq 'nntp (car gnus-current-select-method))
3310                    ;; The author of gnus-get-newsgroup-headers-xover
3311                    ;; reports that the XOVER command is commonly
3312                    ;; unreliable. The problem is that recently
3313                    ;; posted articles may not be entered into the
3314                    ;; NOV database in time to respond to my XOVER
3315                    ;; query.
3316                    ;;
3317                    ;; I'm going to use his assumption that the NOV
3318                    ;; database is updated in order of ascending
3319                    ;; article ID.  Therefore, a response containing
3320                    ;; article ID N implies that all articles from 1
3321                    ;; to N-1 are up-to-date.  Therefore, missing
3322                    ;; articles in that range have expired.
3323
3324                    (set-buffer nntp-server-buffer)
3325                    (let* ((fetched-articles (list nil))
3326                           (tail-fetched-articles fetched-articles)
3327                           (min (cond ((numberp fetch-old)
3328                                       (max 1 (- (car articles) fetch-old)))
3329                                      (fetch-old
3330                                       1)
3331                                      (t
3332                                       (car articles))))
3333                           (max (car (last articles))))
3334
3335                      ;; Get the list of articles that were fetched
3336                      (goto-char (point-min))
3337                      (let ((pm (point-max)))
3338                        (while (< (point) pm)
3339                          (when (looking-at "[0-9]+\t")
3340                            (gnus-agent-append-to-list
3341                             tail-fetched-articles
3342                             (read (current-buffer))))
3343                          (forward-line 1)))
3344
3345                      ;; Clip this list to the headers that will
3346                      ;; actually be returned
3347                      (setq fetched-articles (gnus-list-range-intersection
3348                                              (cdr fetched-articles)
3349                                              (cons min max)))
3350
3351                      ;; Clip the uncached articles list to exclude
3352                      ;; IDs after the last FETCHED header.  The
3353                      ;; excluded IDs may be fetchable using HEAD.
3354                      (if (car tail-fetched-articles)
3355                          (setq uncached-articles
3356                                (gnus-list-range-intersection
3357                                 uncached-articles
3358                                 (cons (car uncached-articles)
3359                                       (car tail-fetched-articles)))))
3360
3361                      ;; Create the list of articles that were
3362                      ;; "successfully" fetched.  Success, in this
3363                      ;; case, means that the ID should not be
3364                      ;; fetched again.  In the case of an expired
3365                      ;; article, the header will not be fetched.
3366                      (setq uncached-articles
3367                            (gnus-sorted-nunion fetched-articles
3368                                                uncached-articles))
3369                      )))
3370
3371             ;; Erase the temp buffer
3372             (set-buffer gnus-agent-overview-buffer)
3373             (erase-buffer)
3374
3375             ;; Copy the nntp-server-buffer to the temp buffer
3376             (set-buffer nntp-server-buffer)
3377             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3378
3379             ;; Merge the temp buffer with the known headers (found on
3380             ;; disk in FILE) into the nntp-server-buffer
3381             (when (and uncached-articles (file-exists-p file))
3382               (gnus-agent-braid-nov group uncached-articles file))
3383
3384             ;; Save the new set of known headers to FILE
3385             (set-buffer nntp-server-buffer)
3386             (let ((coding-system-for-write
3387                    gnus-agent-file-coding-system))
3388               (gnus-agent-check-overview-buffer)
3389               (write-region (point-min) (point-max) file nil 'silent))
3390
3391             ;; Update the group's article alist to include the newly
3392             ;; fetched articles.
3393             (gnus-agent-load-alist group)
3394             (gnus-agent-save-alist group uncached-articles nil)
3395             )
3396
3397         ;; Copy the temp buffer to the nntp-server-buffer
3398         (set-buffer nntp-server-buffer)
3399         (erase-buffer)
3400         (insert-buffer-substring gnus-agent-overview-buffer)))
3401
3402     (if (and fetch-old
3403              (not (numberp fetch-old)))
3404         t                               ; Don't remove anything.
3405       (nnheader-nov-delete-outside-range
3406        (if fetch-old (max 1 (- (car articles) fetch-old))
3407          (car articles))
3408        (car (last articles)))
3409       t)
3410
3411     'nov))
3412
3413 (defun gnus-agent-request-article (article group)
3414   "Retrieve ARTICLE in GROUP from the agent cache."
3415   (when (and gnus-agent
3416              (or gnus-agent-cache
3417                  (not gnus-plugged))
3418              (numberp article))
3419     (let* ((gnus-command-method (gnus-find-method-for-group group))
3420            (file (gnus-agent-article-name (number-to-string article) group))
3421            (buffer-read-only nil))
3422       (when (and (file-exists-p file)
3423                  (> (nth 7 (file-attributes file)) 0))
3424         (erase-buffer)
3425         (gnus-kill-all-overlays)
3426         (let ((coding-system-for-read gnus-cache-coding-system))
3427           (insert-file-contents file))
3428         t))))
3429
3430 (defun gnus-agent-regenerate-group (group &optional reread)
3431   "Regenerate GROUP.
3432 If REREAD is t, all articles in the .overview are marked as unread.
3433 If REREAD is a list, the specified articles will be marked as unread.
3434 In addition, their NOV entries in .overview will be refreshed using
3435 the articles' current headers.
3436 If REREAD is not nil, downloaded articles are marked as unread."
3437   (interactive
3438    (list (let ((def (or (gnus-group-group-name)
3439                         gnus-newsgroup-name)))
3440            (let ((select (read-string (if def
3441                                           (concat "Group Name ("
3442                                                   def "): ")
3443                                         "Group Name: "))))
3444              (if (and (equal "" select)
3445                       def)
3446                  def
3447                select)))
3448          (catch 'mark
3449            (while (let (c
3450                         (cursor-in-echo-area t)
3451                         (echo-keystrokes 0))
3452                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3453                     (setq c (read-char-exclusive))
3454
3455                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3456                            (throw 'mark nil))
3457                           ((or (eq c ?a) (eq c ?A))
3458                            (throw 'mark t))
3459                           ((or (eq c ?d) (eq c ?D))
3460                            (throw 'mark 'some)))
3461                     (gnus-message 3 "Ignoring unexpected input")
3462                     (sit-for 1)
3463                     t)))))
3464
3465   (when group
3466       (gnus-message 5 "Regenerating in %s" group)
3467       (let* ((gnus-command-method (or gnus-command-method
3468                                       (gnus-find-method-for-group group)))
3469              (file (gnus-agent-article-name ".overview" group))
3470              (dir (file-name-directory file))
3471              point
3472              (downloaded (if (file-exists-p dir)
3473                              (sort (mapcar (lambda (name) (string-to-int name))
3474                                            (directory-files dir nil "^[0-9]+$" t))
3475                                    '>)
3476                            (progn (gnus-make-directory dir) nil)))
3477              dl nov-arts
3478              alist header
3479              regenerated)
3480
3481         (mm-with-unibyte-buffer
3482           (if (file-exists-p file)
3483               (let ((nnheader-file-coding-system
3484                      gnus-agent-file-coding-system))
3485                 (nnheader-insert-file-contents file)))
3486           (set-buffer-modified-p nil)
3487
3488           ;; Load the article IDs found in the overview file.  As a
3489           ;; side-effect, validate the file contents.
3490           (let ((load t))
3491             (while load
3492               (setq load nil)
3493               (goto-char (point-min))
3494               (while (< (point) (point-max))
3495                 (cond ((and (looking-at "[0-9]+\t")
3496                             (<= (- (match-end 0) (match-beginning 0)) 9))
3497                        (push (read (current-buffer)) nov-arts)
3498                        (forward-line 1)
3499                        (let ((l1 (car nov-arts))
3500                              (l2 (cadr nov-arts)))
3501                          (cond ((and (listp reread) (memq l1 reread))
3502                                 (gnus-delete-line)
3503                                 (setq nov-arts (cdr nov-arts))
3504                                 (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3505 entry of article %s deleted." l1))
3506                                ((not l2)
3507                                 nil)
3508                                ((< l1 l2)
3509                                 (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3510  entries are NOT in ascending order.")
3511                                 ;; Don't sort now as I haven't verified
3512                                 ;; that every line begins with a number
3513                                 (setq load t))
3514                                ((= l1 l2)
3515                                 (forward-line -1)
3516                                 (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3517  entries contained duplicate of article %s.      Duplicate deleted." l1)
3518                                 (gnus-delete-line)
3519                                 (setq nov-arts (cdr nov-arts))))))
3520                       (t
3521                        (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3522  entries contained line that did not begin with an article number.  Deleted\
3523  line.")
3524                        (gnus-delete-line))))
3525               (when load
3526                 (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3527  entries into ascending order.")
3528                 (sort-numeric-fields 1 (point-min) (point-max))
3529                 (setq nov-arts nil))))
3530           (gnus-agent-check-overview-buffer)
3531
3532           ;; Construct a new article alist whose nodes match every header
3533           ;; in the .overview file.  As a side-effect, missing headers are
3534           ;; reconstructed from the downloaded article file.
3535           (while (or downloaded nov-arts)
3536             (cond ((and downloaded
3537                         (or (not nov-arts)
3538                             (> (car downloaded) (car nov-arts))))
3539                    ;; This entry is missing from the overview file
3540                    (gnus-message 3 "Regenerating NOV %s %d..." group
3541                                  (car downloaded))
3542                    (let ((file (concat dir (number-to-string (car downloaded)))))
3543                      (mm-with-unibyte-buffer
3544                        (nnheader-insert-file-contents file)
3545                        (nnheader-remove-body)
3546                        (setq header (nnheader-parse-naked-head)))
3547                      (mail-header-set-number header (car downloaded))
3548                      (if nov-arts
3549                          (let ((key (concat "^" (int-to-string (car nov-arts))
3550                                             "\t")))
3551                            (or (re-search-backward key nil t)
3552                                (re-search-forward key))
3553                            (forward-line 1))
3554                        (goto-char (point-min)))
3555                      (nnheader-insert-nov header))
3556                    (setq nov-arts (cons (car downloaded) nov-arts)))
3557                   ((eq (car downloaded) (car nov-arts))
3558                    ;; This entry in the overview has been downloaded
3559                    (push (cons (car downloaded)
3560                                (time-to-days
3561                                 (nth 5 (file-attributes
3562                                         (concat dir (number-to-string
3563                                                      (car downloaded))))))) alist)
3564                    (setq downloaded (cdr downloaded))
3565                    (setq nov-arts (cdr nov-arts)))
3566                   (t
3567                    ;; This entry in the overview has not been downloaded
3568                    (push (cons (car nov-arts) nil) alist)
3569                    (setq nov-arts (cdr nov-arts)))))
3570
3571           ;; When gnus-agent-consider-all-articles is set,
3572           ;; gnus-agent-regenerate-group should NOT remove article IDs from
3573           ;; the alist.  Those IDs serve as markers to indicate that an
3574           ;; attempt has been made to fetch that article's header.
3575
3576           ;; When gnus-agent-consider-all-articles is NOT set,
3577           ;; gnus-agent-regenerate-group can remove the article ID of every
3578           ;; article (with the exception of the last ID in the list - it's
3579           ;; special) that no longer appears in the overview.  In this
3580           ;; situtation, the last article ID in the list implies that it,
3581           ;; and every article ID preceeding it, have been fetched from the
3582           ;; server.
3583
3584           (if gnus-agent-consider-all-articles
3585               ;; Restore all article IDs that were not found in the overview file.
3586               (let* ((n (cons nil alist))
3587                      (merged n)
3588                      (o (gnus-agent-load-alist group)))
3589                 (while o
3590                   (let ((nID (caadr n))
3591                         (oID (caar o)))
3592                     (cond ((not nID)
3593                            (setq n (setcdr n (list (list oID))))
3594                            (setq o (cdr o)))
3595                           ((< oID nID)
3596                            (setcdr n (cons (list oID) (cdr n)))
3597                            (setq o (cdr o)))
3598                           ((= oID nID)
3599                            (setq o (cdr o))
3600                            (setq n (cdr n)))
3601                           (t
3602                            (setq n (cdr n))))))
3603                 (setq alist (cdr merged)))
3604             ;; Restore the last article ID if it is not already in the new alist
3605             (let ((n (last alist))
3606                   (o (last (gnus-agent-load-alist group))))
3607               (cond ((not o)
3608                      nil)
3609                     ((not n)
3610                      (push (cons (caar o) nil) alist))
3611                     ((< (caar n) (caar o))
3612                      (setcdr n (list (car o)))))))
3613
3614           (let ((inhibit-quit t))
3615             (if (setq regenerated (buffer-modified-p))
3616                 (let ((coding-system-for-write gnus-agent-file-coding-system))
3617                   (write-region (point-min) (point-max) file nil 'silent)))
3618
3619             (setq regenerated (or regenerated
3620                                   (and reread gnus-agent-article-alist)
3621                                   (not (equal alist gnus-agent-article-alist))))
3622
3623             (setq gnus-agent-article-alist alist)
3624
3625             (when regenerated
3626               (gnus-agent-save-alist group)
3627        
3628               ;; I have to alter the group's active range NOW as
3629               ;; gnus-make-ascending-articles-unread will use it to
3630               ;; recalculate the number of unread articles in the group
3631
3632               (let ((group (gnus-group-real-name group))
3633                     (group-active (gnus-active group)))
3634                 (gnus-agent-possibly-alter-active group group-active)))))
3635
3636         (when (and reread gnus-agent-article-alist)
3637           (gnus-make-ascending-articles-unread
3638            group
3639            (if (listp reread)
3640                reread
3641              (delq nil (mapcar (function (lambda (c)
3642                                            (cond ((eq reread t)
3643                                                   (car c))
3644                                                  ((cdr c)
3645                                                   (car c)))))
3646                                gnus-agent-article-alist))))
3647
3648           (when (gnus-buffer-live-p gnus-group-buffer)
3649             (gnus-group-update-group group t)
3650             (sit-for 0)))
3651
3652         (gnus-message 5 nil)
3653         regenerated)))
3654
3655 ;;;###autoload
3656 (defun gnus-agent-regenerate (&optional clean reread)
3657   "Regenerate all agent covered files.
3658 If CLEAN, obsolete (ignore)."
3659   (interactive "P")
3660   (let (regenerated)
3661     (gnus-message 4 "Regenerating Gnus agent files...")
3662     (dolist (gnus-command-method (gnus-agent-covered-methods))
3663         (dolist (group (gnus-groups-from-server gnus-command-method))
3664           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3665                                 regenerated))))
3666     (gnus-message 4 "Regenerating Gnus agent files...done")
3667
3668     regenerated))
3669
3670 (defun gnus-agent-go-online (&optional force)
3671   "Switch servers into online status."
3672   (interactive (list t))
3673   (dolist (server gnus-opened-servers)
3674     (when (eq (nth 1 server) 'offline)
3675       (if (if (eq force 'ask)
3676               (gnus-y-or-n-p
3677                (format "Switch %s:%s into online status? "
3678                        (caar server) (cadar server)))
3679             force)
3680           (setcar (nthcdr 1 server) 'close)))))
3681
3682 (defun gnus-agent-toggle-group-plugged (group)
3683   "Toggle the status of the server of the current group."
3684   (interactive (list (gnus-group-group-name)))
3685   (let* ((method (gnus-find-method-for-group group))
3686          (status (cadr (assoc method gnus-opened-servers))))
3687     (if (eq status 'offline)
3688         (gnus-server-set-status method 'closed)
3689       (gnus-close-server method)
3690       (gnus-server-set-status method 'offline))
3691     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3692              (if (eq status 'offline) 'offline 'online)
3693              (if (eq status 'offline) 'online 'offline))))
3694
3695 (defun gnus-agent-group-covered-p (group)
3696   (gnus-agent-method-p (gnus-group-method group)))
3697
3698 (add-hook 'gnus-group-prepare-hook
3699           (lambda ()
3700             'gnus-agent-do-once
3701
3702             (when (listp gnus-agent-expire-days)
3703               (beep)
3704               (beep)
3705               (gnus-message 1 "WARNING: gnus-agent-expire-days no longer\
3706  supports being set to a list.")(sleep-for 3)
3707               (gnus-message 1 "Change your configuration to set it to an\
3708  integer.")(sleep-for 3)
3709               (gnus-message 1 "I am now setting group parameters on each\
3710  group to match the configuration that the list offered.")
3711
3712               (save-excursion
3713                 (let ((groups (gnus-group-listed-groups)))
3714                   (while groups
3715                     (let* ((group (pop groups))
3716                            (days gnus-agent-expire-days)
3717                            (day (catch 'found
3718                                   (while days
3719                                     (when (eq 0 (string-match
3720                                                  (caar days)
3721                                                  group))
3722                                       (throw 'found (cadar days)))
3723                                     (setq days (cdr days)))
3724                                   nil)))
3725                       (when day
3726                         (gnus-group-set-parameter group 'agent-days-until-old
3727                                                   day))))))
3728
3729               (let ((h gnus-group-prepare-hook))
3730                 (while h
3731                   (let ((func (pop h)))
3732                     (when (and (listp func)
3733                                (eq (cadr (caddr func)) 'gnus-agent-do-once))
3734                       (remove-hook 'gnus-group-prepare-hook func)
3735                       (setq h nil)))))
3736
3737               (gnus-message 1 "I have finished setting group parameters on\
3738  each group. You may now customize your groups and/or topics to control the\
3739  agent."))))
3740
3741 (provide 'gnus-agent)
3742
3743 ;;; gnus-agent.el ends here