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