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