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