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