* gnus-agent.el (gnus-agent-load-alist): Use new caching
[gnus] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'gnus)
28 (require 'gnus-cache)
29 (require 'nnvirtual)
30 (require 'gnus-sum)
31 (require 'gnus-score)
32 (require 'gnus-srvr)
33 (eval-when-compile
34   (if (featurep 'xemacs)
35       (require 'itimer)
36     (require 'timer))
37   (require 'cl))
38
39 (eval-and-compile
40   (autoload 'gnus-server-update-server "gnus-srvr"))
41
42 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
43   "Where the Gnus agent will store its files."
44   :group 'gnus-agent
45   :type 'directory)
46
47 (defcustom gnus-agent-plugged-hook nil
48   "Hook run when plugging into the network."
49   :group 'gnus-agent
50   :type 'hook)
51
52 (defcustom gnus-agent-unplugged-hook nil
53   "Hook run when unplugging from the network."
54   :group 'gnus-agent
55   :type 'hook)
56
57 (defcustom gnus-agent-fetched-hook nil
58   "Hook run after finishing fetching articles."
59   :group 'gnus-agent
60   :type 'hook)
61
62 (defcustom gnus-agent-handle-level gnus-level-subscribed
63   "Groups on levels higher than this variable will be ignored by the Agent."
64   :group 'gnus-agent
65   :type 'integer)
66
67 (defcustom gnus-agent-expire-days 7
68   "Read articles older than this will be expired.
69 This can also be a list of regexp/day pairs.  The regexps will
70 be matched against group names."
71   :group 'gnus-agent
72   :type 'integer)
73
74 (defcustom gnus-agent-expire-all nil
75   "If non-nil, also expire unread, ticked and dormant articles.
76 If nil, only read articles will be expired."
77   :group 'gnus-agent
78   :type 'boolean)
79
80 (defcustom gnus-agent-group-mode-hook nil
81   "Hook run in Agent group minor modes."
82   :group 'gnus-agent
83   :type 'hook)
84
85 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
86 (when (featurep 'xemacs)
87   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
88
89 (defcustom gnus-agent-summary-mode-hook nil
90   "Hook run in Agent summary minor modes."
91   :group 'gnus-agent
92   :type 'hook)
93
94 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
95 (when (featurep 'xemacs)
96   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
97
98 (defcustom gnus-agent-server-mode-hook nil
99   "Hook run in Agent summary minor modes."
100   :group 'gnus-agent
101   :type 'hook)
102
103 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
104 (when (featurep 'xemacs)
105   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
106
107 (defcustom gnus-agent-confirmation-function 'y-or-n-p
108   "Function to confirm when error happens."
109   :version "21.1"
110   :group 'gnus-agent
111   :type 'function)
112
113 (defcustom gnus-agent-synchronize-flags 'ask
114   "Indicate if flags are synchronized when you plug in.
115 If this is `ask' the hook will query the user."
116   :version "21.1"
117   :type '(choice (const :tag "Always" t)
118                  (const :tag "Never" nil)
119                  (const :tag "Ask" ask))
120   :group 'gnus-agent)
121
122 (defcustom gnus-agent-go-online 'ask
123   "Indicate if offline servers go online when you plug in.
124 If this is `ask' the hook will query the user."
125   :version "21.1"
126   :type '(choice (const :tag "Always" t)
127                  (const :tag "Never" nil)
128                  (const :tag "Ask" ask))
129   :group 'gnus-agent)
130
131 ;;; Internal variables
132
133 (defvar gnus-agent-history-buffers nil)
134 (defvar gnus-agent-buffer-alist nil)
135 (defvar gnus-agent-article-alist nil)
136 (defvar gnus-agent-group-alist nil)
137 (defvar gnus-category-alist nil)
138 (defvar gnus-agent-current-history nil)
139 (defvar gnus-agent-overview-buffer nil)
140 (defvar gnus-category-predicate-cache nil)
141 (defvar gnus-category-group-cache nil)
142 (defvar gnus-agent-spam-hashtb nil)
143 (defvar gnus-agent-file-name nil)
144 (defvar gnus-agent-send-mail-function nil)
145 (defvar gnus-agent-file-coding-system 'raw-text)
146 (defvar gnus-agent-file-loading-cache nil)
147
148 ;; Dynamic variables
149 (defvar gnus-headers)
150 (defvar gnus-score)
151
152 ;;;
153 ;;; Setup
154 ;;;
155
156 (defun gnus-open-agent ()
157   (setq gnus-agent t)
158   (gnus-agent-read-servers)
159   (gnus-category-read)
160   (gnus-agent-create-buffer)
161   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
162   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
163   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
164
165 (defun gnus-agent-create-buffer ()
166   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
167       t
168     (setq gnus-agent-overview-buffer
169           (gnus-get-buffer-create " *Gnus agent overview*"))
170     (with-current-buffer gnus-agent-overview-buffer
171       (mm-enable-multibyte))
172     nil))
173
174 (gnus-add-shutdown 'gnus-close-agent 'gnus)
175
176 (defun gnus-close-agent ()
177   (setq gnus-agent-covered-methods nil
178         gnus-category-predicate-cache nil
179         gnus-category-group-cache nil
180         gnus-agent-spam-hashtb nil)
181   (gnus-kill-buffer gnus-agent-overview-buffer))
182
183 ;;;
184 ;;; Utility functions
185 ;;;
186
187 (defun gnus-agent-read-file (file)
188   "Load FILE and do a `read' there."
189   (with-temp-buffer
190     (ignore-errors
191       (nnheader-insert-file-contents file)
192       (goto-char (point-min))
193       (read (current-buffer)))))
194
195 (defsubst gnus-agent-method ()
196   (concat (symbol-name (car gnus-command-method)) "/"
197           (if (equal (cadr gnus-command-method) "")
198               "unnamed"
199             (cadr gnus-command-method))))
200
201 (defsubst gnus-agent-directory ()
202   "Path of the Gnus agent directory."
203   (nnheader-concat gnus-agent-directory
204                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
205
206 (defun gnus-agent-lib-file (file)
207   "The full path of the Gnus agent library FILE."
208   (expand-file-name file
209                     (file-name-as-directory
210                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
211
212 ;;; Fetching setup functions.
213
214 (defun gnus-agent-start-fetch ()
215   "Initialize data structures for efficient fetching."
216   (gnus-agent-open-history)
217   (setq gnus-agent-current-history (gnus-agent-history-buffer))
218   (gnus-agent-create-buffer))
219
220 (defun gnus-agent-stop-fetch ()
221   "Save all data structures and clean up."
222   (gnus-agent-save-history)
223   (gnus-agent-close-history)
224   (setq gnus-agent-spam-hashtb nil)
225   (save-excursion
226     (set-buffer nntp-server-buffer)
227     (widen)))
228
229 (defmacro gnus-agent-with-fetch (&rest forms)
230   "Do FORMS safely."
231   `(unwind-protect
232        (let ((gnus-agent-fetching t))
233          (gnus-agent-start-fetch)
234          ,@forms)
235      (gnus-agent-stop-fetch)))
236
237 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
238 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
239
240 ;;;
241 ;;; Mode infestation
242 ;;;
243
244 (defvar gnus-agent-mode-hook nil
245   "Hook run when installing agent mode.")
246
247 (defvar gnus-agent-mode nil)
248 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
249
250 (defun gnus-agent-mode ()
251   "Minor mode for providing a agent support in Gnus buffers."
252   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
253                                       (symbol-name major-mode))
254                         (match-string 1 (symbol-name major-mode))))
255          (mode (intern (format "gnus-agent-%s-mode" buffer))))
256     (set (make-local-variable 'gnus-agent-mode) t)
257     (set mode nil)
258     (set (make-local-variable mode) t)
259     ;; Set up the menu.
260     (when (gnus-visual-p 'agent-menu 'menu)
261       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
262     (unless (assq 'gnus-agent-mode minor-mode-alist)
263       (push gnus-agent-mode-status minor-mode-alist))
264     (unless (assq mode minor-mode-map-alist)
265       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
266                                                      buffer))))
267             minor-mode-map-alist))
268     (when (eq major-mode 'gnus-group-mode)
269       (gnus-agent-toggle-plugged gnus-plugged))
270     (gnus-run-hooks 'gnus-agent-mode-hook
271                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
272
273 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
274 (gnus-define-keys gnus-agent-group-mode-map
275   "Ju" gnus-agent-fetch-groups
276   "Jc" gnus-enter-category-buffer
277   "Jj" gnus-agent-toggle-plugged
278   "Js" gnus-agent-fetch-session
279   "JY" gnus-agent-synchronize-flags
280   "JS" gnus-group-send-queue
281   "Ja" gnus-agent-add-group
282   "Jr" gnus-agent-remove-group
283   "Jo" gnus-agent-toggle-group-plugged)
284
285 (defun gnus-agent-group-make-menu-bar ()
286   (unless (boundp 'gnus-agent-group-menu)
287     (easy-menu-define
288      gnus-agent-group-menu gnus-agent-group-mode-map ""
289      '("Agent"
290        ["Toggle plugged" gnus-agent-toggle-plugged t]
291        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
292        ["List categories" gnus-enter-category-buffer t]
293        ["Send queue" gnus-group-send-queue gnus-plugged]
294        ("Fetch"
295         ["All" gnus-agent-fetch-session gnus-plugged]
296         ["Group" gnus-agent-fetch-group gnus-plugged])))))
297
298 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
299 (gnus-define-keys gnus-agent-summary-mode-map
300   "Jj" gnus-agent-toggle-plugged
301   "Ju" gnus-agent-summary-fetch-group
302   "J#" gnus-agent-mark-article
303   "J\M-#" gnus-agent-unmark-article
304   "@" gnus-agent-toggle-mark
305   "Jc" gnus-agent-catchup)
306
307 (defun gnus-agent-summary-make-menu-bar ()
308   (unless (boundp 'gnus-agent-summary-menu)
309     (easy-menu-define
310      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
311      '("Agent"
312        ["Toggle plugged" gnus-agent-toggle-plugged t]
313        ["Mark as downloadable" gnus-agent-mark-article t]
314        ["Unmark as downloadable" gnus-agent-unmark-article t]
315        ["Toggle mark" gnus-agent-toggle-mark t]
316        ["Fetch downloadable" gnus-aget-summary-fetch-group t]
317        ["Catchup undownloaded" gnus-agent-catchup t]))))
318
319 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
320 (gnus-define-keys gnus-agent-server-mode-map
321   "Jj" gnus-agent-toggle-plugged
322   "Ja" gnus-agent-add-server
323   "Jr" gnus-agent-remove-server)
324
325 (defun gnus-agent-server-make-menu-bar ()
326   (unless (boundp 'gnus-agent-server-menu)
327     (easy-menu-define
328      gnus-agent-server-menu gnus-agent-server-mode-map ""
329      '("Agent"
330        ["Toggle plugged" gnus-agent-toggle-plugged t]
331        ["Add" gnus-agent-add-server t]
332        ["Remove" gnus-agent-remove-server t]))))
333
334 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
335   (if (and (fboundp 'propertize)
336            (fboundp 'make-mode-line-mouse-map))
337       (propertize string 'local-map
338                   (make-mode-line-mouse-map mouse-button mouse-func))
339     string))
340
341 (defun gnus-agent-toggle-plugged (plugged)
342   "Toggle whether Gnus is unplugged or not."
343   (interactive (list (not gnus-plugged)))
344   (if plugged
345       (progn
346         (setq gnus-plugged plugged)
347         (gnus-run-hooks 'gnus-agent-plugged-hook)
348         (setcar (cdr gnus-agent-mode-status) 
349                 (gnus-agent-make-mode-line-string " Plugged"
350                                                   'mouse-2
351                                                   'gnus-agent-toggle-plugged))
352         (gnus-agent-go-online gnus-agent-go-online)
353         (gnus-agent-possibly-synchronize-flags))
354     (gnus-agent-close-connections)
355     (setq gnus-plugged plugged)
356     (gnus-run-hooks 'gnus-agent-unplugged-hook)
357     (setcar (cdr gnus-agent-mode-status) 
358             (gnus-agent-make-mode-line-string " Unplugged"
359                                               'mouse-2
360                                               'gnus-agent-toggle-plugged)))
361   (set-buffer-modified-p t))
362
363 (defun gnus-agent-close-connections ()
364   "Close all methods covered by the Gnus agent."
365   (let ((methods gnus-agent-covered-methods))
366     (while methods
367       (gnus-close-server (pop methods)))))
368
369 ;;;###autoload
370 (defun gnus-unplugged ()
371   "Start Gnus unplugged."
372   (interactive)
373   (setq gnus-plugged nil)
374   (gnus))
375
376 ;;;###autoload
377 (defun gnus-plugged ()
378   "Start Gnus plugged."
379   (interactive)
380   (setq gnus-plugged t)
381   (gnus))
382
383 ;;;###autoload
384 (defun gnus-agentize ()
385   "Allow Gnus to be an offline newsreader.
386 The normal usage of this command is to put the following as the
387 last form in your `.gnus.el' file:
388
389 \(gnus-agentize)
390
391 This will modify the `gnus-setup-news-hook', and
392 `message-send-mail-real-function' variables, and install the Gnus agent
393 minor mode in all Gnus buffers."
394   (interactive)
395   (gnus-open-agent)
396   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
397   (unless gnus-agent-send-mail-function
398     (setq gnus-agent-send-mail-function (or
399                                          message-send-mail-real-function
400                                          message-send-mail-function)
401           message-send-mail-real-function 'gnus-agent-send-mail))
402   (unless gnus-agent-covered-methods
403     (setq gnus-agent-covered-methods (list gnus-select-method))))
404
405 (defun gnus-agent-queue-setup ()
406   "Make sure the queue group exists."
407   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
408     (gnus-request-create-group "queue" '(nndraft ""))
409     (let ((gnus-level-default-subscribed 1))
410       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
411     (gnus-group-set-parameter
412      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
413
414 (defun gnus-agent-send-mail ()
415   (if gnus-plugged
416       (funcall gnus-agent-send-mail-function)
417     (goto-char (point-min))
418     (re-search-forward
419      (concat "^" (regexp-quote mail-header-separator) "\n"))
420     (replace-match "\n")
421     (gnus-agent-insert-meta-information 'mail)
422     (gnus-request-accept-article "nndraft:queue" nil t t)))
423
424 (defun gnus-agent-insert-meta-information (type &optional method)
425   "Insert meta-information into the message that says how it's to be posted.
426 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
427 be a select method."
428   (save-excursion
429     (message-remove-header gnus-agent-meta-information-header)
430     (goto-char (point-min))
431     (insert gnus-agent-meta-information-header ": "
432             (symbol-name type) " " (format "%S" method)
433             "\n")
434     (forward-char -1)
435     (while (search-backward "\n" nil t)
436       (replace-match "\\n" t t))))
437
438 (defun gnus-agent-restore-gcc ()
439   "Restore GCC field from saved header."
440   (save-excursion
441     (goto-char (point-min))
442     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
443       (replace-match "Gcc:" 'fixedcase))))
444
445 (defun gnus-agent-any-covered-gcc ()
446   (save-restriction
447     (message-narrow-to-headers)
448     (let* ((gcc (mail-fetch-field "gcc" nil t))
449            (methods (and gcc
450                          (mapcar 'gnus-inews-group-method
451                                  (message-unquote-tokens
452                                   (message-tokenize-header
453                                    gcc " ,")))))
454            covered)
455       (while (and (not covered) methods)
456         (setq covered (gnus-agent-method-p (car methods))
457               methods (cdr methods)))
458       covered)))
459
460 (defun gnus-agent-possibly-save-gcc ()
461   "Save GCC if Gnus is unplugged."
462   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
463     (save-excursion
464       (goto-char (point-min))
465       (let ((case-fold-search t))
466         (while (re-search-forward "^gcc:" nil t)
467           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
468
469 (defun gnus-agent-possibly-do-gcc ()
470   "Do GCC if Gnus is plugged."
471   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
472     (gnus-inews-do-gcc)))
473
474 ;;;
475 ;;; Group mode commands
476 ;;;
477
478 (defun gnus-agent-fetch-groups (n)
479   "Put all new articles in the current groups into the Agent."
480   (interactive "P")
481   (unless gnus-plugged
482     (error "Groups can't be fetched when Gnus is unplugged"))
483   (gnus-group-iterate n 'gnus-agent-fetch-group))
484
485 (defun gnus-agent-fetch-group (group)
486   "Put all new articles in GROUP into the Agent."
487   (interactive (list (gnus-group-group-name)))
488   (let ((state gnus-plugged))
489     (unwind-protect
490         (progn
491           (unless group
492             (error "No group on the current line"))
493           (unless state
494             (gnus-agent-toggle-plugged gnus-plugged))
495           (let ((gnus-command-method (gnus-find-method-for-group group)))
496             (gnus-agent-with-fetch
497               (gnus-agent-fetch-group-1 group gnus-command-method)
498               (gnus-message 5 "Fetching %s...done" group))))
499       (when (and (not state)
500                  gnus-plugged)
501         (gnus-agent-toggle-plugged gnus-plugged)))))
502
503 (defun gnus-agent-add-group (category arg)
504   "Add the current group to an agent category."
505   (interactive
506    (list
507     (intern
508      (completing-read
509       "Add to category: "
510       (mapcar (lambda (cat) (list (symbol-name (car cat))))
511               gnus-category-alist)
512       nil t))
513     current-prefix-arg))
514   (let ((cat (assq category gnus-category-alist))
515         c groups)
516     (gnus-group-iterate arg
517       (lambda (group)
518         (when (cadddr (setq c (gnus-group-category group)))
519           (setf (cadddr c) (delete group (cadddr c))))
520         (push group groups)))
521     (setf (cadddr cat) (nconc (cadddr cat) groups))
522     (gnus-category-write)))
523
524 (defun gnus-agent-remove-group (arg)
525   "Remove the current group from its agent category, if any."
526   (interactive "P")
527   (let (c)
528     (gnus-group-iterate arg
529       (lambda (group)
530         (when (cadddr (setq c (gnus-group-category group)))
531           (setf (cadddr c) (delete group (cadddr c))))))
532     (gnus-category-write)))
533
534 (defun gnus-agent-synchronize-flags ()
535   "Synchronize unplugged flags with servers."
536   (interactive)
537   (save-excursion
538     (dolist (gnus-command-method gnus-agent-covered-methods)
539       (when (file-exists-p (gnus-agent-lib-file "flags"))
540         (gnus-agent-synchronize-flags-server gnus-command-method)))))
541
542 (defun gnus-agent-possibly-synchronize-flags ()
543   "Synchronize flags according to `gnus-agent-synchronize-flags'."
544   (interactive)
545   (save-excursion
546     (dolist (gnus-command-method gnus-agent-covered-methods)
547       (when (file-exists-p (gnus-agent-lib-file "flags"))
548         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
549
550 (defun gnus-agent-synchronize-flags-server (method)
551   "Synchronize flags set when unplugged for server."
552   (let ((gnus-command-method method))
553     (when (file-exists-p (gnus-agent-lib-file "flags"))
554       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
555       (erase-buffer)
556       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
557       (if (null (gnus-check-server gnus-command-method))
558           (message "Couldn't open server %s" (nth 1 gnus-command-method))
559         (while (not (eobp))
560           (if (null (eval (read (current-buffer))))
561               (progn (forward-line)
562                      (kill-line -1))
563             (write-file (gnus-agent-lib-file "flags"))
564             (error "Couldn't set flags from file %s"
565                    (gnus-agent-lib-file "flags"))))
566         (delete-file (gnus-agent-lib-file "flags")))
567       (kill-buffer nil))))
568
569 (defun gnus-agent-possibly-synchronize-flags-server (method)
570   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
571   (when (or (and gnus-agent-synchronize-flags
572                  (not (eq gnus-agent-synchronize-flags 'ask)))
573             (and (eq gnus-agent-synchronize-flags 'ask)
574                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
575                                         (cadr method)))))
576     (gnus-agent-synchronize-flags-server method)))
577
578 ;;;
579 ;;; Server mode commands
580 ;;;
581
582 (defun gnus-agent-add-server (server)
583   "Enroll SERVER in the agent program."
584   (interactive (list (gnus-server-server-name)))
585   (unless server
586     (error "No server on the current line"))
587   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
588     (when (gnus-agent-method-p method)
589       (error "Server already in the agent program"))
590     (push method gnus-agent-covered-methods)
591     (gnus-server-update-server server)
592     (gnus-agent-write-servers)
593     (message "Entered %s into the Agent" server)))
594
595 (defun gnus-agent-remove-server (server)
596   "Remove SERVER from the agent program."
597   (interactive (list (gnus-server-server-name)))
598   (unless server
599     (error "No server on the current line"))
600   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
601     (unless (gnus-agent-method-p method)
602       (error "Server not in the agent program"))
603     (setq gnus-agent-covered-methods
604           (delete method gnus-agent-covered-methods))
605     (gnus-server-update-server server)
606     (gnus-agent-write-servers)
607     (message "Removed %s from the agent" server)))
608
609 (defun gnus-agent-read-servers ()
610   "Read the alist of covered servers."
611   (setq gnus-agent-covered-methods
612         (gnus-agent-read-file
613          (nnheader-concat gnus-agent-directory "lib/servers"))))
614
615 (defun gnus-agent-write-servers ()
616   "Write the alist of covered servers."
617   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
618   (let ((coding-system-for-write nnheader-file-coding-system)
619         (file-name-coding-system nnmail-pathname-coding-system))
620     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
621       (prin1 gnus-agent-covered-methods (current-buffer)))))
622
623 ;;;
624 ;;; Summary commands
625 ;;;
626
627 (defun gnus-agent-mark-article (n &optional unmark)
628   "Mark the next N articles as downloadable.
629 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
630 the mark instead.  The difference between N and the actual number of
631 articles marked is returned."
632   (interactive "p")
633   (let ((backward (< n 0))
634         (n (abs n)))
635     (while (and
636             (> n 0)
637             (progn
638               (gnus-summary-set-agent-mark
639                (gnus-summary-article-number) unmark)
640               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
641       (setq n (1- n)))
642     (when (/= 0 n)
643       (gnus-message 7 "No more articles"))
644     (gnus-summary-recenter)
645     (gnus-summary-position-point)
646     n))
647
648 (defun gnus-agent-unmark-article (n)
649   "Remove the downloadable mark from the next N articles.
650 If N is negative, unmark backward instead.  The difference between N and
651 the actual number of articles unmarked is returned."
652   (interactive "p")
653   (gnus-agent-mark-article n t))
654
655 (defun gnus-agent-toggle-mark (n)
656   "Toggle the downloadable mark from the next N articles.
657 If N is negative, toggle backward instead.  The difference between N and
658 the actual number of articles toggled is returned."
659   (interactive "p")
660   (gnus-agent-mark-article n 'toggle))
661
662 (defun gnus-summary-set-agent-mark (article &optional unmark)
663   "Mark ARTICLE as downloadable."
664   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
665                     (memq article gnus-newsgroup-downloadable)
666                   unmark)))
667     (if unmark
668         (progn
669           (setq gnus-newsgroup-downloadable
670                 (delq article gnus-newsgroup-downloadable))
671           (push article gnus-newsgroup-undownloaded))
672       (setq gnus-newsgroup-undownloaded
673             (delq article gnus-newsgroup-undownloaded))
674       (push article gnus-newsgroup-downloadable))
675     (gnus-summary-update-mark
676      (if unmark gnus-undownloaded-mark gnus-downloadable-mark)
677      'unread)))
678
679 (defun gnus-agent-get-undownloaded-list ()
680   "Mark all unfetched articles as read."
681   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
682     (when (and (not (gnus-online gnus-command-method))
683                (gnus-agent-method-p gnus-command-method))
684       (gnus-agent-load-alist gnus-newsgroup-name)
685       ;; First mark all undownloaded articles as undownloaded.
686       (let ((articles (mapcar (lambda (header) (mail-header-number header))
687                               gnus-newsgroup-headers))
688             (agent-articles gnus-agent-article-alist)
689             candidates article)
690         (while (setq article (pop articles))
691           (while (and agent-articles
692                       (< (caar agent-articles) article))
693             (setq agent-articles (cdr agent-articles)))
694           (when (or (not (cdar agent-articles))
695                     (not (= (caar agent-articles) article)))
696             (push article candidates)))
697         (dolist (article candidates)
698           (unless (or (memq article gnus-newsgroup-downloadable)
699                       (memq article gnus-newsgroup-cached))
700             (push article gnus-newsgroup-undownloaded))))
701       ;; Then mark downloaded downloadable as not-downloadable,
702       ;; if you get my drift.
703       (dolist (article gnus-newsgroup-downloadable)
704         (when (cdr (assq article gnus-agent-article-alist))
705           (setq gnus-newsgroup-downloadable
706                 (delq article gnus-newsgroup-downloadable)))))))
707
708 (defun gnus-agent-catchup ()
709   "Mark all undownloaded articles as read."
710   (interactive)
711   (save-excursion
712     (while gnus-newsgroup-undownloaded
713       (gnus-summary-mark-article
714        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
715   (gnus-summary-position-point))
716
717 (defun gnus-agent-summary-fetch-group ()
718   "Fetch the downloadable articles in the group."
719   (interactive)
720   (let ((articles gnus-newsgroup-downloadable)
721         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
722         (state gnus-plugged))
723     (unwind-protect
724         (progn
725           (unless state
726             (gnus-agent-toggle-plugged t))
727           (unless articles
728             (error "No articles to download"))
729           (gnus-agent-with-fetch
730             (gnus-agent-fetch-articles gnus-newsgroup-name articles))
731           (save-excursion
732             (dolist (article articles)
733               (setq gnus-newsgroup-downloadable
734                     (delq article gnus-newsgroup-downloadable))
735               (gnus-summary-mark-article article gnus-unread-mark))))
736       (when (and (not state)
737                  gnus-plugged)
738         (gnus-agent-toggle-plugged nil)))))
739
740 ;;;
741 ;;; Internal functions
742 ;;;
743
744 (defun gnus-agent-save-active (method)
745   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
746
747 (defun gnus-agent-save-active-1 (method function)
748   (when (gnus-agent-method-p method)
749     (let* ((gnus-command-method method)
750            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
751            (file (gnus-agent-lib-file "active")))
752       (funcall function nil new)
753       (gnus-agent-write-active file new)
754       (erase-buffer)
755       (nnheader-insert-file-contents file))))
756
757 (defun gnus-agent-write-active (file new)
758   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
759         (file (gnus-agent-lib-file "active"))
760         elem osym)
761     (when (file-exists-p file)
762       (with-temp-buffer
763         (nnheader-insert-file-contents file)
764         (gnus-active-to-gnus-format nil orig))
765       (mapatoms
766        (lambda (sym)
767          (when (and sym (boundp sym))
768            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
769                     (setq elem (symbol-value osym)))
770                (progn
771                  (if (and (integerp (car (symbol-value sym)))
772                           (> (car elem) (car (symbol-value sym))))
773                      (setcar elem (car (symbol-value sym))))
774                  (if (integerp (cdr (symbol-value sym)))
775                      (setcdr elem (cdr (symbol-value sym)))))
776              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
777        new))
778     (gnus-make-directory (file-name-directory file))
779     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
780       ;; The hashtable contains real names of groups,  no more prefix
781       ;; removing, so set `full' to `t'.
782       (gnus-write-active-file file orig t))))
783
784 (defun gnus-agent-save-groups (method)
785   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
786
787 (defun gnus-agent-save-group-info (method group active)
788   (when (gnus-agent-method-p method)
789     (let* ((gnus-command-method method)
790            (coding-system-for-write nnheader-file-coding-system)
791            (file-name-coding-system nnmail-pathname-coding-system)
792            (file (gnus-agent-lib-file "active"))
793            oactive-min)
794       (gnus-make-directory (file-name-directory file))
795       (with-temp-file file
796         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
797         (mm-disable-multibyte)
798         (when (file-exists-p file)
799           (nnheader-insert-file-contents file))
800         (goto-char (point-min))
801         (when (re-search-forward
802                (concat "^" (regexp-quote group) " ") nil t)
803           (save-excursion
804             (read (current-buffer))                      ;; max
805             (setq oactive-min (read (current-buffer))))  ;; min
806           (gnus-delete-line))
807         (insert (format "%S %d %d y\n" (intern group)
808                         (cdr active)
809                         (or oactive-min (car active))))
810         (goto-char (point-max))
811         (while (search-backward "\\." nil t)
812           (delete-char 1))))))
813
814 (defun gnus-agent-group-path (group)
815   "Translate GROUP into a path."
816   (if nnmail-use-long-file-names
817       (gnus-group-real-name group)
818     (nnheader-translate-file-chars
819      (nnheader-replace-chars-in-string
820       (nnheader-replace-duplicate-chars-in-string
821        (nnheader-replace-chars-in-string
822         (gnus-group-real-name group)
823         ?/ ?_)
824        ?. ?_)
825       ?. ?/))))
826
827 \f
828
829 (defun gnus-agent-get-function (method)
830   (if (gnus-online method)
831       (car method)
832     (require 'nnagent)
833     'nnagent))
834
835 ;;; History functions
836
837 (defun gnus-agent-history-buffer ()
838   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
839
840 (defun gnus-agent-open-history ()
841   (save-excursion
842     (push (cons (gnus-agent-method)
843                 (set-buffer (gnus-get-buffer-create
844                              (format " *Gnus agent %s history*"
845                                      (gnus-agent-method)))))
846           gnus-agent-history-buffers)
847     (mm-disable-multibyte) ;; everything is binary
848     (erase-buffer)
849     (insert "\n")
850     (let ((file (gnus-agent-lib-file "history")))
851       (when (file-exists-p file)
852         (nnheader-insert-file-contents file))
853       (set (make-local-variable 'gnus-agent-file-name) file))))
854
855 (defun gnus-agent-save-history ()
856   (save-excursion
857     (set-buffer gnus-agent-current-history)
858     (gnus-make-directory (file-name-directory gnus-agent-file-name))
859     (let ((coding-system-for-write gnus-agent-file-coding-system))
860       (write-region (1+ (point-min)) (point-max)
861                     gnus-agent-file-name nil 'silent))))
862
863 (defun gnus-agent-close-history ()
864   (when (gnus-buffer-live-p gnus-agent-current-history)
865     (kill-buffer gnus-agent-current-history)
866     (setq gnus-agent-history-buffers
867           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
868                 gnus-agent-history-buffers))))
869
870 (defun gnus-agent-enter-history (id group-arts date)
871   (save-excursion
872     (set-buffer gnus-agent-current-history)
873     (goto-char (point-max))
874     (let ((p (point)))
875       (insert id "\t" (number-to-string date) "\t")
876       (while group-arts
877         (insert (format "%S" (intern (caar group-arts)))
878                 " " (number-to-string (cdr (pop group-arts)))
879                 " "))
880       (insert "\n")
881       (while (search-backward "\\." p t)
882         (delete-char 1)))))
883
884 (defun gnus-agent-article-in-history-p (id)
885   (save-excursion
886     (set-buffer (gnus-agent-history-buffer))
887     (goto-char (point-min))
888     (search-forward (concat "\n" id "\t") nil t)))
889
890 (defun gnus-agent-history-path (id)
891   (save-excursion
892     (set-buffer (gnus-agent-history-buffer))
893     (goto-char (point-min))
894     (when (search-forward (concat "\n" id "\t") nil t)
895       (let ((method (gnus-agent-method)))
896         (let (paths group)
897           (while (not (numberp (setq group (read (current-buffer)))))
898             (push (concat method "/" group) paths))
899           (nreverse paths))))))
900
901 ;;;
902 ;;; Fetching
903 ;;;
904
905 (defun gnus-agent-fetch-articles (group articles)
906   "Fetch ARTICLES from GROUP and put them into the Agent."
907   (when articles
908     ;; Prune off articles that we have already fetched.
909     (while (and articles
910                 (cdr (assq (car articles) gnus-agent-article-alist)))
911       (pop articles))
912     (let ((arts articles))
913       (while (cdr arts)
914         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
915             (setcdr arts (cddr arts))
916           (setq arts (cdr arts)))))
917     (when articles
918       (let ((dir (concat
919                   (gnus-agent-directory)
920                   (gnus-agent-group-path group) "/"))
921             (date (time-to-days (current-time)))
922             (case-fold-search t)
923             pos crosses id elem)
924         (gnus-make-directory dir)
925         (gnus-message 7 "Fetching articles for %s..." group)
926         ;; Fetch the articles from the backend.
927         (if (gnus-check-backend-function 'retrieve-articles group)
928             (setq pos (gnus-retrieve-articles articles group))
929           (with-temp-buffer
930             (let (article)
931               (while (setq article (pop articles))
932                 (when (or
933                        (gnus-backlog-request-article group article
934                                                      nntp-server-buffer)
935                        (gnus-request-article article group))
936                   (goto-char (point-max))
937                   (push (cons article (point)) pos)
938                   (insert-buffer-substring nntp-server-buffer)))
939               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
940               (setq pos (nreverse pos)))))
941         ;; Then save these articles into the Agent.
942         (save-excursion
943           (set-buffer nntp-server-buffer)
944           (while pos
945             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
946             (goto-char (point-min))
947             (when (search-forward "\n\n" nil t)
948               (when (search-backward "\nXrefs: " nil t)
949                 ;; Handle crossposting.
950                 (skip-chars-forward "^ ")
951                 (skip-chars-forward " ")
952                 (setq crosses nil)
953                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
954                   (push (cons (buffer-substring (match-beginning 1)
955                                                 (match-end 1))
956                               (buffer-substring (match-beginning 2)
957                                                 (match-end 2)))
958                         crosses)
959                   (goto-char (match-end 0)))
960                 (gnus-agent-crosspost crosses (caar pos))))
961             (goto-char (point-min))
962             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
963                 (setq id "No-Message-ID-in-article")
964               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
965             (let ((coding-system-for-write
966                    gnus-agent-file-coding-system))
967               (write-region (point-min) (point-max)
968                             (concat dir (number-to-string (caar pos)))
969                             nil 'silent))
970             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
971               (setcdr elem t))
972             (gnus-agent-enter-history
973              id (or crosses (list (cons group (caar pos)))) date)
974             (widen)
975             (pop pos)))
976         (gnus-agent-save-alist group)))))
977
978 (defun gnus-agent-crosspost (crosses article)
979   (let (gnus-agent-article-alist group alist beg end)
980     (save-excursion
981       (set-buffer gnus-agent-overview-buffer)
982       (when (nnheader-find-nov-line article)
983         (forward-word 1)
984         (setq beg (point))
985         (setq end (progn (forward-line 1) (point)))))
986     (while crosses
987       (setq group (caar crosses))
988       (unless (setq alist (assoc group gnus-agent-group-alist))
989         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
990               gnus-agent-group-alist))
991       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
992       (save-excursion
993         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
994                                                     group)))
995         (when (= (point-max) (point-min))
996           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
997           (ignore-errors
998             (nnheader-insert-file-contents
999              (gnus-agent-article-name ".overview" group))))
1000         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1001         (insert (string-to-number (cdar crosses)))
1002         (insert-buffer-substring gnus-agent-overview-buffer beg end))
1003       (pop crosses))))
1004
1005 (defun gnus-agent-flush-cache ()
1006   (save-excursion
1007     (while gnus-agent-buffer-alist
1008       (set-buffer (cdar gnus-agent-buffer-alist))
1009       (let ((coding-system-for-write
1010              gnus-agent-file-coding-system))
1011         (write-region (point-min) (point-max)
1012                       (gnus-agent-article-name ".overview"
1013                                                (caar gnus-agent-buffer-alist))
1014                       nil 'silent))
1015       (pop gnus-agent-buffer-alist))
1016     (while gnus-agent-group-alist
1017       (with-temp-file (caar gnus-agent-group-alist)
1018         (princ (cdar gnus-agent-group-alist))
1019         (insert "\n"))
1020       (pop gnus-agent-group-alist))))
1021
1022 (defun gnus-agent-fetch-headers (group &optional force)
1023   (let ((articles (gnus-list-of-unread-articles group))
1024         (gnus-decode-encoded-word-function 'identity)
1025         (file (gnus-agent-article-name ".overview" group))
1026         gnus-agent-cache)
1027     ;; Add article with marks to list of article headers we want to fetch.
1028     (dolist (arts (gnus-info-marks (gnus-get-info group)))
1029       (unless (memq (car arts) '(seen recent))
1030         (setq articles (gnus-range-add articles (cdr arts)))))
1031     (setq articles (sort (gnus-uncompress-sequence articles) '<))
1032     ;; Remove known articles.
1033     (when (gnus-agent-load-alist group)
1034       (setq articles (gnus-sorted-intersection
1035                       articles
1036                       (gnus-uncompress-range
1037                        (cons (1+ (caar (last gnus-agent-article-alist)))
1038                              (cdr (gnus-active group)))))))
1039     ;; Fetch them.
1040     (gnus-make-directory (nnheader-translate-file-chars
1041                           (file-name-directory file) t))
1042     (when articles
1043       (gnus-message 7 "Fetching headers for %s..." group)
1044       (save-excursion
1045         (set-buffer nntp-server-buffer)
1046         (unless (eq 'nov (gnus-retrieve-headers articles group))
1047           (nnvirtual-convert-headers))
1048         ;; Save these headers for later processing.
1049         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1050         (when (file-exists-p file)
1051           (gnus-agent-braid-nov group articles file))
1052         (let ((coding-system-for-write
1053                gnus-agent-file-coding-system))
1054           (write-region (point-min) (point-max) file nil 'silent))
1055         (gnus-agent-save-alist group articles nil)
1056         (gnus-agent-enter-history
1057          "last-header-fetched-for-session"
1058          (list (cons group (nth (- (length  articles) 1) articles)))
1059          (time-to-days (current-time)))
1060         articles))))
1061
1062 (defsubst gnus-agent-copy-nov-line (article)
1063   (let (b e)
1064     (set-buffer gnus-agent-overview-buffer)
1065     (unless (eobp)
1066       (setq b (point))
1067       (if (eq article (read (current-buffer)))
1068           (setq e (progn (forward-line 1) (point)))
1069         (progn
1070           (beginning-of-line)
1071           (setq e b)))
1072       (set-buffer nntp-server-buffer)
1073       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1074
1075 (defun gnus-agent-braid-nov (group articles file)
1076   (set-buffer gnus-agent-overview-buffer)
1077   (goto-char (point-min))
1078   (set-buffer nntp-server-buffer)
1079   (erase-buffer)
1080   (nnheader-insert-file-contents file)
1081   (goto-char (point-max))
1082   (if (or (= (point-min) (point-max))
1083           (progn
1084             (forward-line -1)
1085             (< (read (current-buffer)) (car articles))))
1086       ;; We have only headers that are after the older headers,
1087       ;; so we just append them.
1088       (progn
1089         (goto-char (point-max))
1090         (insert-buffer-substring gnus-agent-overview-buffer))
1091     ;; We do it the hard way.
1092     (nnheader-find-nov-line (car articles))
1093     (gnus-agent-copy-nov-line (car articles))
1094     (pop articles)
1095     (while (and articles
1096                 (not (eobp)))
1097       (while (and (not (eobp))
1098                   (< (read (current-buffer)) (car articles)))
1099         (forward-line 1))
1100       (beginning-of-line)
1101       (unless (eobp)
1102         (gnus-agent-copy-nov-line (car articles))
1103         (setq articles (cdr articles))))
1104     (set-buffer nntp-server-buffer)
1105     (when articles
1106       (let (b e)
1107         (set-buffer gnus-agent-overview-buffer)
1108         (setq b (point)
1109               e (point-max))
1110         (while (and (not (eobp))
1111                     (<= (read (current-buffer)) (car articles)))
1112           (forward-line 1)
1113           (setq b (point)))
1114         (set-buffer nntp-server-buffer)
1115         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
1116
1117 (defun gnus-agent-load-alist (group &optional dir)
1118   "Load the article-state alist for GROUP."
1119   (let ((file ))
1120   (setq gnus-agent-article-alist
1121         (gnus-cache-file-contents
1122          (if dir
1123                   (expand-file-name ".agentview" dir)
1124                 (gnus-agent-article-name ".agentview" group))
1125          'gnus-agent-file-loading-cache
1126          'gnus-agent-read-file))))
1127
1128 (defun gnus-agent-save-alist (group &optional articles state dir)
1129   "Save the article-state alist for GROUP."
1130   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1131          (prev (cons nil gnus-agent-article-alist))
1132          (all prev)
1133          print-level print-length item article)
1134     (while (setq article (pop articles))
1135       (while (and (cdr prev)
1136                  (< (caadr prev) article))
1137         (setq prev (cdr prev)))
1138       (cond
1139        ((not (cdr prev))
1140         (setcdr prev (list (cons article state))))
1141        ((> (caadr prev) article)
1142         (setcdr prev (cons (cons article state) (cdr prev))))
1143        ((= (caadr prev) article)
1144         (setcdr (cadr prev) state)))
1145       (setq prev (cdr prev)))
1146     (setq gnus-agent-article-alist (cdr all))
1147     (with-temp-file (if dir
1148                         (expand-file-name ".agentview" dir)
1149                       (gnus-agent-article-name ".agentview" group))
1150       (princ gnus-agent-article-alist (current-buffer))
1151       (insert "\n"))))
1152
1153 (defun gnus-agent-article-name (article group)
1154   (expand-file-name (if (stringp article) article (string-to-number article))
1155                     (file-name-as-directory
1156                      (expand-file-name (gnus-agent-group-path group)
1157                                        (gnus-agent-directory)))))
1158
1159 (defun gnus-agent-batch-confirmation (msg)
1160   "Show error message and return t."
1161   (gnus-message 1 msg)
1162   t)
1163
1164 ;;;###autoload
1165 (defun gnus-agent-batch-fetch ()
1166   "Start Gnus and fetch session."
1167   (interactive)
1168   (gnus)
1169   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1170     (gnus-agent-fetch-session))
1171   (gnus-group-exit))
1172
1173 (defun gnus-agent-fetch-session ()
1174   "Fetch all articles and headers that are eligible for fetching."
1175   (interactive)
1176   (unless gnus-agent-covered-methods
1177     (error "No servers are covered by the Gnus agent"))
1178   (unless gnus-plugged
1179     (error "Can't fetch articles while Gnus is unplugged"))
1180   (let ((methods gnus-agent-covered-methods)
1181         groups group gnus-command-method)
1182     (save-excursion
1183       (while methods
1184         (condition-case err
1185             (progn
1186               (setq gnus-command-method (car methods))
1187               (when (and (or (gnus-server-opened gnus-command-method)
1188                              (gnus-open-server gnus-command-method))
1189                          (gnus-online gnus-command-method))
1190                 (setq groups (gnus-groups-from-server (car methods)))
1191                 (gnus-agent-with-fetch
1192                   (while (setq group (pop groups))
1193                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1194                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1195           (error
1196            (unless (funcall gnus-agent-confirmation-function
1197                             (format "Error (%s).  Continue? " err))
1198              (error "Cannot fetch articles into the Gnus agent")))
1199           (quit
1200            (unless (funcall gnus-agent-confirmation-function
1201                             (format "Quit fetching session (%s).  Continue? "
1202                                     err))
1203              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1204         (pop methods))
1205       (run-hooks 'gnus-agent-fetch-hook)
1206       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1207
1208 (defun gnus-agent-fetch-group-1 (group method)
1209   "Fetch GROUP."
1210   (let ((gnus-command-method method)
1211         (gnus-newsgroup-name group)
1212         gnus-newsgroup-dependencies gnus-newsgroup-headers
1213         gnus-newsgroup-scored gnus-headers gnus-score
1214         gnus-use-cache articles arts
1215         category predicate info marks score-param
1216         (gnus-summary-expunge-below gnus-summary-expunge-below)
1217         (gnus-summary-mark-below gnus-summary-mark-below)
1218         (gnus-orphan-score gnus-orphan-score)
1219         ;; Maybe some other gnus-summary local variables should also
1220         ;; be put here.
1221         )
1222     (unless (gnus-check-group group)
1223       (error "Can't open server for %s" group))
1224     ;; Fetch headers.
1225     (when (and (or (gnus-active group)
1226                    (gnus-activate-group group))
1227                (setq articles (gnus-agent-fetch-headers group))
1228                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1229                  ;; Parse them and see which articles we want to fetch.
1230                  (setq gnus-newsgroup-dependencies
1231                        (make-vector (length articles) 0))
1232                  (setq gnus-newsgroup-headers
1233                        (gnus-get-newsgroup-headers-xover articles nil nil
1234                                                          group))
1235                  ;; `gnus-agent-overview-buffer' may be killed for
1236                  ;; timeout reason.  If so, recreate it.
1237                  (gnus-agent-create-buffer)))
1238       (setq category (gnus-group-category group))
1239       (setq predicate
1240             (gnus-get-predicate
1241              (or (gnus-group-find-parameter group 'agent-predicate t)
1242                  (cadr category))))
1243       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1244           ;; Simple implementation
1245           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1246         (setq arts nil)
1247         (setq score-param
1248               (or (gnus-group-get-parameter group 'agent-score t)
1249                   (caddr category)))
1250         ;; Translate score-param into real one
1251         (cond
1252          ((not score-param))
1253          ((eq score-param 'file)
1254           (setq score-param (gnus-all-score-files group)))
1255          ((stringp (car score-param)))
1256          (t
1257           (setq score-param (list (list score-param)))))
1258         (when score-param
1259           (gnus-score-headers score-param))
1260         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1261           (setq gnus-score
1262                 (or (cdr (assq (mail-header-number gnus-headers)
1263                                gnus-newsgroup-scored))
1264                     gnus-summary-default-score))
1265           (when (funcall predicate)
1266             (push (mail-header-number gnus-headers)
1267                   arts))))
1268       ;; Fetch the articles.
1269       (when arts
1270         (gnus-agent-fetch-articles group arts)))
1271     ;; Perhaps we have some additional articles to fetch.
1272     (setq arts (assq 'download (gnus-info-marks
1273                                 (setq info (gnus-get-info group)))))
1274     (when (cdr arts)
1275       (gnus-message 8 "Agent is downloading marked articles...")
1276       (gnus-agent-fetch-articles
1277        group (gnus-uncompress-range (cdr arts)))
1278       (setq marks (delq arts (gnus-info-marks info)))
1279       (gnus-info-set-marks info marks)
1280       (gnus-dribble-enter
1281        (concat "(gnus-group-set-info '"
1282                (gnus-prin1-to-string info)
1283                ")")))))
1284
1285 ;;;
1286 ;;; Agent Category Mode
1287 ;;;
1288
1289 (defvar gnus-category-mode-hook nil
1290   "Hook run in `gnus-category-mode' buffers.")
1291
1292 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1293   "Format of category lines.
1294
1295 Valid specifiers include:
1296 %c  Topic name (string)
1297 %g  The number of groups in the topic (integer)
1298
1299 General format specifiers can also be used.  See
1300 (gnus)Formatting Variables.")
1301
1302 (defvar gnus-category-mode-line-format "Gnus: %%b"
1303   "The format specification for the category mode line.")
1304
1305 (defvar gnus-agent-short-article 100
1306   "Articles that have fewer lines than this are short.")
1307
1308 (defvar gnus-agent-long-article 200
1309   "Articles that have more lines than this are long.")
1310
1311 (defvar gnus-agent-low-score 0
1312   "Articles that have a score lower than this have a low score.")
1313
1314 (defvar gnus-agent-high-score 0
1315   "Articles that have a score higher than this have a high score.")
1316
1317
1318 ;;; Internal variables.
1319
1320 (defvar gnus-category-buffer "*Agent Category*")
1321
1322 (defvar gnus-category-line-format-alist
1323   `((?c gnus-tmp-name ?s)
1324     (?g gnus-tmp-groups ?d)))
1325
1326 (defvar gnus-category-mode-line-format-alist
1327   `((?u user-defined ?s)))
1328
1329 (defvar gnus-category-line-format-spec nil)
1330 (defvar gnus-category-mode-line-format-spec nil)
1331
1332 (defvar gnus-category-mode-map nil)
1333 (put 'gnus-category-mode 'mode-class 'special)
1334
1335 (unless gnus-category-mode-map
1336   (setq gnus-category-mode-map (make-sparse-keymap))
1337   (suppress-keymap gnus-category-mode-map)
1338
1339   (gnus-define-keys gnus-category-mode-map
1340     "q" gnus-category-exit
1341     "k" gnus-category-kill
1342     "c" gnus-category-copy
1343     "a" gnus-category-add
1344     "p" gnus-category-edit-predicate
1345     "g" gnus-category-edit-groups
1346     "s" gnus-category-edit-score
1347     "l" gnus-category-list
1348
1349     "\C-c\C-i" gnus-info-find-node
1350     "\C-c\C-b" gnus-bug))
1351
1352 (defvar gnus-category-menu-hook nil
1353   "*Hook run after the creation of the menu.")
1354
1355 (defun gnus-category-make-menu-bar ()
1356   (gnus-turn-off-edit-menu 'category)
1357   (unless (boundp 'gnus-category-menu)
1358     (easy-menu-define
1359      gnus-category-menu gnus-category-mode-map ""
1360      '("Categories"
1361        ["Add" gnus-category-add t]
1362        ["Kill" gnus-category-kill t]
1363        ["Copy" gnus-category-copy t]
1364        ["Edit predicate" gnus-category-edit-predicate t]
1365        ["Edit score" gnus-category-edit-score t]
1366        ["Edit groups" gnus-category-edit-groups t]
1367        ["Exit" gnus-category-exit t]))
1368
1369     (gnus-run-hooks 'gnus-category-menu-hook)))
1370
1371 (defun gnus-category-mode ()
1372   "Major mode for listing and editing agent categories.
1373
1374 All normal editing commands are switched off.
1375 \\<gnus-category-mode-map>
1376 For more in-depth information on this mode, read the manual
1377 (`\\[gnus-info-find-node]').
1378
1379 The following commands are available:
1380
1381 \\{gnus-category-mode-map}"
1382   (interactive)
1383   (when (gnus-visual-p 'category-menu 'menu)
1384     (gnus-category-make-menu-bar))
1385   (kill-all-local-variables)
1386   (gnus-simplify-mode-line)
1387   (setq major-mode 'gnus-category-mode)
1388   (setq mode-name "Category")
1389   (gnus-set-default-directory)
1390   (setq mode-line-process nil)
1391   (use-local-map gnus-category-mode-map)
1392   (buffer-disable-undo)
1393   (setq truncate-lines t)
1394   (setq buffer-read-only t)
1395   (gnus-run-hooks 'gnus-category-mode-hook))
1396
1397 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1398
1399 (defun gnus-category-insert-line (category)
1400   (let* ((gnus-tmp-name (format "%s" (car category)))
1401          (gnus-tmp-groups (length (cadddr category))))
1402     (beginning-of-line)
1403     (gnus-add-text-properties
1404      (point)
1405      (prog1 (1+ (point))
1406        ;; Insert the text.
1407        (eval gnus-category-line-format-spec))
1408      (list 'gnus-category gnus-tmp-name))))
1409
1410 (defun gnus-enter-category-buffer ()
1411   "Go to the Category buffer."
1412   (interactive)
1413   (gnus-category-setup-buffer)
1414   (gnus-configure-windows 'category)
1415   (gnus-category-prepare))
1416
1417 (defun gnus-category-setup-buffer ()
1418   (unless (get-buffer gnus-category-buffer)
1419     (save-excursion
1420       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1421       (gnus-category-mode))))
1422
1423 (defun gnus-category-prepare ()
1424   (gnus-set-format 'category-mode)
1425   (gnus-set-format 'category t)
1426   (let ((alist gnus-category-alist)
1427         (buffer-read-only nil))
1428     (erase-buffer)
1429     (while alist
1430       (gnus-category-insert-line (pop alist)))
1431     (goto-char (point-min))
1432     (gnus-category-position-point)))
1433
1434 (defun gnus-category-name ()
1435   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1436       (error "No category on the current line")))
1437
1438 (defun gnus-category-read ()
1439   "Read the category alist."
1440   (setq gnus-category-alist
1441         (or (gnus-agent-read-file
1442              (nnheader-concat gnus-agent-directory "lib/categories"))
1443             (list (list 'default 'short nil nil)))))
1444
1445 (defun gnus-category-write ()
1446   "Write the category alist."
1447   (setq gnus-category-predicate-cache nil
1448         gnus-category-group-cache nil)
1449   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1450   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1451     (prin1 gnus-category-alist (current-buffer))))
1452
1453 (defun gnus-category-edit-predicate (category)
1454   "Edit the predicate for CATEGORY."
1455   (interactive (list (gnus-category-name)))
1456   (let ((info (assq category gnus-category-alist)))
1457     (gnus-edit-form
1458      (cadr info) (format "Editing the predicate for category %s" category)
1459      `(lambda (predicate)
1460         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1461         (gnus-category-write)
1462         (gnus-category-list)))))
1463
1464 (defun gnus-category-edit-score (category)
1465   "Edit the score expression for CATEGORY."
1466   (interactive (list (gnus-category-name)))
1467   (let ((info (assq category gnus-category-alist)))
1468     (gnus-edit-form
1469      (caddr info)
1470      (format "Editing the score expression for category %s" category)
1471      `(lambda (groups)
1472         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1473         (gnus-category-write)
1474         (gnus-category-list)))))
1475
1476 (defun gnus-category-edit-groups (category)
1477   "Edit the group list for CATEGORY."
1478   (interactive (list (gnus-category-name)))
1479   (let ((info (assq category gnus-category-alist)))
1480     (gnus-edit-form
1481      (cadddr info) (format "Editing the group list for category %s" category)
1482      `(lambda (groups)
1483         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1484         (gnus-category-write)
1485         (gnus-category-list)))))
1486
1487 (defun gnus-category-kill (category)
1488   "Kill the current category."
1489   (interactive (list (gnus-category-name)))
1490   (let ((info (assq category gnus-category-alist))
1491         (buffer-read-only nil))
1492     (gnus-delete-line)
1493     (setq gnus-category-alist (delq info gnus-category-alist))
1494     (gnus-category-write)))
1495
1496 (defun gnus-category-copy (category to)
1497   "Copy the current category."
1498   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1499   (let ((info (assq category gnus-category-alist)))
1500     (push (list to (gnus-copy-sequence (cadr info))
1501                 (gnus-copy-sequence (caddr info)) nil)
1502           gnus-category-alist)
1503     (gnus-category-write)
1504     (gnus-category-list)))
1505
1506 (defun gnus-category-add (category)
1507   "Create a new category."
1508   (interactive "SCategory name: ")
1509   (when (assq category gnus-category-alist)
1510     (error "Category %s already exists" category))
1511   (push (list category 'false nil nil)
1512         gnus-category-alist)
1513   (gnus-category-write)
1514   (gnus-category-list))
1515
1516 (defun gnus-category-list ()
1517   "List all categories."
1518   (interactive)
1519   (gnus-category-prepare))
1520
1521 (defun gnus-category-exit ()
1522   "Return to the group buffer."
1523   (interactive)
1524   (kill-buffer (current-buffer))
1525   (gnus-configure-windows 'group t))
1526
1527 ;; To avoid having 8-bit characters in the source file.
1528 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1529
1530 (defvar gnus-category-predicate-alist
1531   '((spam . gnus-agent-spam-p)
1532     (short . gnus-agent-short-p)
1533     (long . gnus-agent-long-p)
1534     (low . gnus-agent-low-scored-p)
1535     (high . gnus-agent-high-scored-p)
1536     (true . gnus-agent-true)
1537     (false . gnus-agent-false))
1538   "Mapping from short score predicate symbols to predicate functions.")
1539
1540 (defun gnus-agent-spam-p ()
1541   "Say whether an article is spam or not."
1542   (unless gnus-agent-spam-hashtb
1543     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1544   (if (not (equal (mail-header-references gnus-headers) ""))
1545       nil
1546     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1547       (prog1
1548           (gnus-gethash string gnus-agent-spam-hashtb)
1549         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1550
1551 (defun gnus-agent-short-p ()
1552   "Say whether an article is short or not."
1553   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1554
1555 (defun gnus-agent-long-p ()
1556   "Say whether an article is long or not."
1557   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1558
1559 (defun gnus-agent-low-scored-p ()
1560   "Say whether an article has a low score or not."
1561   (< gnus-score gnus-agent-low-score))
1562
1563 (defun gnus-agent-high-scored-p ()
1564   "Say whether an article has a high score or not."
1565   (> gnus-score gnus-agent-high-score))
1566
1567 (defun gnus-category-make-function (cat)
1568   "Make a function from category CAT."
1569   (let ((func (gnus-category-make-function-1 cat)))
1570     (if (and (= (length func) 1)
1571              (symbolp (car func)))
1572         (car func)
1573       (gnus-byte-compile `(lambda () ,func)))))
1574
1575 (defun gnus-agent-true ()
1576   "Return t."
1577   t)
1578
1579 (defun gnus-agent-false ()
1580   "Return nil."
1581   nil)
1582
1583 (defun gnus-category-make-function-1 (cat)
1584   "Make a function from category CAT."
1585   (cond
1586    ;; Functions are just returned as is.
1587    ((or (symbolp cat)
1588         (gnus-functionp cat))
1589     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1590            cat)))
1591    ;; More complex category.
1592    ((consp cat)
1593     `(,(cond
1594         ((memq (car cat) '(& and))
1595          'and)
1596         ((memq (car cat) '(| or))
1597          'or)
1598         ((memq (car cat) gnus-category-not)
1599          'not))
1600       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1601    (t
1602     (error "Unknown category type: %s" cat))))
1603
1604 (defun gnus-get-predicate (predicate)
1605   "Return the predicate for CATEGORY."
1606   (or (cdr (assoc predicate gnus-category-predicate-cache))
1607       (cdar (push (cons predicate
1608                         (gnus-category-make-function predicate))
1609                   gnus-category-predicate-cache))))
1610
1611 (defun gnus-group-category (group)
1612   "Return the category GROUP belongs to."
1613   (unless gnus-category-group-cache
1614     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1615     (let ((cs gnus-category-alist)
1616           groups cat)
1617       (while (setq cat (pop cs))
1618         (setq groups (cadddr cat))
1619         (while groups
1620           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1621   (or (gnus-gethash group gnus-category-group-cache)
1622       (assq 'default gnus-category-alist)))
1623
1624 (defun gnus-agent-expire ()
1625   "Expire all old articles."
1626   (interactive)
1627   (let ((methods gnus-agent-covered-methods)
1628         (day (if (numberp gnus-agent-expire-days)
1629                  (- (time-to-days (current-time)) gnus-agent-expire-days)
1630                nil))
1631         (current-day (time-to-days (current-time)))
1632         gnus-command-method sym group articles
1633         history overview file histories elem art nov-file low info
1634         unreads marked article orig lowest highest found days)
1635     (save-excursion
1636       (setq overview (gnus-get-buffer-create " *expire overview*"))
1637       (while (setq gnus-command-method (pop methods))
1638         (when (file-exists-p (gnus-agent-lib-file "active"))
1639           (with-temp-buffer
1640             (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1641             (gnus-active-to-gnus-format
1642              gnus-command-method
1643              (setq orig (gnus-make-hashtable
1644                          (count-lines (point-min) (point-max))))))
1645           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1646             (gnus-agent-open-history)
1647             (set-buffer
1648              (setq gnus-agent-current-history
1649                    (setq history (gnus-agent-history-buffer))))
1650             (goto-char (point-min))
1651             (when (> (buffer-size) 1)
1652               (goto-char (point-min))
1653               (while (not (eobp))
1654                 (skip-chars-forward "^\t")
1655                 (if (let ((fetch-date (read (current-buffer))))
1656                       (if (numberp fetch-date)
1657                           ;; We now have the arrival day, so we see
1658                           ;; whether it's old enough to be expired.
1659                           (if (numberp day)
1660                               (> fetch-date day)
1661                             (skip-chars-forward "\t")
1662                             (setq found nil
1663                                   days gnus-agent-expire-days)
1664                             (while (and (not found)
1665                                         days)
1666                               (when (looking-at (caar days))
1667                                 (setq found (cadar days)))
1668                               (pop days))
1669                             (> fetch-date (- current-day found)))
1670                         ;; History file is corrupted.
1671                         (gnus-message
1672                          5
1673                          (format "File %s is corrupted!"
1674                                  (gnus-agent-lib-file "history")))
1675                         (sit-for 1)
1676                         ;; Ignore it
1677                         t))
1678                     ;; New article; we don't expire it.
1679                     (forward-line 1)
1680                   ;; Old article.  Schedule it for possible nuking.
1681                   (while (not (eolp))
1682                     (setq sym (let ((obarray expiry-hashtb) s)
1683                                 (setq s (read (current-buffer)))
1684                                 (if (stringp s) (intern s) s)))
1685                     (if (boundp sym)
1686                         (set sym (cons (cons (read (current-buffer)) (point))
1687                                        (symbol-value sym)))
1688                       (set sym (list (cons (read (current-buffer)) (point)))))
1689                     (skip-chars-forward " "))
1690                   (forward-line 1)))
1691               ;; We now have all articles that can possibly be expired.
1692               (mapatoms
1693                (lambda (sym)
1694                  (setq group (symbol-name sym)
1695                        articles (sort (symbol-value sym) 'car-less-than-car)
1696                        low (car (gnus-active group))
1697                        info (gnus-get-info group)
1698                        unreads (ignore-errors
1699                                  (gnus-list-of-unread-articles group))
1700                        marked (nconc
1701                                (gnus-uncompress-range
1702                                 (cdr (assq 'tick (gnus-info-marks info))))
1703                                (gnus-uncompress-range
1704                                 (cdr (assq 'dormant
1705                                            (gnus-info-marks info)))))
1706                        nov-file (gnus-agent-article-name ".overview" group)
1707                        lowest nil
1708                        highest nil)
1709                  (gnus-agent-load-alist group)
1710                  (gnus-message 5 "Expiring articles in %s" group)
1711                  (set-buffer overview)
1712                  (erase-buffer)
1713                  (when (file-exists-p nov-file)
1714                    (nnheader-insert-file-contents nov-file))
1715                  (goto-char (point-min))
1716                  (setq article 0)
1717                  (while (setq elem (pop articles))
1718                    (setq article (car elem))
1719                    (when (or (null low)
1720                              (< article low)
1721                              gnus-agent-expire-all
1722                              (and (not (memq article unreads))
1723                                   (not (memq article marked))))
1724                      ;; Find and nuke the NOV line.
1725                      (while (and (not (eobp))
1726                                  (or (not (numberp
1727                                            (setq art (read (current-buffer)))))
1728                                      (< art article)))
1729                        (if (and (numberp art)
1730                                 (file-exists-p
1731                                  (gnus-agent-article-name
1732                                   (number-to-string art) group)))
1733                            (progn
1734                              (unless lowest
1735                                (setq lowest art))
1736                              (setq highest art)
1737                              (forward-line 1))
1738                          ;; Remove old NOV lines that have no articles.
1739                          (gnus-delete-line)))
1740                      (if (or (eobp)
1741                              (/= art article))
1742                          (beginning-of-line)
1743                        (gnus-delete-line))
1744                      ;; Nuke the article.
1745                      (when (file-exists-p
1746                             (setq file (gnus-agent-article-name
1747                                         (number-to-string article)
1748                                         group)))
1749                        (delete-file file))
1750                      ;; Schedule the history line for nuking.
1751                      (push (cdr elem) histories)))
1752                  (gnus-make-directory (file-name-directory nov-file))
1753                  (let ((coding-system-for-write
1754                         gnus-agent-file-coding-system))
1755                    (write-region (point-min) (point-max) nov-file nil 'silent))
1756                  ;; Delete the unwanted entries in the alist.
1757                  (setq gnus-agent-article-alist
1758                        (sort gnus-agent-article-alist 'car-less-than-car))
1759                  (let* ((alist gnus-agent-article-alist)
1760                         (prev (cons nil alist))
1761                         (first prev)
1762                         expired)
1763                    (while (and alist
1764                                (<= (caar alist) article))
1765                      (if (or (not (cdar alist))
1766                              (not (file-exists-p
1767                                    (gnus-agent-article-name
1768                                     (number-to-string
1769                                      (caar alist))
1770                                     group))))
1771                          (progn
1772                            (push (caar alist) expired)
1773                            (setcdr prev (setq alist (cdr alist))))
1774                        (setq prev alist
1775                              alist (cdr alist))))
1776                    (setq gnus-agent-article-alist (cdr first))
1777                    (gnus-agent-save-alist group)
1778                    ;; Mark all articles up to the first article
1779                    ;; in `gnus-article-alist' as read.
1780                    (when (and info (caar gnus-agent-article-alist))
1781                      (setcar (nthcdr 2 info)
1782                              (gnus-range-add
1783                               (nth 2 info)
1784                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1785                    ;; Maybe everything has been expired from
1786                    ;; `gnus-article-alist' and so the above marking as
1787                    ;; read could not be conducted, or there are
1788                    ;; expired article within the range of the alist.
1789                    (when (and info
1790                               expired
1791                               (or (not (caar gnus-agent-article-alist))
1792                                   (> (car expired)
1793                                      (caar gnus-agent-article-alist))))
1794                      (setcar (nthcdr 2 info)
1795                              (gnus-add-to-range
1796                               (nth 2 info)
1797                               (nreverse expired))))
1798                    (gnus-dribble-enter
1799                     (concat "(gnus-group-set-info '"
1800                             (gnus-prin1-to-string info)
1801                             ")")))
1802                  (when lowest
1803                    (if (gnus-gethash group orig)
1804                        (setcar (gnus-gethash group orig) lowest)
1805                      (gnus-sethash group (cons lowest highest) orig))))
1806                expiry-hashtb)
1807               (set-buffer history)
1808               (setq histories (nreverse (sort histories '<)))
1809               (while histories
1810                 (goto-char (pop histories))
1811                 (gnus-delete-line))
1812               (gnus-agent-save-history)
1813               (gnus-agent-close-history)
1814               (gnus-write-active-file
1815                (gnus-agent-lib-file "active") orig))
1816             (gnus-message 4 "Expiry...done")))))))
1817
1818 ;;;###autoload
1819 (defun gnus-agent-batch ()
1820   (interactive)
1821   (let ((init-file-user "")
1822         (gnus-always-read-dribble-file t))
1823     (gnus))
1824   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1825     (gnus-group-send-queue)
1826     (gnus-agent-fetch-session)))
1827
1828 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
1829   (save-excursion
1830     (gnus-agent-create-buffer)
1831     (let ((gnus-decode-encoded-word-function 'identity)
1832           (file (gnus-agent-article-name ".overview" group))
1833           cached-articles uncached-articles)
1834       (gnus-make-directory (nnheader-translate-file-chars
1835                             (file-name-directory file) t))
1836       (when (file-exists-p file)
1837         (with-current-buffer gnus-agent-overview-buffer
1838           (erase-buffer)
1839           (let ((nnheader-file-coding-system
1840                  gnus-agent-file-coding-system))
1841             (nnheader-insert-file-contents file))
1842           (goto-char (point-min)) 
1843           (while (not (eobp))
1844             (when (looking-at "[0-9]")
1845               (push (read (current-buffer)) cached-articles))
1846             (forward-line 1))
1847           (setq cached-articles (sort cached-articles '<))))
1848       (if (setq uncached-articles 
1849                 (gnus-set-difference articles cached-articles))
1850           (progn
1851             (set-buffer nntp-server-buffer)
1852             (erase-buffer)
1853             (let (gnus-agent-cache)
1854               (unless (eq 'nov 
1855                           (gnus-retrieve-headers 
1856                            uncached-articles group fetch-old))
1857                 (nnvirtual-convert-headers)))
1858             (set-buffer gnus-agent-overview-buffer)
1859             (erase-buffer)
1860             (set-buffer nntp-server-buffer)
1861             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1862             (when (and uncached-articles (file-exists-p file))
1863               (gnus-agent-braid-nov group uncached-articles file))
1864             (set-buffer nntp-server-buffer)
1865             (let ((coding-system-for-write
1866                    gnus-agent-file-coding-system))
1867               (write-region (point-min) (point-max) file nil 'silent))
1868             (gnus-agent-load-alist group)
1869             (gnus-agent-save-alist group uncached-articles nil)
1870             (gnus-agent-open-history)
1871             (setq gnus-agent-current-history (gnus-agent-history-buffer))
1872             (gnus-agent-enter-history
1873              "last-header-fetched-for-session"
1874              (list (cons group (nth (- (length  articles) 1) articles)))
1875              (time-to-days (current-time)))
1876             (gnus-agent-save-history))
1877         (set-buffer nntp-server-buffer)
1878         (erase-buffer)
1879         (insert-buffer-substring gnus-agent-overview-buffer)))
1880     (if (and fetch-old
1881              (not (numberp fetch-old)))
1882         t                               ; Don't remove anything.
1883       (nnheader-nov-delete-outside-range
1884        (if fetch-old (max 1 (- (car articles) fetch-old))
1885          (car articles))
1886        (car (last articles)))
1887       t)
1888     'nov))
1889
1890 (defun gnus-agent-request-article (article group)
1891   "Retrieve ARTICLE in GROUP from the agent cache."
1892   (let* ((gnus-command-method (gnus-find-method-for-group group))
1893          (file (concat
1894                   (gnus-agent-directory)
1895                   (gnus-agent-group-path group) "/"
1896                   (number-to-string article)))
1897          (buffer-read-only nil))
1898     (when (and (file-exists-p file)
1899                (> (nth 7 (file-attributes file)) 0))
1900       (erase-buffer)
1901       (gnus-kill-all-overlays)
1902       (let ((coding-system-for-read gnus-cache-coding-system))
1903         (insert-file-contents file))
1904       t)))
1905
1906 (defun gnus-agent-regenerate-group (group &optional clean)
1907   "Regenerate GROUP."
1908   (let ((dir (concat (gnus-agent-directory)
1909                      (gnus-agent-group-path group) "/"))
1910         (file (gnus-agent-article-name ".overview" group))
1911         n point arts alist header new-alist changed)
1912     (when (file-exists-p dir)
1913       (setq arts
1914             (sort (mapcar (lambda (name) (string-to-int name))
1915                           (directory-files dir nil "^[0-9]+$" t))
1916                   '<)))
1917     (gnus-make-directory (nnheader-translate-file-chars
1918                           (file-name-directory file) t))
1919     (mm-with-unibyte-buffer
1920       (if (file-exists-p file)
1921           (let ((nnheader-file-coding-system
1922                  gnus-agent-file-coding-system))
1923             (nnheader-insert-file-contents file)))
1924       (goto-char (point-min)) 
1925       (while (not (eobp))
1926         (while (not (or (eobp) (looking-at "[0-9]")))
1927           (setq point (point))
1928           (forward-line 1)
1929           (delete-region point (point)))
1930         (unless (eobp)
1931           (setq n (read (current-buffer)))
1932           (when (and arts (> n (car arts)))
1933             (beginning-of-line)
1934             (while (and arts (> n (car arts)))
1935               (message "Regenerating NOV %s %d..." group (car arts))
1936               (mm-with-unibyte-buffer
1937                 (nnheader-insert-file-contents 
1938                  (concat dir (number-to-string (car arts))))
1939                 (goto-char (point-min))
1940                 (if (search-forward "\n\n" nil t)
1941                     (delete-region (point) (point-max))
1942                   (goto-char (point-max)))
1943                 (setq header (nnheader-parse-head t)))
1944               (mail-header-set-number header (car arts))
1945               (nnheader-insert-nov header)
1946               (setq changed t)
1947               (push (cons (car arts) t) alist)
1948               (pop arts)))
1949           (if (and arts (= n (car arts)))
1950               (progn
1951                 (push (cons n t) alist)
1952                 (pop arts))
1953             (push (cons n nil) alist))
1954           (forward-line 1)))
1955       (if changed
1956           (let ((coding-system-for-write gnus-agent-file-coding-system))
1957             (write-region (point-min) (point-max) file nil 'silent))))
1958     (setq gnus-agent-article-alist nil)
1959     (unless clean
1960       (gnus-agent-load-alist group))
1961     (setq alist (sort alist 'car-less-than-car))
1962     (setq gnus-agent-article-alist (sort gnus-agent-article-alist 
1963                                          'car-less-than-car))
1964     (while (and alist gnus-agent-article-alist)
1965       (cond 
1966        ((< (caar alist) (caar gnus-agent-article-alist))
1967         (push (pop alist) new-alist))
1968        ((> (caar alist) (caar gnus-agent-article-alist))
1969         (push (list (car (pop gnus-agent-article-alist))) new-alist))
1970        (t 
1971         (pop gnus-agent-article-alist)
1972         (while (and gnus-agent-article-alist
1973                     (= (caar alist) (caar gnus-agent-article-alist)))
1974           (pop gnus-agent-article-alist))
1975         (push (pop alist) new-alist))))
1976     (while alist
1977       (push (pop alist) new-alist))
1978     (while gnus-agent-article-alist
1979       (push (list (car (pop gnus-agent-article-alist))) new-alist))
1980     (setq gnus-agent-article-alist (nreverse new-alist))
1981     (gnus-agent-save-alist group)))
1982
1983 (defun gnus-agent-regenerate-history (group article)
1984   (let ((file (concat (gnus-agent-directory)
1985                       (gnus-agent-group-path group) "/"
1986                       (number-to-string article))) id)
1987     (mm-with-unibyte-buffer
1988       (nnheader-insert-file-contents file)
1989       (message-narrow-to-head)
1990       (goto-char (point-min))
1991       (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1992           (setq id "No-Message-ID-in-article")
1993         (setq id (buffer-substring (match-beginning 1) (match-end 1))))
1994       (gnus-agent-enter-history 
1995        id (list (cons group article)) 
1996        (time-to-days (nth 5 (file-attributes file)))))))
1997
1998 ;;;###autoload
1999 (defun gnus-agent-regenerate (&optional clean)
2000   "Regenerate all agent covered files.
2001 If CLEAN, don't read existing active and agentview files."
2002   (interactive "P")
2003   (message "Regenerating Gnus agent files...")
2004   (dolist (gnus-command-method gnus-agent-covered-methods)
2005     (let ((active-file (gnus-agent-lib-file "active"))
2006           history-hashtb active-hashtb active-changed 
2007           history-changed point)
2008       (gnus-make-directory (file-name-directory active-file))
2009       (if clean
2010           (setq active-hashtb (gnus-make-hashtable 1000))
2011         (mm-with-unibyte-buffer
2012           (if (file-exists-p active-file)
2013               (let ((nnheader-file-coding-system
2014                      gnus-agent-file-coding-system))
2015                 (nnheader-insert-file-contents active-file))
2016             (setq active-changed t))
2017           (gnus-active-to-gnus-format
2018            nil (setq active-hashtb
2019                      (gnus-make-hashtable
2020                       (count-lines (point-min) (point-max)))))))
2021       (gnus-agent-open-history)
2022       (setq history-hashtb (gnus-make-hashtable 1000))
2023       (with-current-buffer
2024           (setq gnus-agent-current-history (gnus-agent-history-buffer))
2025         (goto-char (point-min))
2026         (forward-line 1)
2027         (while (not (eobp))
2028           (if (looking-at 
2029                "\\([^\t\n]+\\)\t[0-9]+\t\\([^ \n]+\\) \\([0-9]+\\)")
2030               (progn
2031                 (unless (string= (match-string 1) 
2032                                  "last-header-fetched-for-session")
2033                   (gnus-sethash (match-string 2) 
2034                                 (cons (string-to-number (match-string 3))
2035                                       (gnus-gethash-safe (match-string 2)
2036                                                          history-hashtb))
2037                                 history-hashtb))
2038                 (forward-line 1))
2039             (setq point (point))
2040             (forward-line 1)
2041             (delete-region point (point))
2042             (setq history-changed t))))
2043       (dolist (group (gnus-groups-from-server gnus-command-method))
2044         (gnus-agent-regenerate-group group clean)
2045         (let ((min (or (caar gnus-agent-article-alist) 1))
2046               (max (or (caar (last gnus-agent-article-alist)) 0))
2047               (active (gnus-gethash-safe (gnus-group-real-name group)
2048                                          active-hashtb)))
2049           (if (not active)
2050               (progn
2051                 (setq active (cons min max)
2052                       active-changed t)
2053                 (gnus-sethash group active active-hashtb))
2054             (when (> (car active) min)
2055               (setcar active min)
2056               (setq active-changed t))
2057             (when (< (cdr active) max)
2058               (setcdr active max)
2059               (setq active-changed t))))
2060         (let ((arts (sort (gnus-gethash-safe group history-hashtb) '<))
2061               n)
2062           (gnus-sethash group arts history-hashtb)
2063           (while (and arts gnus-agent-article-alist)
2064             (cond 
2065              ((> (car arts) (caar gnus-agent-article-alist))
2066               (when (cdar gnus-agent-article-alist)
2067                 (gnus-agent-regenerate-history 
2068                  group (caar gnus-agent-article-alist))
2069                 (setq history-changed t))
2070               (setq n (car (pop gnus-agent-article-alist)))
2071               (while (and gnus-agent-article-alist 
2072                           (= n (caar gnus-agent-article-alist)))
2073                 (pop gnus-agent-article-alist)))
2074              ((< (car arts) (caar gnus-agent-article-alist))
2075               (setq n (pop arts))
2076               (while (and arts (= n (car arts)))
2077                 (pop arts)))
2078              (t
2079               (setq n (car (pop gnus-agent-article-alist)))
2080               (while (and gnus-agent-article-alist 
2081                           (= n (caar gnus-agent-article-alist)))
2082                 (pop gnus-agent-article-alist))
2083               (setq n (pop arts))
2084               (while (and arts (= n (car arts)))
2085                 (pop arts)))))
2086           (while gnus-agent-article-alist
2087             (when (cdar gnus-agent-article-alist)
2088               (gnus-agent-regenerate-history 
2089                group (caar gnus-agent-article-alist))
2090               (setq history-changed t))
2091             (pop gnus-agent-article-alist))))
2092       (when history-changed
2093         (message "Regenerate the history file of %s:%s" 
2094                  (car gnus-command-method)
2095                  (cadr gnus-command-method))
2096         (gnus-agent-save-history))
2097       (gnus-agent-close-history)
2098       (when active-changed
2099         (message "Regenerate %s" active-file) 
2100         (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2101           (gnus-write-active-file active-file active-hashtb)))))
2102   (message "Regenerating Gnus agent files...done"))
2103
2104 (defun gnus-agent-go-online (&optional force)
2105   "Switch servers into online status."
2106   (interactive (list t))
2107   (dolist (server gnus-opened-servers)
2108     (when (eq (nth 1 server) 'offline)
2109       (if (if (eq force 'ask) 
2110               (gnus-y-or-n-p 
2111                (format "Switch %s:%s into online status? "
2112                        (caar server) (cadar server)))
2113             force)
2114           (setcar (nthcdr 1 server) 'close)))))
2115
2116 (defun gnus-agent-toggle-group-plugged (group)
2117   "Toggle the status of the server of the current group."
2118   (interactive (list (gnus-group-group-name)))
2119   (let* ((method (gnus-find-method-for-group group))
2120          (status (cadr (assoc method gnus-opened-servers))))
2121     (if (eq status 'offline)
2122         (gnus-server-set-status method 'closed)
2123       (gnus-close-server method)
2124       (gnus-server-set-status method 'offline))
2125     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2126              (if (eq status 'offline) 'offline 'online)
2127              (if (eq status 'offline) 'online 'offline))))
2128
2129 (provide 'gnus-agent)
2130
2131 ;;; gnus-agent.el ends here