Synch to No Gnus 200406292138.
[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 nil
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 (inline
1877                                    (gnus-uncompress-range
1878                                     (cdr comp-list)))))
1879                    (mapcar (lambda (article-id)
1880                              (setq uncomp (cons (cons article-id state) uncomp)))
1881                            sequence)))
1882                alist)
1883               (setq alist (sort uncomp 'car-less-than-car)))))
1884           (when changed-version
1885             (let ((gnus-agent-article-alist alist))
1886               (gnus-agent-save-alist gnus-agent-read-agentview)))
1887           alist))
1888       (file-error nil))))
1889
1890 (defun gnus-agent-save-alist (group &optional articles state)
1891   "Save the article-state alist for GROUP."
1892   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1893          (prev (cons nil gnus-agent-article-alist))
1894          (all prev)
1895          print-level print-length item article)
1896     (while (setq article (pop articles))
1897       (while (and (cdr prev)
1898                   (< (caadr prev) article))
1899         (setq prev (cdr prev)))
1900       (cond
1901        ((not (cdr prev))
1902         (setcdr prev (list (cons article state))))
1903        ((> (caadr prev) article)
1904         (setcdr prev (cons (cons article state) (cdr prev))))
1905        ((= (caadr prev) article)
1906         (setcdr (cadr prev) state)))
1907       (setq prev (cdr prev)))
1908     (setq gnus-agent-article-alist (cdr all))
1909
1910     (gnus-agent-set-local group 
1911                           (caar gnus-agent-article-alist) 
1912                           (caar (last gnus-agent-article-alist)))
1913
1914     (gnus-make-directory (gnus-agent-article-name "" group))
1915     (with-temp-file (gnus-agent-article-name ".agentview" group)
1916       (cond ((eq gnus-agent-article-alist-save-format 1)
1917              (princ gnus-agent-article-alist (current-buffer)))
1918             ((eq gnus-agent-article-alist-save-format 2)
1919              (let ((compressed nil))
1920                (mapcar (lambda (pair)
1921                          (let* ((article-id (car pair))
1922                                 (day-of-download (cdr pair))
1923                                 (comp-list (assq day-of-download compressed)))
1924                            (if comp-list
1925                                (setcdr comp-list
1926                                        (cons article-id (cdr comp-list)))
1927                              (setq compressed
1928                                    (cons (list day-of-download article-id)
1929                                          compressed)))
1930                            nil)) gnus-agent-article-alist)
1931                (mapcar (lambda (comp-list)
1932                          (setcdr comp-list
1933                                  (gnus-compress-sequence
1934                                   (nreverse (cdr comp-list)))))
1935                        compressed)
1936                (princ compressed (current-buffer)))))
1937       (insert "\n")
1938       (princ gnus-agent-article-alist-save-format (current-buffer))
1939       (insert "\n"))
1940
1941     (gnus-agent-update-view-total-fetched-for group nil)))
1942
1943 (defvar gnus-agent-article-local nil)
1944 (defvar gnus-agent-file-loading-local nil)
1945
1946 (defun gnus-agent-load-local (&optional method)
1947   "Load the METHOD'S local file.  The local file contains min/max
1948 article counts for each of the method's subscribed groups."
1949   (let ((gnus-command-method (or method gnus-command-method)))
1950     (setq gnus-agent-article-local
1951           (gnus-cache-file-contents
1952            (gnus-agent-lib-file "local")
1953            'gnus-agent-file-loading-local
1954            'gnus-agent-read-and-cache-local))))
1955
1956 (defun gnus-agent-read-and-cache-local (file)
1957   "Load and read FILE then bind its contents to
1958 gnus-agent-article-local.  If that variable had `dirty' (also known as
1959 modified) original contents, they are first saved to their own file."
1960
1961   (if (and gnus-agent-article-local
1962            (symbol-value (intern "+dirty" gnus-agent-article-local)))
1963       (gnus-agent-save-local))
1964   (gnus-agent-read-local file))
1965
1966 (defun gnus-agent-read-local (file)
1967   "Load FILE and do a `read' there."
1968   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min) 
1969                                                       (point-max))))
1970         (line 1))
1971     (with-temp-buffer
1972       (condition-case nil
1973           (let ((nnheader-file-coding-system gnus-agent-file-coding-system))
1974             (nnheader-insert-file-contents file))
1975         (file-error))
1976
1977       (goto-char (point-min))
1978       ;; Skip any comments at the beginning of the file (the only place where they may appear)
1979       (while (= (following-char) ?\;)
1980         (forward-line 1)
1981         (setq line (1+ line)))
1982
1983       (while (not (eobp))
1984         (condition-case err
1985             (let (group 
1986                   min
1987                   max
1988                   (cur (current-buffer)))
1989               (setq group (read cur)
1990                     min (read cur)
1991                     max (read cur))
1992
1993               (when (stringp group)
1994                 (setq group (intern group my-obarray)))
1995
1996               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
1997               (set group (cons (+ 0 min) (+ 0 max))))
1998           (error
1999            (gnus-message 3 "Warning - invalid agent local: %s on line %d: "
2000                          file line (error-message-string err))))
2001         (forward-line 1)
2002         (setq line (1+ line))))
2003       
2004     (set (intern "+dirty" my-obarray) nil)
2005     (set (intern "+method" my-obarray) gnus-command-method)
2006     my-obarray))
2007
2008 (defun gnus-agent-save-local (&optional force)
2009   "Save gnus-agent-article-local under it method's agent.lib directory."
2010   (let ((my-obarray gnus-agent-article-local))
2011     (when (and my-obarray
2012                (or force (symbol-value (intern "+dirty" my-obarray))))
2013       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2014              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
2015              (dest (gnus-agent-lib-file "local")))
2016         (gnus-make-directory (gnus-agent-lib-file ""))
2017
2018         (let ((buffer-file-coding-system gnus-agent-file-coding-system))
2019           (with-temp-file dest
2020             (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2021                   (file-name-coding-system nnmail-pathname-coding-system)
2022                   print-level print-length item article
2023                   (standard-output (current-buffer)))
2024               (mapatoms (lambda (symbol)
2025                           (cond ((not (boundp symbol))
2026                                  nil)
2027                                 ((member (symbol-name symbol) '("+dirty" "+method"))
2028                                  nil)
2029                                 (t
2030                                  (prin1 symbol)
2031                                  (let ((range (symbol-value symbol)))
2032                                    (princ " ")
2033                                    (princ (car range))
2034                                    (princ " ")
2035                                    (princ (cdr range))
2036                                    (princ "\n"))))) 
2037                         my-obarray))))))))
2038
2039 (defun gnus-agent-get-local (group &optional gmane method)
2040   (let* ((gmane (or gmane (gnus-group-real-name group)))
2041          (gnus-command-method (or method (gnus-find-method-for-group group)))
2042          (local (gnus-agent-load-local))
2043          (symb (intern gmane local))
2044          (minmax (and (boundp symb) (symbol-value symb))))
2045     (unless minmax
2046       ;; Bind these so that gnus-agent-load-alist doesn't change the
2047       ;; current alist (i.e. gnus-agent-article-alist)
2048       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2049              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2050              (alist (gnus-agent-load-alist group)))
2051         (when alist
2052           (setq minmax
2053                 (cons (caar alist)
2054                       (caar (last alist))))
2055           (gnus-agent-set-local group (car minmax) (cdr minmax) 
2056                                 gmane gnus-command-method local))))
2057     minmax))
2058
2059 (defun gnus-agent-set-local (group min max &optional gmane method local)
2060   (let* ((gmane (or gmane (gnus-group-real-name group)))
2061          (gnus-command-method (or method (gnus-find-method-for-group group)))
2062          (local (or local (gnus-agent-load-local)))
2063          (symb (intern gmane local))
2064          (minmax (and (boundp symb) (symbol-value symb))))
2065     
2066     (if (cond ((and minmax
2067                     (or (not (eq min (car minmax)))
2068                         (not (eq max (cdr minmax)))))
2069                (setcar minmax min)
2070                (setcdr minmax max)
2071                t)
2072               (minmax
2073                nil)
2074               ((and min max)
2075                (set symb (cons min max))
2076                t)
2077               (t
2078                (unintern symb local)))
2079         (set (intern "+dirty" local) t))))
2080
2081 (defun gnus-agent-article-name (article group)
2082   (expand-file-name article
2083                     (file-name-as-directory
2084                      (gnus-agent-group-pathname group))))
2085
2086 (defun gnus-agent-batch-confirmation (msg)
2087   "Show error message and return t."
2088   (gnus-message 1 msg)
2089   t)
2090
2091 ;;;###autoload
2092 (defun gnus-agent-batch-fetch ()
2093   "Start Gnus and fetch session."
2094   (interactive)
2095   (gnus)
2096   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2097     (gnus-agent-fetch-session))
2098   (gnus-group-exit))
2099
2100 (defun gnus-agent-fetch-session ()
2101   "Fetch all articles and headers that are eligible for fetching."
2102   (interactive)
2103   (unless gnus-agent-covered-methods
2104     (error "No servers are covered by the Gnus agent"))
2105   (unless gnus-plugged
2106     (error "Can't fetch articles while Gnus is unplugged"))
2107   (let ((methods (gnus-agent-covered-methods))
2108         groups group gnus-command-method)
2109     (save-excursion
2110       (while methods
2111         (setq gnus-command-method (car methods))
2112         (when (and (or (gnus-server-opened gnus-command-method)
2113                        (gnus-open-server gnus-command-method))
2114                    (gnus-online gnus-command-method))
2115           (setq groups (gnus-groups-from-server (car methods)))
2116           (gnus-agent-with-fetch
2117             (while (setq group (pop groups))
2118               (when (<= (gnus-group-level group)
2119                         gnus-agent-handle-level)
2120                 (if (or debug-on-error debug-on-quit)
2121                     (gnus-agent-fetch-group-1
2122                      group gnus-command-method)
2123                   (condition-case err
2124                       (gnus-agent-fetch-group-1
2125                        group gnus-command-method)
2126                     (error
2127                      (unless (funcall gnus-agent-confirmation-function
2128                                       (format "Error %s while fetching session.  Should gnus continue? "
2129                                               (error-message-string err)))
2130                        (error "Cannot fetch articles into the Gnus agent")))
2131                     (quit
2132                      (gnus-agent-regenerate-group group)
2133                      (unless (funcall gnus-agent-confirmation-function
2134                                       (format
2135                                        "%s while fetching session.  Should gnus continue? "
2136                                        (error-message-string err)))
2137                        (signal 'quit
2138                                "Cannot fetch articles into the Gnus agent")))))))))
2139         (setq methods (cdr methods)))
2140       (gnus-run-hooks 'gnus-agent-fetched-hook)
2141       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2142
2143 (defun gnus-agent-fetch-group-1 (group method)
2144   "Fetch GROUP."
2145   (let ((gnus-command-method method)
2146         (gnus-newsgroup-name group)
2147         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2148         (gnus-newsgroup-headers gnus-newsgroup-headers)
2149         (gnus-newsgroup-scored gnus-newsgroup-scored)
2150         (gnus-use-cache gnus-use-cache)
2151         (gnus-summary-expunge-below gnus-summary-expunge-below)
2152         (gnus-summary-mark-below gnus-summary-mark-below)
2153         (gnus-orphan-score gnus-orphan-score)
2154         ;; Maybe some other gnus-summary local variables should also
2155         ;; be put here.
2156
2157         gnus-headers
2158         gnus-score
2159         articles arts
2160         category predicate info marks score-param
2161         )
2162     (unless (gnus-check-group group)
2163       (error "Can't open server for %s" group))
2164
2165     ;; Fetch headers.
2166     (when (or gnus-newsgroup-active
2167               (gnus-active group)
2168               (gnus-activate-group group))
2169       (let ((marked-articles gnus-newsgroup-downloadable))
2170         ;; Identify the articles marked for download
2171         (unless gnus-newsgroup-active
2172           ;; The variable gnus-newsgroup-active was selected as I need
2173           ;; a gnus-summary local variable that is NOT bound to any
2174           ;; value (its global value should default to nil).
2175           (dolist (mark gnus-agent-download-marks)
2176             (let ((arts (cdr (assq mark (gnus-info-marks
2177                                          (setq info (gnus-get-info group)))))))
2178               (when arts
2179                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2180                                              marked-articles))
2181                 ))))
2182         (setq marked-articles (sort marked-articles '<))
2183
2184         ;; Fetch any new articles from the server
2185         (setq articles (gnus-agent-fetch-headers group))
2186
2187         ;; Merge new articles with marked
2188         (setq articles (sort (append marked-articles articles) '<))
2189
2190         (when articles
2191           ;; Parse them and see which articles we want to fetch.
2192           (setq gnus-newsgroup-dependencies
2193                 (or gnus-newsgroup-dependencies
2194                     (make-vector (length articles) 0)))
2195           (setq gnus-newsgroup-headers
2196                 (or gnus-newsgroup-headers
2197                     (gnus-get-newsgroup-headers-xover articles nil nil
2198                                                       group)))
2199           ;; `gnus-agent-overview-buffer' may be killed for
2200           ;; timeout reason.  If so, recreate it.
2201           (gnus-agent-create-buffer)
2202
2203           ;; Figure out how to select articles in this group
2204           (setq category (gnus-group-category group))
2205
2206           (setq predicate
2207                 (gnus-get-predicate
2208                  (gnus-agent-find-parameter group 'agent-predicate)))
2209
2210           ;; If the selection predicate requires scoring, score each header
2211           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2212             (let ((score-param
2213                    (gnus-agent-find-parameter group 'agent-score-file)))
2214               ;; Translate score-param into real one
2215               (cond
2216                ((not score-param))
2217                ((eq score-param 'file)
2218                 (setq score-param (gnus-all-score-files group)))
2219                ((stringp (car score-param)))
2220                (t
2221                 (setq score-param (list (list score-param)))))
2222               (when score-param
2223                 (gnus-score-headers score-param))))
2224
2225           (unless (and (eq predicate 'gnus-agent-false)
2226                        (not marked-articles))
2227             (let ((arts (list nil)))
2228               (let ((arts-tail arts)
2229                     (alist (gnus-agent-load-alist group))
2230                     (marked-articles marked-articles)
2231                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2232                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2233                   (let ((num (mail-header-number gnus-headers)))
2234                     ;; Determine if this article is already in the cache
2235                     (while (and alist
2236                                 (> num (caar alist)))
2237                       (setq alist (cdr alist)))
2238
2239                     (unless (and (eq num (caar alist))
2240                                  (cdar alist))
2241
2242                       ;; Determine if this article was marked for download.
2243                       (while (and marked-articles
2244                                   (> num (car marked-articles)))
2245                         (setq marked-articles
2246                               (cdr marked-articles)))
2247
2248                       ;; When this article is marked, or selected by the
2249                       ;; predicate, add it to the download list
2250                       (when (or (eq num (car marked-articles))
2251                                 (let ((gnus-score
2252                                        (or (cdr
2253                                             (assq num gnus-newsgroup-scored))
2254                                            gnus-summary-default-score))
2255                                       (gnus-agent-long-article
2256                                        (gnus-agent-find-parameter
2257                                         group 'agent-long-article))
2258                                       (gnus-agent-short-article
2259                                        (gnus-agent-find-parameter
2260                                         group 'agent-short-article))
2261                                       (gnus-agent-low-score
2262                                        (gnus-agent-find-parameter
2263                                         group 'agent-low-score))
2264                                       (gnus-agent-high-score
2265                                        (gnus-agent-find-parameter
2266                                         group 'agent-high-score))
2267                                       (gnus-agent-expire-days
2268                                        (gnus-agent-find-parameter
2269                                         group 'agent-days-until-old)))
2270                                   (funcall predicate)))
2271                         (gnus-agent-append-to-list arts-tail num))))))
2272
2273               (let (fetched-articles)
2274                 ;; Fetch all selected articles
2275                 (setq gnus-newsgroup-undownloaded
2276                       (gnus-sorted-ndifference
2277                        gnus-newsgroup-undownloaded
2278                        (setq fetched-articles
2279                              (if (cdr arts)
2280                                  (gnus-agent-fetch-articles group (cdr arts))
2281                                nil))))
2282
2283                 (let ((unfetched-articles
2284                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2285                   (if gnus-newsgroup-active
2286                       ;; Update the summary buffer
2287                       (progn
2288                         (dolist (article marked-articles)
2289                           (gnus-summary-set-agent-mark article t))
2290                         (dolist (article fetched-articles)
2291                           (if gnus-agent-mark-unread-after-downloaded
2292                               (gnus-summary-mark-article
2293                                article gnus-unread-mark))
2294                           (when (gnus-summary-goto-subject article nil t)
2295                             (gnus-summary-update-download-mark article)))
2296                         (dolist (article unfetched-articles)
2297                           (gnus-summary-mark-article
2298                            article gnus-canceled-mark)))
2299
2300                     ;; Update the group buffer.
2301
2302                     ;; When some, or all, of the marked articles came
2303                     ;; from the download mark.  Remove that mark.  I
2304                     ;; didn't do this earlier as I only want to remove
2305                     ;; the marks after the fetch is completed.
2306
2307                     (dolist (mark gnus-agent-download-marks)
2308                       (when (eq mark 'download)
2309                         (let ((marked-arts
2310                                (assq mark (gnus-info-marks
2311                                            (setq info (gnus-get-info group))))))
2312                           (when (cdr marked-arts)
2313                             (setq marks
2314                                   (delq marked-arts (gnus-info-marks info)))
2315                             (gnus-info-set-marks info marks)))))
2316                     (let ((read (gnus-info-read
2317                                  (or info (setq info (gnus-get-info group))))))
2318                       (gnus-info-set-read
2319                        info (gnus-add-to-range read unfetched-articles)))
2320
2321                     (gnus-group-update-group group t)
2322                     (sit-for 0)
2323
2324                     (gnus-dribble-enter
2325                      (concat "(gnus-group-set-info '"
2326                              (gnus-prin1-to-string info)
2327                              ")"))))))))))))
2328
2329 ;;;
2330 ;;; Agent Category Mode
2331 ;;;
2332
2333 (defvar gnus-category-mode-hook nil
2334   "Hook run in `gnus-category-mode' buffers.")
2335
2336 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2337   "Format of category lines.
2338
2339 Valid specifiers include:
2340 %c  Topic name (string)
2341 %g  The number of groups in the topic (integer)
2342
2343 General format specifiers can also be used.  See Info node
2344 `(gnus)Formatting Variables'.")
2345
2346 (defvar gnus-category-mode-line-format "Gnus: %%b"
2347   "The format specification for the category mode line.")
2348
2349 (defvar gnus-agent-predicate 'false
2350   "The selection predicate used when no other source is available.")
2351
2352 (defvar gnus-agent-short-article 100
2353   "Articles that have fewer lines than this are short.")
2354
2355 (defvar gnus-agent-long-article 200
2356   "Articles that have more lines than this are long.")
2357
2358 (defvar gnus-agent-low-score 0
2359   "Articles that have a score lower than this have a low score.")
2360
2361 (defvar gnus-agent-high-score 0
2362   "Articles that have a score higher than this have a high score.")
2363
2364
2365 ;;; Internal variables.
2366
2367 (defvar gnus-category-buffer "*Agent Category*")
2368
2369 (defvar gnus-category-line-format-alist
2370   `((?c gnus-tmp-name ?s)
2371     (?g gnus-tmp-groups ?d)))
2372
2373 (defvar gnus-category-mode-line-format-alist
2374   `((?u user-defined ?s)))
2375
2376 (defvar gnus-category-line-format-spec nil)
2377 (defvar gnus-category-mode-line-format-spec nil)
2378
2379 (defvar gnus-category-mode-map nil)
2380 (put 'gnus-category-mode 'mode-class 'special)
2381
2382 (unless gnus-category-mode-map
2383   (setq gnus-category-mode-map (make-sparse-keymap))
2384   (suppress-keymap gnus-category-mode-map)
2385
2386   (gnus-define-keys gnus-category-mode-map
2387     "q" gnus-category-exit
2388     "k" gnus-category-kill
2389     "c" gnus-category-copy
2390     "a" gnus-category-add
2391     "e" gnus-agent-customize-category
2392     "p" gnus-category-edit-predicate
2393     "g" gnus-category-edit-groups
2394     "s" gnus-category-edit-score
2395     "l" gnus-category-list
2396
2397     "\C-c\C-i" gnus-info-find-node
2398     "\C-c\C-b" gnus-bug))
2399
2400 (defvar gnus-category-menu-hook nil
2401   "*Hook run after the creation of the menu.")
2402
2403 (defun gnus-category-make-menu-bar ()
2404   (gnus-turn-off-edit-menu 'category)
2405   (unless (boundp 'gnus-category-menu)
2406     (easy-menu-define
2407      gnus-category-menu gnus-category-mode-map ""
2408      '("Categories"
2409        ["Add" gnus-category-add t]
2410        ["Kill" gnus-category-kill t]
2411        ["Copy" gnus-category-copy t]
2412        ["Edit category" gnus-agent-customize-category t]
2413        ["Edit predicate" gnus-category-edit-predicate t]
2414        ["Edit score" gnus-category-edit-score t]
2415        ["Edit groups" gnus-category-edit-groups t]
2416        ["Exit" gnus-category-exit t]))
2417
2418     (gnus-run-hooks 'gnus-category-menu-hook)))
2419
2420 (defun gnus-category-mode ()
2421   "Major mode for listing and editing agent categories.
2422
2423 All normal editing commands are switched off.
2424 \\<gnus-category-mode-map>
2425 For more in-depth information on this mode, read the manual
2426 \(`\\[gnus-info-find-node]').
2427
2428 The following commands are available:
2429
2430 \\{gnus-category-mode-map}"
2431   (interactive)
2432   (when (gnus-visual-p 'category-menu 'menu)
2433     (gnus-category-make-menu-bar))
2434   (kill-all-local-variables)
2435   (gnus-simplify-mode-line)
2436   (setq major-mode 'gnus-category-mode)
2437   (setq mode-name "Category")
2438   (gnus-set-default-directory)
2439   (setq mode-line-process nil)
2440   (use-local-map gnus-category-mode-map)
2441   (buffer-disable-undo)
2442   (setq truncate-lines t)
2443   (setq buffer-read-only t)
2444   (gnus-run-hooks 'gnus-category-mode-hook))
2445
2446 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2447
2448 (defun gnus-category-insert-line (category)
2449   (let* ((gnus-tmp-name (format "%s" (car category)))
2450          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2451     (beginning-of-line)
2452     (gnus-add-text-properties
2453      (point)
2454      (prog1 (1+ (point))
2455        ;; Insert the text.
2456        (eval gnus-category-line-format-spec))
2457      (list 'gnus-category gnus-tmp-name))))
2458
2459 (defun gnus-enter-category-buffer ()
2460   "Go to the Category buffer."
2461   (interactive)
2462   (gnus-category-setup-buffer)
2463   (gnus-configure-windows 'category)
2464   (gnus-category-prepare))
2465
2466 (defun gnus-category-setup-buffer ()
2467   (unless (get-buffer gnus-category-buffer)
2468     (save-excursion
2469       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2470       (gnus-category-mode))))
2471
2472 (defun gnus-category-prepare ()
2473   (gnus-set-format 'category-mode)
2474   (gnus-set-format 'category t)
2475   (let ((alist gnus-category-alist)
2476         (buffer-read-only nil))
2477     (erase-buffer)
2478     (while alist
2479       (gnus-category-insert-line (pop alist)))
2480     (goto-char (point-min))
2481     (gnus-category-position-point)))
2482
2483 (defun gnus-category-name ()
2484   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2485       (error "No category on the current line")))
2486
2487 (defun gnus-category-read ()
2488   "Read the category alist."
2489   (setq gnus-category-alist
2490         (or
2491          (with-temp-buffer
2492            (ignore-errors
2493             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2494             (goto-char (point-min))
2495             ;; This code isn't temp, it will be needed so long as
2496             ;; anyone may be migrating from an older version.
2497
2498             ;; Once we're certain that people will not revert to an
2499             ;; earlier version, we can take out the old-list code in
2500             ;; gnus-category-write.
2501             (let* ((old-list (read (current-buffer)))
2502                    (new-list (ignore-errors (read (current-buffer)))))
2503               (if new-list
2504                   new-list
2505                 ;; Convert from a positional list to an alist.
2506                 (mapcar
2507                  (lambda (c)
2508                    (setcdr c
2509                            (delq nil
2510                                  (gnus-mapcar
2511                                   (lambda (valu symb)
2512                                     (if valu
2513                                         (cons symb valu)))
2514                                   (cdr c)
2515                                   '(agent-predicate agent-score-file agent-groups))))
2516                    c)
2517                  old-list)))))
2518          (list (gnus-agent-cat-make 'default 'short)))))
2519
2520 (defun gnus-category-write ()
2521   "Write the category alist."
2522   (setq gnus-category-predicate-cache nil
2523         gnus-category-group-cache nil)
2524   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2525   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2526     ;; This prin1 is temporary.  It exists so that people can revert
2527     ;; to an earlier version of gnus-agent.
2528     (prin1 (mapcar (lambda (c)
2529               (list (car c)
2530                     (cdr (assoc 'agent-predicate c))
2531                     (cdr (assoc 'agent-score-file c))
2532                     (cdr (assoc 'agent-groups c))))
2533                    gnus-category-alist)
2534            (current-buffer))
2535     (newline)
2536     (prin1 gnus-category-alist (current-buffer))))
2537
2538 (defun gnus-category-edit-predicate (category)
2539   "Edit the predicate for CATEGORY."
2540   (interactive (list (gnus-category-name)))
2541   (let ((info (assq category gnus-category-alist)))
2542     (gnus-edit-form
2543      (gnus-agent-cat-predicate info)
2544      (format "Editing the select predicate for category %s" category)
2545      `(lambda (predicate)
2546         ;; Avoid run-time execution of setf form
2547         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2548         ;;       predicate)
2549         ;; use its expansion instead:
2550         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2551                                      'agent-predicate predicate)
2552
2553         (gnus-category-write)
2554         (gnus-category-list)))))
2555
2556 (defun gnus-category-edit-score (category)
2557   "Edit the score expression for CATEGORY."
2558   (interactive (list (gnus-category-name)))
2559   (let ((info (assq category gnus-category-alist)))
2560     (gnus-edit-form
2561      (gnus-agent-cat-score-file info)
2562      (format "Editing the score expression for category %s" category)
2563      `(lambda (score-file)
2564         ;; Avoid run-time execution of setf form
2565         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2566         ;;       score-file)
2567         ;; use its expansion instead:
2568         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2569                                      'agent-score-file score-file)
2570
2571         (gnus-category-write)
2572         (gnus-category-list)))))
2573
2574 (defun gnus-category-edit-groups (category)
2575   "Edit the group list for CATEGORY."
2576   (interactive (list (gnus-category-name)))
2577   (let ((info (assq category gnus-category-alist)))
2578     (gnus-edit-form
2579      (gnus-agent-cat-groups info)
2580      (format "Editing the group list for category %s" category)
2581      `(lambda (groups)
2582         ;; Avoid run-time execution of setf form
2583         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2584         ;;       groups)
2585         ;; use its expansion instead:
2586         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2587                                    groups)
2588
2589         (gnus-category-write)
2590         (gnus-category-list)))))
2591
2592 (defun gnus-category-kill (category)
2593   "Kill the current category."
2594   (interactive (list (gnus-category-name)))
2595   (let ((info (assq category gnus-category-alist))
2596         (buffer-read-only nil))
2597     (gnus-delete-line)
2598     (setq gnus-category-alist (delq info gnus-category-alist))
2599     (gnus-category-write)))
2600
2601 (defun gnus-category-copy (category to)
2602   "Copy the current category."
2603   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2604   (let ((info (assq category gnus-category-alist)))
2605     (push (let ((newcat (gnus-copy-sequence info)))
2606             (setf (gnus-agent-cat-name newcat) to)
2607             (setf (gnus-agent-cat-groups newcat) nil)
2608             newcat)
2609           gnus-category-alist)
2610     (gnus-category-write)
2611     (gnus-category-list)))
2612
2613 (defun gnus-category-add (category)
2614   "Create a new category."
2615   (interactive "SCategory name: ")
2616   (when (assq category gnus-category-alist)
2617     (error "Category %s already exists" category))
2618   (push (gnus-agent-cat-make category)
2619         gnus-category-alist)
2620   (gnus-category-write)
2621   (gnus-category-list))
2622
2623 (defun gnus-category-list ()
2624   "List all categories."
2625   (interactive)
2626   (gnus-category-prepare))
2627
2628 (defun gnus-category-exit ()
2629   "Return to the group buffer."
2630   (interactive)
2631   (kill-buffer (current-buffer))
2632   (gnus-configure-windows 'group t))
2633
2634 ;; To avoid having 8-bit characters in the source file.
2635 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2636
2637 (defvar gnus-category-predicate-alist
2638   '((spam . gnus-agent-spam-p)
2639     (short . gnus-agent-short-p)
2640     (long . gnus-agent-long-p)
2641     (low . gnus-agent-low-scored-p)
2642     (high . gnus-agent-high-scored-p)
2643     (read . gnus-agent-read-p)
2644     (true . gnus-agent-true)
2645     (false . gnus-agent-false))
2646   "Mapping from short score predicate symbols to predicate functions.")
2647
2648 (defun gnus-agent-spam-p ()
2649   "Say whether an article is spam or not."
2650   (unless gnus-agent-spam-hashtb
2651     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2652   (if (not (equal (mail-header-references gnus-headers) ""))
2653       nil
2654     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2655       (prog1
2656           (gnus-gethash string gnus-agent-spam-hashtb)
2657         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2658
2659 (defun gnus-agent-short-p ()
2660   "Say whether an article is short or not."
2661   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2662
2663 (defun gnus-agent-long-p ()
2664   "Say whether an article is long or not."
2665   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2666
2667 (defun gnus-agent-low-scored-p ()
2668   "Say whether an article has a low score or not."
2669   (< gnus-score gnus-agent-low-score))
2670
2671 (defun gnus-agent-high-scored-p ()
2672   "Say whether an article has a high score or not."
2673   (> gnus-score gnus-agent-high-score))
2674
2675 (defun gnus-agent-read-p ()
2676   "Say whether an article is read or not."
2677   (gnus-member-of-range (mail-header-number gnus-headers)
2678                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2679
2680 (defun gnus-category-make-function (predicate)
2681   "Make a function from PREDICATE."
2682   (let ((func (gnus-category-make-function-1 predicate)))
2683     (if (and (= (length func) 1)
2684              (symbolp (car func)))
2685         (car func)
2686       (gnus-byte-compile `(lambda () ,func)))))
2687
2688 (defun gnus-agent-true ()
2689   "Return t."
2690   t)
2691
2692 (defun gnus-agent-false ()
2693   "Return nil."
2694   nil)
2695
2696 (defun gnus-category-make-function-1 (predicate)
2697   "Make a function from PREDICATE."
2698   (cond
2699    ;; Functions are just returned as is.
2700    ((or (symbolp predicate)
2701         (functionp predicate))
2702     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2703            predicate)))
2704    ;; More complex predicate.
2705    ((consp predicate)
2706     `(,(cond
2707         ((memq (car predicate) '(& and))
2708          'and)
2709         ((memq (car predicate) '(| or))
2710          'or)
2711         ((memq (car predicate) gnus-category-not)
2712          'not))
2713       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2714    (t
2715     (error "Unknown predicate type: %s" predicate))))
2716
2717 (defun gnus-get-predicate (predicate)
2718   "Return the function implementing PREDICATE."
2719   (or (cdr (assoc predicate gnus-category-predicate-cache))
2720       (let ((func (gnus-category-make-function predicate)))
2721         (setq gnus-category-predicate-cache
2722               (nconc gnus-category-predicate-cache
2723                      (list (cons predicate func))))
2724         func)))
2725
2726 (defun gnus-predicate-implies-unread (predicate)
2727   "Say whether PREDICATE implies unread articles only.
2728 It is okay to miss some cases, but there must be no false positives.
2729 That is, if this predicate returns true, then indeed the predicate must
2730 return only unread articles."
2731   (eq t (gnus-function-implies-unread-1 
2732          (gnus-category-make-function-1 predicate))))
2733
2734 (defun gnus-function-implies-unread-1 (function)
2735   "Recursively evaluate a predicate function to determine whether it can select
2736 any read articles.  Returns t if the function is known to never
2737 return read articles, nil when it is known to always return read
2738 articles, and t_nil when the function may return both read and unread
2739 articles."
2740   (let ((func (car function))
2741         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2742     (cond ((eq func 'and)
2743            (cond ((memq t args) ; if any argument returns only unread articles
2744                   ;; then that argument constrains the result to only unread articles.
2745                   t)
2746                  ((memq 't_nil args) ; if any argument is indeterminate
2747                   ;; then the result is indeterminate
2748                   't_nil)))
2749           ((eq func 'or)
2750            (cond ((memq nil args) ; if any argument returns read articles
2751                   ;; then that argument ensures that the results includes read articles.
2752                   nil)
2753                  ((memq 't_nil args) ; if any argument is indeterminate
2754                   ;; then that argument ensures that the results are indeterminate
2755                   't_nil)
2756                  (t ; if all arguments return only unread articles
2757                   ;; then the result returns only unread articles
2758                   t)))
2759           ((eq func 'not)
2760            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2761                   ; then the result is indeterminate
2762                   (car args))
2763                  (t ; otherwise
2764                   ; toggle the result to be the opposite of the argument
2765                   (not (car args)))))
2766           ((eq func 'gnus-agent-read-p)
2767            nil) ; The read predicate NEVER returns unread articles
2768           ((eq func 'gnus-agent-false)
2769            t) ; The false predicate returns t as the empty set excludes all read articles
2770           ((eq func 'gnus-agent-true)
2771            nil) ; The true predicate ALWAYS returns read articles
2772           ((catch 'found-match
2773              (let ((alist gnus-category-predicate-alist))
2774                (while alist
2775                  (if (eq func (cdar alist))
2776                      (throw 'found-match t)
2777                    (setq alist (cdr alist))))))
2778            't_nil) ; All other predicates return read and unread articles
2779           (t
2780            (error "Unknown predicate function: %s" function)))))
2781
2782 (defun gnus-group-category (group)
2783   "Return the category GROUP belongs to."
2784   (unless gnus-category-group-cache
2785     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2786     (let ((cs gnus-category-alist)
2787           groups cat)
2788       (while (setq cat (pop cs))
2789         (setq groups (gnus-agent-cat-groups cat))
2790         (while groups
2791           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2792   (or (gnus-gethash group gnus-category-group-cache)
2793       (assq 'default gnus-category-alist)))
2794
2795 (defun gnus-agent-expire-group (group &optional articles force)
2796   "Expire all old articles in GROUP.
2797 If you want to force expiring of certain articles, this function can
2798 take ARTICLES, and FORCE parameters as well.
2799
2800 The articles on which the expiration process runs are selected as follows:
2801   if ARTICLES is null, all read and unmarked articles.
2802   if ARTICLES is t, all articles.
2803   if ARTICLES is a list, just those articles.
2804 FORCE is equivalent to setting the expiration predicates to true."
2805   (interactive
2806    (list (let ((def (or (gnus-group-group-name)
2807                         gnus-newsgroup-name)))
2808            (let ((select (read-string (if def
2809                                           (concat "Group Name ("
2810                                                   def "): ")
2811                                         "Group Name: "))))
2812              (if (and (equal "" select)
2813                       def)
2814                  def
2815                select)))))
2816
2817   (if (not group)
2818       (gnus-agent-expire articles group force)
2819     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2820           ;; expiration statistics of this single group
2821           (gnus-agent-expire-stats (list 0 0 0.0)))
2822       (if (or (not (eq articles t))
2823               (yes-or-no-p
2824                (concat "Are you sure that you want to "
2825                        "expire all articles in " group ".")))
2826           (let ((gnus-command-method (gnus-find-method-for-group group))
2827                 (overview (gnus-get-buffer-create " *expire overview*"))
2828                 orig)
2829             (unwind-protect
2830                 (let ((active-file (gnus-agent-lib-file "active")))
2831                   (when (file-exists-p active-file)
2832                     (with-temp-buffer
2833                       (nnheader-insert-file-contents active-file)
2834                       (gnus-active-to-gnus-format
2835                        gnus-command-method
2836                        (setq orig (gnus-make-hashtable
2837                                    (count-lines (point-min) (point-max))))))
2838                     (save-excursion
2839                       (gnus-agent-expire-group-1
2840                        group overview (gnus-gethash-safe group orig)
2841                        articles force))))
2842               (kill-buffer overview))))
2843       (gnus-message 4 (gnus-agent-expire-done-message)))))
2844
2845 (defun gnus-agent-expire-group-1 (group overview active articles force)
2846   ;; Internal function - requires caller to have set
2847   ;; gnus-command-method, initialized overview buffer, and to have
2848   ;; provided a non-nil active
2849
2850   (let ((dir (gnus-agent-group-pathname group)))
2851     (gnus-agent-with-refreshed-group 
2852      group
2853      (when (boundp 'gnus-agent-expire-current-dirs)
2854        (set 'gnus-agent-expire-current-dirs 
2855             (cons dir 
2856                   (symbol-value 'gnus-agent-expire-current-dirs))))
2857
2858      (if (and (not force)
2859               (eq 'DISABLE (gnus-agent-find-parameter group 
2860                                                       'agent-enable-expiration)))
2861          (gnus-message 5 "Expiry skipping over %s" group)
2862        (gnus-message 5 "Expiring articles in %s" group)
2863        (gnus-agent-load-alist group)
2864        (let* ((bytes-freed 0)
2865               (size-files-deleted 0.0)
2866               (files-deleted 0)
2867               (nov-entries-deleted 0)
2868               (info (gnus-get-info group))
2869               (alist gnus-agent-article-alist)
2870               (day (- (time-to-days (current-time))
2871                       (gnus-agent-find-parameter group 'agent-days-until-old)))
2872               (specials (if (and alist
2873                                  (not force))
2874                             ;; This could be a bit of a problem.  I need to
2875                             ;; keep the last article to avoid refetching
2876                             ;; headers when using nntp in the backend.  At
2877                             ;; the same time, if someone uses a backend
2878                             ;; that supports article moving then I may have
2879                             ;; to remove the last article to complete the
2880                             ;; move.  Right now, I'm going to assume that
2881                             ;; FORCE overrides specials.
2882                             (list (caar (last alist)))))
2883               (unreads ;; Articles that are excluded from the
2884                ;; expiration process
2885                (cond (gnus-agent-expire-all
2886                       ;; All articles are marked read by global decree
2887                       nil)
2888                      ((eq articles t)
2889                       ;; All articles are marked read by function
2890                       ;; parameter
2891                       nil)
2892                      ((not articles)
2893                       ;; Unread articles are marked protected from
2894                       ;; expiration Don't call
2895                       ;; gnus-list-of-unread-articles as it returns
2896                       ;; articles that have not been fetched into the
2897                       ;; agent.
2898                       (ignore-errors
2899                         (gnus-agent-unread-articles group)))
2900                      (t
2901                       ;; All articles EXCEPT those named by the caller
2902                       ;; are protected from expiration
2903                       (gnus-sorted-difference
2904                        (gnus-uncompress-range
2905                         (cons (caar alist)
2906                               (caar (last alist))))
2907                        (sort articles '<)))))
2908               (marked ;; More articles that are excluded from the
2909                ;; expiration process
2910                (cond (gnus-agent-expire-all
2911                       ;; All articles are unmarked by global decree
2912                       nil)
2913                      ((eq articles t)
2914                       ;; All articles are unmarked by function
2915                       ;; parameter
2916                       nil)
2917                      (articles
2918                       ;; All articles may as well be unmarked as the
2919                       ;; unreads list already names the articles we are
2920                       ;; going to keep
2921                       nil)
2922                      (t
2923                       ;; Ticked and/or dormant articles are excluded
2924                       ;; from expiration
2925                       (nconc
2926                        (gnus-uncompress-range
2927                         (cdr (assq 'tick (gnus-info-marks info))))
2928                        (gnus-uncompress-range
2929                         (cdr (assq 'dormant
2930                                    (gnus-info-marks info))))))))
2931               (nov-file (concat dir ".overview"))
2932               (cnt 0)
2933               (completed -1)
2934               dlist
2935               type)
2936
2937          ;; The normal article alist contains elements that look like
2938          ;; (article# .  fetch_date) I need to combine other
2939          ;; information with this list.  For example, a flag indicating
2940          ;; that a particular article MUST BE KEPT.  To do this, I'm
2941          ;; going to transform the elements to look like (article#
2942          ;; fetch_date keep_flag NOV_entry_marker) Later, I'll reverse
2943          ;; the process to generate the expired article alist.
2944
2945          ;; Convert the alist elements to (article# fetch_date nil
2946          ;; nil).
2947          (setq dlist (mapcar (lambda (e)
2948                                (list (car e) (cdr e) nil nil)) alist))
2949
2950          ;; Convert the keep lists to elements that look like (article#
2951          ;; nil keep_flag nil) then append it to the expanded dlist
2952          ;; These statements are sorted by ascending precidence of the
2953          ;; keep_flag.
2954          (setq dlist (nconc dlist
2955                             (mapcar (lambda (e)
2956                                       (list e nil 'unread  nil))
2957                                     unreads)))
2958          (setq dlist (nconc dlist
2959                             (mapcar (lambda (e)
2960                                       (list e nil 'marked  nil))
2961                                     marked)))
2962          (setq dlist (nconc dlist
2963                             (mapcar (lambda (e)
2964                                       (list e nil 'special nil))
2965                                     specials)))
2966
2967          (set-buffer overview)
2968          (erase-buffer)
2969          (buffer-disable-undo)
2970          (when (file-exists-p nov-file)
2971            (gnus-message 7 "gnus-agent-expire: Loading overview...")
2972            (nnheader-insert-file-contents nov-file)
2973            (goto-char (point-min))
2974
2975            (let (p)
2976              (while (< (setq p (point)) (point-max))
2977                (condition-case nil
2978                    ;; If I successfully read an integer (the plus zero
2979                    ;; ensures a numeric type), prepend a marker entry
2980                    ;; to the list
2981                    (push (list (+ 0 (read (current-buffer))) nil nil
2982                                (set-marker (make-marker) p))
2983                          dlist)
2984                  (error
2985                   (gnus-message 1 "gnus-agent-expire: read error \
2986 occurred when reading expression at %s in %s.  Skipping to next \
2987 line." (point) nov-file)))
2988                ;; Whether I succeeded, or failed, it doesn't matter.
2989                ;; Move to the next line then try again.
2990                (forward-line 1)))
2991
2992            (gnus-message
2993             7 "gnus-agent-expire: Loading overview... Done"))
2994          (set-buffer-modified-p nil)
2995
2996          ;; At this point, all of the information is in dlist.  The
2997          ;; only problem is that much of it is spread across multiple
2998          ;; entries.  Sort then MERGE!!
2999          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
3000          ;; If two entries have the same article-number then sort by
3001          ;; ascending keep_flag.
3002          (let ((special 0)
3003                (marked 1)
3004                (unread 2))
3005            (setq dlist
3006                  (sort dlist
3007                        (lambda (a b)
3008                          (cond ((< (nth 0 a) (nth 0 b))
3009                                 t)
3010                                ((> (nth 0 a) (nth 0 b))
3011                                 nil)
3012                                (t
3013                                 (let ((a (or (symbol-value (nth 2 a))
3014                                              3))
3015                                       (b (or (symbol-value (nth 2 b))
3016                                              3)))
3017                                   (<= a b))))))))
3018          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3019          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3020          (let ((dlist dlist))
3021            (while (cdr dlist)           ; I'm not at the end-of-list
3022              (if (eq (caar dlist) (caadr dlist))
3023                  (let ((first (cdr (car dlist)))
3024                        (secnd (cdr (cadr dlist))))
3025                    (setcar first (or (car first)
3026                                      (car secnd))) ; fetch_date
3027                    (setq first (cdr first)
3028                          secnd (cdr secnd))
3029                    (setcar first (or (car first)
3030                                      (car secnd))) ; Keep_flag
3031                    (setq first (cdr first)
3032                          secnd (cdr secnd))
3033                    (setcar first (or (car first)
3034                                      (car secnd))) ; NOV_entry_marker
3035
3036                    (setcdr dlist (cddr dlist)))
3037                (setq dlist (cdr dlist)))))
3038          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3039
3040          (let* ((len (float (length dlist)))
3041                 (alist (list nil))
3042                 (tail-alist alist))
3043            (while dlist
3044              (let ((new-completed (truncate (* 100.0
3045                                                (/ (setq cnt (1+ cnt))
3046                                                   len))))
3047                    message-log-max)
3048                (when (> new-completed completed)
3049                  (setq completed new-completed)
3050                  (gnus-message 7 "%3d%% completed..."  completed)))
3051              (let* ((entry          (car dlist))
3052                     (article-number (nth 0 entry))
3053                     (fetch-date     (nth 1 entry))
3054                     (keep           (nth 2 entry))
3055                     (marker         (nth 3 entry)))
3056
3057                (cond
3058                 ;; Kept articles are unread, marked, or special.
3059                 (keep
3060                  (gnus-agent-message 10
3061                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3062                                      group article-number keep (if fetch-date " and file" ""))
3063                  (when fetch-date
3064                    (unless (file-exists-p
3065                             (concat dir (number-to-string
3066                                          article-number)))
3067                      (setf (nth 1 entry) nil)
3068                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3069 download flag on %s:%d as the cached article file is missing."
3070                                          group (caar dlist)))
3071                    (unless marker
3072                      (gnus-message 1 "gnus-agent-expire detected a \
3073 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3074                  (gnus-agent-append-to-list
3075                   tail-alist
3076                   (cons article-number fetch-date)))
3077
3078                 ;; The following articles are READ, UNMARKED, and
3079                 ;; ORDINARY.  See if they can be EXPIRED!!!
3080                 ((setq type
3081                        (cond
3082                         ((not (integerp fetch-date))
3083                          'read) ;; never fetched article (may expire
3084                         ;; right now)
3085                         ((not (file-exists-p
3086                                (concat dir (number-to-string
3087                                             article-number))))
3088                          (setf (nth 1 entry) nil)
3089                          'externally-expired) ;; Can't find the cached
3090                         ;; article.  Handle case
3091                         ;; as though this article
3092                         ;; was never fetched.
3093
3094                         ;; We now have the arrival day, so we see
3095                         ;; whether it's old enough to be expired.
3096                         ((< fetch-date day)
3097                          'expired)
3098                         (force
3099                          'forced)))
3100
3101                  ;; I found some reason to expire this entry.
3102
3103                  (let ((actions nil))
3104                    (when (memq type '(forced expired))
3105                      (ignore-errors     ; Just being paranoid.
3106                        (let* ((file-name (nnheader-concat dir (number-to-string
3107                                                                article-number)))
3108                               (size (float (nth 7 (file-attributes file-name)))))
3109                          (incf bytes-freed size)
3110                          (incf size-files-deleted size)
3111                          (incf files-deleted)
3112                          (delete-file file-name))
3113                        (push "expired cached article" actions))
3114                      (setf (nth 1 entry) nil)
3115                      )
3116
3117                    (when marker
3118                      (push "NOV entry removed" actions)
3119                      (goto-char marker)
3120
3121                      (incf nov-entries-deleted)
3122
3123                      (let ((from (point-at-bol))
3124                            (to (progn (forward-line 1) (point))))
3125                        (incf bytes-freed (- to from))
3126                        (delete-region from to)))
3127
3128                    ;; If considering all articles is set, I can only
3129                    ;; expire article IDs that are no longer in the
3130                    ;; active range (That is, articles that preceed the
3131                    ;; first article in the new alist).
3132                    (if (and gnus-agent-consider-all-articles
3133                             (>= article-number (car active)))
3134                        ;; I have to keep this ID in the alist
3135                        (gnus-agent-append-to-list
3136                         tail-alist (cons article-number fetch-date))
3137                      (push (format "Removed %s article number from \
3138 article alist" type) actions))
3139
3140                    (when actions
3141                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3142                                          group article-number
3143                                          (mapconcat 'identity actions ", ")))))
3144                 (t
3145                  (gnus-agent-message
3146                   10 "gnus-agent-expire: %s:%d: Article kept as \
3147 expiration tests failed." group article-number)
3148                  (gnus-agent-append-to-list
3149                   tail-alist (cons article-number fetch-date)))
3150                 )
3151
3152                ;; Clean up markers as I want to recycle this buffer
3153                ;; over several groups.
3154                (when marker
3155                  (set-marker marker nil))
3156
3157                (setq dlist (cdr dlist))))
3158
3159            (setq alist (cdr alist))
3160
3161            (let ((inhibit-quit t))
3162              (unless (equal alist gnus-agent-article-alist)
3163                (setq gnus-agent-article-alist alist)
3164                (gnus-agent-save-alist group))
3165
3166              (when (buffer-modified-p)
3167                (gnus-make-directory dir)
3168                (write-region-as-coding-system gnus-agent-file-coding-system
3169                                               (point-min) (point-max) nov-file
3170                                               nil 'silent)
3171                ;; clear the modified flag as that I'm not confused by
3172                ;; its status on the next pass through this routine.
3173                (set-buffer-modified-p nil)
3174                (gnus-agent-update-view-total-fetched-for group t))
3175
3176              (when (eq articles t)
3177                (gnus-summary-update-info))))
3178
3179          (when (boundp 'gnus-agent-expire-stats)
3180            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3181              (incf (nth 2 stats) bytes-freed)
3182              (incf (nth 1 stats) files-deleted)
3183              (incf (nth 0 stats) nov-entries-deleted)))
3184
3185          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3186
3187 (defun gnus-agent-expire (&optional articles group force)
3188   "Expire all old articles.
3189 If you want to force expiring of certain articles, this function can
3190 take ARTICLES, GROUP and FORCE parameters as well.
3191
3192 The articles on which the expiration process runs are selected as follows:
3193   if ARTICLES is null, all read and unmarked articles.
3194   if ARTICLES is t, all articles.
3195   if ARTICLES is a list, just those articles.
3196 Setting GROUP will limit expiration to that group.
3197 FORCE is equivalent to setting the expiration predicates to true."
3198   (interactive)
3199   
3200   (if group
3201       (gnus-agent-expire-group group articles force)
3202     (if (or (not (eq articles t))
3203             (yes-or-no-p "Are you sure that you want to expire all \
3204 articles in every agentized group."))
3205         (let ((methods (gnus-agent-covered-methods))
3206               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3207               ;; of agent directories.
3208               (gnus-agent-expire-current-dirs nil)
3209               ;; Bind gnus-agent-expire-stats to enable tracking of
3210               ;; expiration statistics across all groups
3211               (gnus-agent-expire-stats (list 0 0 0.0))
3212               gnus-command-method overview orig)
3213           (setq overview (gnus-get-buffer-create " *expire overview*"))
3214           (unwind-protect
3215               (while (setq gnus-command-method (pop methods))
3216                 (let ((active-file (gnus-agent-lib-file "active")))
3217                   (when (file-exists-p active-file)
3218                     (with-temp-buffer
3219                       (nnheader-insert-file-contents active-file)
3220                       (gnus-active-to-gnus-format
3221                        gnus-command-method
3222                        (setq orig (gnus-make-hashtable
3223                                    (count-lines (point-min) (point-max))))))
3224                     (dolist (expiring-group (gnus-groups-from-server
3225                                              gnus-command-method))
3226                       (let* ((active
3227                               (gnus-gethash-safe expiring-group orig)))
3228                                         
3229                         (when active
3230                           (save-excursion
3231                             (gnus-agent-expire-group-1
3232                              expiring-group overview active articles force))))))))
3233             (kill-buffer overview))
3234           (gnus-agent-expire-unagentized-dirs)
3235           (gnus-message 4 (gnus-agent-expire-done-message))))))
3236
3237 (defun gnus-agent-expire-done-message ()
3238   (if (and (> gnus-verbose 4)
3239            (boundp 'gnus-agent-expire-stats))
3240       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3241              (size (nth 2 stats))
3242             (units '(B KB MB GB)))
3243         (while (and (> size 1024.0)
3244                     (cdr units))
3245           (setq size (/ size 1024.0)
3246                 units (cdr units)))
3247
3248         (format "Expiry recovered %d NOV entries, deleted %d files,\
3249  and freed %f %s." 
3250                 (nth 0 stats) 
3251                 (nth 1 stats) 
3252                 size (car units)))
3253     "Expiry...done"))
3254
3255 (defun gnus-agent-expire-unagentized-dirs ()
3256   (when (and gnus-agent-expire-unagentized-dirs
3257              (boundp 'gnus-agent-expire-current-dirs))
3258     (let* ((keep (gnus-make-hashtable))
3259            ;; Formally bind gnus-agent-expire-current-dirs so that the
3260            ;; compiler will not complain about free references.
3261            (gnus-agent-expire-current-dirs
3262             (symbol-value 'gnus-agent-expire-current-dirs))
3263            dir)
3264
3265       (gnus-sethash gnus-agent-directory t keep)
3266       (while gnus-agent-expire-current-dirs
3267         (setq dir (pop gnus-agent-expire-current-dirs))
3268         (when (and (stringp dir)
3269                    (file-directory-p dir))
3270           (while (not (gnus-gethash dir keep))
3271             (gnus-sethash dir t keep)
3272             (setq dir (file-name-directory (directory-file-name dir))))))
3273
3274       (let* (to-remove
3275              checker
3276              (checker
3277               (function
3278                (lambda (d)
3279                  "Given a directory, check it and its subdirectories for 
3280               membership in the keep hash.  If it isn't found, add 
3281               it to to-remove." 
3282                  (let ((files (directory-files d))
3283                        file)
3284                    (while (setq file (pop files))
3285                      (cond ((equal file ".") ; Ignore self
3286                             nil)
3287                            ((equal file "..") ; Ignore parent
3288                             nil)
3289                            ((equal file ".overview") 
3290                             ;; Directory must contain .overview to be
3291                             ;; agent's cache of a group.
3292                             (let ((d (file-name-as-directory d))
3293                                   r)
3294                               ;; Search ancestor's for last directory NOT
3295                               ;; found in keep hash.
3296                               (while (not (gnus-gethash
3297                                            (setq d (file-name-directory d)) keep))
3298                                 (setq r d
3299                                       d (directory-file-name d)))
3300                               ;; if ANY ancestor was NOT in keep hash and
3301                               ;; it it's already in to-remove, add it to
3302                               ;; to-remove.                          
3303                               (if (and r
3304                                        (not (member r to-remove)))
3305                                   (push r to-remove))))
3306                            ((file-directory-p (setq file (nnheader-concat d file)))
3307                             (funcall checker file)))))))))
3308         (funcall checker (expand-file-name gnus-agent-directory))
3309
3310         (when (and to-remove
3311                    (or gnus-expert-user
3312                        (gnus-y-or-n-p
3313                         "gnus-agent-expire has identified local directories that are\
3314  not currently required by any agentized group.  Do you wish to consider\
3315  deleting them?")))
3316           (while to-remove
3317             (let ((dir (pop to-remove)))
3318               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3319                   (let* (delete-recursive
3320                          (delete-recursive
3321                           (function
3322                            (lambda (f-or-d)
3323                              (ignore-errors
3324                                (if (file-directory-p f-or-d)
3325                                    (condition-case nil
3326                                        (delete-directory f-or-d)
3327                                      (file-error
3328                                       (mapcar (lambda (f)
3329                                                 (or (member f '("." ".."))
3330                                                     (funcall delete-recursive
3331                                                              (nnheader-concat
3332                                                               f-or-d f))))
3333                                               (directory-files f-or-d))
3334                                       (delete-directory f-or-d)))
3335                                  (delete-file f-or-d)))))))
3336                     (funcall delete-recursive dir))))))))))
3337
3338 ;;;###autoload
3339 (defun gnus-agent-batch ()
3340   "Start Gnus, send queue and fetch session."
3341   (interactive)
3342   (let ((init-file-user "")
3343         (gnus-always-read-dribble-file t))
3344     (gnus))
3345   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3346     (gnus-group-send-queue)
3347     (gnus-agent-fetch-session)))
3348
3349 (defun gnus-agent-unread-articles (group)
3350   (let* ((read (gnus-info-read (gnus-get-info group)))
3351          (known (gnus-agent-load-alist group))
3352          (unread (list nil))
3353          (tail-unread unread))
3354     (while (and known read)
3355       (let ((candidate (car (pop known))))
3356         (while (let* ((range (car read))
3357                       (min   (if (numberp range) range (car range)))
3358                       (max   (if (numberp range) range (cdr range))))
3359                  (cond ((or (not min)
3360                             (< candidate min))
3361                         (gnus-agent-append-to-list tail-unread candidate)
3362                         nil)
3363                        ((> candidate max)
3364                         (setq read (cdr read))
3365                         ;; return t so that I always loop one more
3366                         ;; time.  If I just iterated off the end of
3367                         ;; read, min will become nil and the current
3368                         ;; candidate will be added to the unread list.
3369                         t))))))
3370     (while known
3371       (gnus-agent-append-to-list tail-unread (car (pop known))))
3372     (cdr unread)))
3373
3374 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3375   "Restrict ARTICLES to numbers already fetched.
3376 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
3377 that have already been fetched.
3378 If CACHED-HEADER is nil, articles are only excluded if the article itself
3379 has been fetched."
3380
3381   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3382   ;; 'car gnus-agent-article-alist))
3383
3384   ;; Functionally, I don't need to construct a temp list using mapcar.
3385
3386   (if (and (or gnus-agent-cache (not gnus-plugged))
3387            (gnus-agent-load-alist group))
3388     (let* ((ref gnus-agent-article-alist)
3389            (arts articles)
3390            (uncached (list nil))
3391            (tail-uncached uncached))
3392       (while (and ref arts)
3393         (let ((v1 (car arts))
3394               (v2 (caar ref)))
3395           (cond ((< v1 v2) ; v1 does not appear in the reference list
3396                  (gnus-agent-append-to-list tail-uncached v1)
3397                  (setq arts (cdr arts)))
3398                 ((= v1 v2)
3399                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3400                    (gnus-agent-append-to-list tail-uncached v1))
3401                  (setq arts (cdr arts))
3402                  (setq ref (cdr ref)))
3403                 (t ; reference article (v2) preceeds the list being filtered
3404                  (setq ref (cdr ref))))))
3405       (while arts
3406         (gnus-agent-append-to-list tail-uncached (pop arts)))
3407       (cdr uncached))
3408     ;; if gnus-agent-load-alist fails, no articles are cached.
3409     articles))
3410
3411 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3412   (save-excursion
3413     (gnus-agent-create-buffer)
3414     (let ((gnus-decode-encoded-word-function 'identity)
3415           (file (gnus-agent-article-name ".overview" group))
3416           cached-articles uncached-articles)
3417       (gnus-make-directory (nnheader-translate-file-chars
3418                             (file-name-directory file) t))
3419
3420       ;; Populate temp buffer with known headers
3421       (when (file-exists-p file)
3422         (with-current-buffer gnus-agent-overview-buffer
3423           (erase-buffer)
3424           (let ((nnheader-file-coding-system
3425                  gnus-agent-file-coding-system))
3426             (nnheader-insert-nov-file file (car articles)))))
3427
3428       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3429                                                                 t))
3430           (progn
3431             ;; Populate nntp-server-buffer with uncached headers
3432             (set-buffer nntp-server-buffer)
3433             (erase-buffer)
3434             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3435                                    (gnus-retrieve-headers
3436                                     uncached-articles group fetch-old))))
3437                    (nnvirtual-convert-headers))
3438                   ((eq 'nntp (car gnus-current-select-method))
3439                    ;; The author of gnus-get-newsgroup-headers-xover
3440                    ;; reports that the XOVER command is commonly
3441                    ;; unreliable. The problem is that recently
3442                    ;; posted articles may not be entered into the
3443                    ;; NOV database in time to respond to my XOVER
3444                    ;; query.
3445                    ;;
3446                    ;; I'm going to use his assumption that the NOV
3447                    ;; database is updated in order of ascending
3448                    ;; article ID.  Therefore, a response containing
3449                    ;; article ID N implies that all articles from 1
3450                    ;; to N-1 are up-to-date.  Therefore, missing
3451                    ;; articles in that range have expired.
3452
3453                    (set-buffer nntp-server-buffer)
3454                    (let* ((fetched-articles (list nil))
3455                           (tail-fetched-articles fetched-articles)
3456                           (min (cond ((numberp fetch-old)
3457                                       (max 1 (- (car articles) fetch-old)))
3458                                      (fetch-old
3459                                       1)
3460                                      (t
3461                                       (car articles))))
3462                           (max (car (last articles))))
3463
3464                      ;; Get the list of articles that were fetched
3465                      (goto-char (point-min))
3466                      (let ((pm (point-max)))
3467                        (while (< (point) pm)
3468                          (when (looking-at "[0-9]+\t")
3469                            (gnus-agent-append-to-list
3470                             tail-fetched-articles
3471                             (read (current-buffer))))
3472                          (forward-line 1)))
3473
3474                      ;; Clip this list to the headers that will
3475                      ;; actually be returned
3476                      (setq fetched-articles (gnus-list-range-intersection
3477                                              (cdr fetched-articles)
3478                                              (cons min max)))
3479
3480                      ;; Clip the uncached articles list to exclude
3481                      ;; IDs after the last FETCHED header.  The
3482                      ;; excluded IDs may be fetchable using HEAD.
3483                      (if (car tail-fetched-articles)
3484                          (setq uncached-articles
3485                                (gnus-list-range-intersection
3486                                 uncached-articles
3487                                 (cons (car uncached-articles)
3488                                       (car tail-fetched-articles)))))
3489
3490                      ;; Create the list of articles that were
3491                      ;; "successfully" fetched.  Success, in this
3492                      ;; case, means that the ID should not be
3493                      ;; fetched again.  In the case of an expired
3494                      ;; article, the header will not be fetched.
3495                      (setq uncached-articles
3496                            (gnus-sorted-nunion fetched-articles
3497                                                uncached-articles))
3498                      )))
3499
3500             ;; Erase the temp buffer
3501             (set-buffer gnus-agent-overview-buffer)
3502             (erase-buffer)
3503
3504             ;; Copy the nntp-server-buffer to the temp buffer
3505             (set-buffer nntp-server-buffer)
3506             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3507
3508             ;; Merge the temp buffer with the known headers (found on
3509             ;; disk in FILE) into the nntp-server-buffer
3510             (when (and uncached-articles (file-exists-p file))
3511               (gnus-agent-braid-nov group uncached-articles file))
3512
3513             ;; Save the new set of known headers to FILE
3514             (set-buffer nntp-server-buffer)
3515             (gnus-agent-check-overview-buffer)
3516             (write-region-as-coding-system
3517              gnus-agent-file-coding-system
3518              (point-min) (point-max) file nil 'silent)
3519
3520             (gnus-agent-update-view-total-fetched-for group t)
3521
3522             ;; Update the group's article alist to include the newly
3523             ;; fetched articles.
3524             (gnus-agent-load-alist group)
3525             (gnus-agent-save-alist group uncached-articles nil)
3526             )
3527
3528         ;; Copy the temp buffer to the nntp-server-buffer
3529         (set-buffer nntp-server-buffer)
3530         (erase-buffer)
3531         (insert-buffer-substring gnus-agent-overview-buffer)))
3532
3533     (if (and fetch-old
3534              (not (numberp fetch-old)))
3535         t                               ; Don't remove anything.
3536       (nnheader-nov-delete-outside-range
3537        (if fetch-old (max 1 (- (car articles) fetch-old))
3538          (car articles))
3539        (car (last articles)))
3540       t)
3541
3542     'nov))
3543
3544 (defun gnus-agent-request-article (article group)
3545   "Retrieve ARTICLE in GROUP from the agent cache."
3546   (when (and gnus-agent
3547              (or gnus-agent-cache
3548                  (not gnus-plugged))
3549              (numberp article))
3550     (let* ((gnus-command-method (gnus-find-method-for-group group))
3551            (file (gnus-agent-article-name (number-to-string article) group))
3552            (buffer-read-only nil))
3553       (when (and (file-exists-p file)
3554                  (> (nth 7 (file-attributes file)) 0))
3555         (erase-buffer)
3556         (gnus-kill-all-overlays)
3557         (insert-file-contents-as-coding-system gnus-cache-coding-system file)
3558         t))))
3559
3560 (defun gnus-agent-regenerate-group (group &optional reread)
3561   "Regenerate GROUP.
3562 If REREAD is t, all articles in the .overview are marked as unread.
3563 If REREAD is a list, the specified articles will be marked as unread.
3564 In addition, their NOV entries in .overview will be refreshed using
3565 the articles' current headers.
3566 If REREAD is not nil, downloaded articles are marked as unread."
3567   (interactive
3568    (list (let ((def (or (gnus-group-group-name)
3569                         gnus-newsgroup-name)))
3570            (let ((select (read-string (if def
3571                                           (concat "Group Name ("
3572                                                   def "): ")
3573                                         "Group Name: "))))
3574              (if (and (equal "" select)
3575                       def)
3576                  def
3577                select)))
3578          (catch 'mark
3579            (while (let (c
3580                         (cursor-in-echo-area t)
3581                         (echo-keystrokes 0))
3582                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3583                     (setq c (read-char-exclusive))
3584
3585                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3586                            (throw 'mark nil))
3587                           ((or (eq c ?a) (eq c ?A))
3588                            (throw 'mark t))
3589                           ((or (eq c ?d) (eq c ?D))
3590                            (throw 'mark 'some)))
3591                     (gnus-message 3 "Ignoring unexpected input")
3592                     (sit-for 1)
3593                     t)))))
3594   (when group
3595     (gnus-message 5 "Regenerating in %s" group)
3596     (let* ((gnus-command-method (or gnus-command-method
3597                                     (gnus-find-method-for-group group)))
3598            (file (gnus-agent-article-name ".overview" group))
3599            (dir (file-name-directory file))
3600            point
3601            (downloaded (if (file-exists-p dir)
3602                            (sort (mapcar (lambda (name) (string-to-int name))
3603                                          (directory-files dir nil "^[0-9]+$" t))
3604                                  '>)
3605                          (progn (gnus-make-directory dir) nil)))
3606            dl nov-arts
3607            alist header
3608            regenerated)
3609
3610       (mm-with-unibyte-buffer
3611         (if (file-exists-p file)
3612             (let ((nnheader-file-coding-system
3613                    gnus-agent-file-coding-system))
3614               (nnheader-insert-file-contents file)))
3615         (set-buffer-modified-p nil)
3616
3617         ;; Load the article IDs found in the overview file.  As a
3618         ;; side-effect, validate the file contents.
3619         (let ((load t))
3620           (while load
3621             (setq load nil)
3622             (goto-char (point-min))
3623             (while (< (point) (point-max))
3624               (cond ((and (looking-at "[0-9]+\t")
3625                           (<= (- (match-end 0) (match-beginning 0)) 9))
3626                      (push (read (current-buffer)) nov-arts)
3627                      (forward-line 1)
3628                      (let ((l1 (car nov-arts))
3629                            (l2 (cadr nov-arts)))
3630                        (cond ((and (listp reread) (memq l1 reread))
3631                               (gnus-delete-line)
3632                               (setq nov-arts (cdr nov-arts))
3633                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3634 entry of article %s deleted." l1))
3635                              ((not l2)
3636                               nil)
3637                              ((< l1 l2)
3638                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3639  entries are NOT in ascending order.")
3640                               ;; Don't sort now as I haven't verified
3641                               ;; that every line begins with a number
3642                               (setq load t))
3643                              ((= l1 l2)
3644                               (forward-line -1)
3645                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3646  entries contained duplicate of article %s.      Duplicate deleted." l1)
3647                               (gnus-delete-line)
3648                               (setq nov-arts (cdr nov-arts))))))
3649                     (t
3650                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3651  entries contained line that did not begin with an article number.  Deleted\
3652  line.")
3653                      (gnus-delete-line))))
3654             (when load
3655               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3656  entries into ascending order.")
3657               (sort-numeric-fields 1 (point-min) (point-max))
3658               (setq nov-arts nil))))
3659         (gnus-agent-check-overview-buffer)
3660
3661         ;; Construct a new article alist whose nodes match every header
3662         ;; in the .overview file.  As a side-effect, missing headers are
3663         ;; reconstructed from the downloaded article file.
3664         (while (or downloaded nov-arts)
3665           (cond ((and downloaded
3666                       (or (not nov-arts)
3667                           (> (car downloaded) (car nov-arts))))
3668                  ;; This entry is missing from the overview file
3669                  (gnus-message 3 "Regenerating NOV %s %d..." group
3670                                (car downloaded))
3671                  (let ((file (concat dir (number-to-string (car downloaded)))))
3672                    (mm-with-unibyte-buffer
3673                      (nnheader-insert-file-contents file)
3674                      (nnheader-remove-body)
3675                      (setq header (nnheader-parse-naked-head)))
3676                    (mail-header-set-number header (car downloaded))
3677                    (if nov-arts
3678                        (let ((key (concat "^" (int-to-string (car nov-arts))
3679                                           "\t")))
3680                          (or (re-search-backward key nil t)
3681                              (re-search-forward key))
3682                          (forward-line 1))
3683                      (goto-char (point-min)))
3684                    (nnheader-insert-nov header))
3685                  (setq nov-arts (cons (car downloaded) nov-arts)))
3686                 ((eq (car downloaded) (car nov-arts))
3687                  ;; This entry in the overview has been downloaded
3688                  (push (cons (car downloaded)
3689                              (time-to-days
3690                               (nth 5 (file-attributes
3691                                       (concat dir (number-to-string
3692                                                    (car downloaded))))))) alist)
3693                  (setq downloaded (cdr downloaded))
3694                  (setq nov-arts (cdr nov-arts)))
3695                 (t
3696                  ;; This entry in the overview has not been downloaded
3697                  (push (cons (car nov-arts) nil) alist)
3698                  (setq nov-arts (cdr nov-arts)))))
3699
3700         ;; When gnus-agent-consider-all-articles is set,
3701         ;; gnus-agent-regenerate-group should NOT remove article IDs from
3702         ;; the alist.  Those IDs serve as markers to indicate that an
3703         ;; attempt has been made to fetch that article's header.
3704
3705         ;; When gnus-agent-consider-all-articles is NOT set,
3706         ;; gnus-agent-regenerate-group can remove the article ID of every
3707         ;; article (with the exception of the last ID in the list - it's
3708         ;; special) that no longer appears in the overview.  In this
3709         ;; situtation, the last article ID in the list implies that it,
3710         ;; and every article ID preceeding it, have been fetched from the
3711         ;; server.
3712
3713         (if gnus-agent-consider-all-articles
3714             ;; Restore all article IDs that were not found in the overview file.
3715             (let* ((n (cons nil alist))
3716                    (merged n)
3717                    (o (gnus-agent-load-alist group)))
3718               (while o
3719                 (let ((nID (caadr n))
3720                       (oID (caar o)))
3721                   (cond ((not nID)
3722                          (setq n (setcdr n (list (list oID))))
3723                          (setq o (cdr o)))
3724                         ((< oID nID)
3725                          (setcdr n (cons (list oID) (cdr n)))
3726                          (setq o (cdr o)))
3727                         ((= oID nID)
3728                          (setq o (cdr o))
3729                          (setq n (cdr n)))
3730                         (t
3731                          (setq n (cdr n))))))
3732               (setq alist (cdr merged)))
3733           ;; Restore the last article ID if it is not already in the new alist
3734           (let ((n (last alist))
3735                 (o (last (gnus-agent-load-alist group))))
3736             (cond ((not o)
3737                    nil)
3738                   ((not n)
3739                    (push (cons (caar o) nil) alist))
3740                   ((< (caar n) (caar o))
3741                    (setcdr n (list (car o)))))))
3742
3743         (let ((inhibit-quit t))
3744           (if (setq regenerated (buffer-modified-p))
3745               (write-region-as-coding-system
3746                gnus-agent-file-coding-system
3747                (point-min) (point-max) file nil 'silent))
3748
3749           (setq regenerated (or regenerated
3750                                 (and reread gnus-agent-article-alist)
3751                                 (not (equal alist gnus-agent-article-alist))))
3752
3753           (setq gnus-agent-article-alist alist)
3754
3755           (when regenerated
3756             (gnus-agent-save-alist group)
3757        
3758             ;; I have to alter the group's active range NOW as
3759             ;; gnus-make-ascending-articles-unread will use it to
3760             ;; recalculate the number of unread articles in the group
3761
3762             (let ((group (gnus-group-real-name group))
3763                   (group-active (or (gnus-active group)
3764                                     (gnus-activate-group group))))
3765               (gnus-agent-possibly-alter-active group group-active)))))
3766
3767       (when (and reread gnus-agent-article-alist)
3768         (gnus-make-ascending-articles-unread
3769          group
3770          (if (listp reread)
3771              reread
3772            (delq nil (mapcar (function (lambda (c)
3773                                          (cond ((eq reread t)
3774                                                 (car c))
3775                                                ((cdr c)
3776                                                 (car c)))))
3777                              gnus-agent-article-alist))))
3778
3779         (when regenerated
3780             (gnus-agent-update-files-total-fetched-for group nil)))
3781
3782       (gnus-message 5 "")
3783       regenerated)))
3784
3785 ;;;###autoload
3786 (defun gnus-agent-regenerate (&optional clean reread)
3787   "Regenerate all agent covered files.
3788 If CLEAN, obsolete (ignore)."
3789   (interactive "P")
3790   (let (regenerated)
3791     (gnus-message 4 "Regenerating Gnus agent files...")
3792     (dolist (gnus-command-method (gnus-agent-covered-methods))
3793         (dolist (group (gnus-groups-from-server gnus-command-method))
3794           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3795                                 regenerated))))
3796     (gnus-message 4 "Regenerating Gnus agent files...done")
3797
3798     regenerated))
3799
3800 (defun gnus-agent-go-online (&optional force)
3801   "Switch servers into online status."
3802   (interactive (list t))
3803   (dolist (server gnus-opened-servers)
3804     (when (eq (nth 1 server) 'offline)
3805       (if (if (eq force 'ask)
3806               (gnus-y-or-n-p
3807                (format "Switch %s:%s into online status? "
3808                        (caar server) (cadar server)))
3809             force)
3810           (setcar (nthcdr 1 server) 'close)))))
3811
3812 (defun gnus-agent-toggle-group-plugged (group)
3813   "Toggle the status of the server of the current group."
3814   (interactive (list (gnus-group-group-name)))
3815   (let* ((method (gnus-find-method-for-group group))
3816          (status (cadr (assoc method gnus-opened-servers))))
3817     (if (eq status 'offline)
3818         (gnus-server-set-status method 'closed)
3819       (gnus-close-server method)
3820       (gnus-server-set-status method 'offline))
3821     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
3822              (if (eq status 'offline) 'offline 'online)
3823              (if (eq status 'offline) 'online 'offline))))
3824
3825 (defun gnus-agent-group-covered-p (group)
3826   (gnus-agent-method-p (gnus-group-method group)))
3827
3828 (defun gnus-agent-update-files-total-fetched-for 
3829   (group delta &optional method path)
3830   "Update, or set, the total disk space used by the articles that the
3831 agent has fetched."
3832   (when gnus-agent-total-fetched-hashtb
3833     (gnus-agent-with-refreshed-group
3834      group
3835      ;; if null, gnus-agent-group-pathname will calc method.
3836      (let* ((gnus-command-method method) 
3837             (path (or path (gnus-agent-group-pathname group)))
3838             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
3839                        (gnus-sethash path (make-list 3 0) 
3840                                      gnus-agent-total-fetched-hashtb))))
3841        (when (listp delta)
3842          (unless delta
3843            (setq delta (directory-files path nil "^-?[0-9]+$" t)))
3844
3845          (let ((sum 0.0)
3846                file)
3847            (while (setq file (pop delta))
3848              (incf sum (float (or (nth 7 (file-attributes 
3849                                           (nnheader-concat 
3850                                            path 
3851                                            (if (numberp file)
3852                                                (number-to-string file)
3853                                              file)))) 0))))
3854            (setq delta sum)))
3855
3856        (setq gnus-agent-need-update-total-fetched-for t)
3857        (incf (nth 2 entry) delta)))))
3858
3859 (defun gnus-agent-update-view-total-fetched-for 
3860   (group agent-over &optional method path)
3861   "Update, or set, the total disk space used by the .agentview and
3862 .overview files.  These files are calculated separately as they can be
3863 modified."
3864   (when gnus-agent-total-fetched-hashtb
3865     (gnus-agent-with-refreshed-group
3866      group
3867      ;; if null, gnus-agent-group-pathname will calc method.
3868      (let* ((gnus-command-method method) 
3869             (path (or path (gnus-agent-group-pathname group)))
3870             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
3871                        (gnus-sethash path (make-list 3 0) 
3872                                      gnus-agent-total-fetched-hashtb)))
3873             (size (or (nth 7 (file-attributes 
3874                               (nnheader-concat
3875                                path (if agent-over 
3876                                         ".overview"
3877                                       ".agentview"))))
3878                       0)))
3879        (setq gnus-agent-need-update-total-fetched-for t)
3880        (setf (nth (if agent-over 1 0) entry) size)))))
3881
3882 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
3883   "Get the total disk space used by the specified GROUP."
3884   (unless gnus-agent-total-fetched-hashtb
3885     (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
3886
3887   ;; if null, gnus-agent-group-pathname will calc method.
3888   (let* ((gnus-command-method method) 
3889          (path (gnus-agent-group-pathname group))
3890          (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
3891     (if entry
3892         (apply '+ entry)
3893       (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
3894         (+ 
3895          (gnus-agent-update-view-total-fetched-for  group nil method path)
3896          (gnus-agent-update-view-total-fetched-for  group t   method path)
3897          (gnus-agent-update-files-total-fetched-for group nil method path))))))
3898
3899 (provide 'gnus-agent)
3900
3901 ;;; gnus-agent.el ends here