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