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