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