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