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