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