* gnus-sum.el (gnus-summary-update-info): Use
[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             (unless (eobp)  ;; Don't save empty articles.
948               (when (search-forward "\n\n" nil t)
949                 (when (search-backward "\nXrefs: " nil t)
950                   ;; Handle cross posting.
951                   (skip-chars-forward "^ ")
952                   (skip-chars-forward " ")
953                   (setq crosses nil)
954                   (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
955                     (push (cons (buffer-substring (match-beginning 1)
956                                                   (match-end 1))
957                                 (buffer-substring (match-beginning 2)
958                                                   (match-end 2)))
959                           crosses)
960                     (goto-char (match-end 0)))
961                   (gnus-agent-crosspost crosses (caar pos))))
962               (goto-char (point-min))
963               (if (not (re-search-forward 
964                         "^Message-ID: *<\\([^>\n]+\\)>" nil t))
965                   (setq id "No-Message-ID-in-article")
966                 (setq id (buffer-substring (match-beginning 1) (match-end 1))))
967               (let ((coding-system-for-write
968                      gnus-agent-file-coding-system))
969                 (write-region (point-min) (point-max)
970                               (concat dir (number-to-string (caar pos)))
971                               nil 'silent))
972               (when (setq elem (assq (caar pos) gnus-agent-article-alist))
973                 (setcdr elem t))
974               (gnus-agent-enter-history
975                id (or crosses (list (cons group (caar pos)))) date))
976             (widen)
977             (pop pos)))
978         (gnus-agent-save-alist group)))))
979
980 (defun gnus-agent-crosspost (crosses article)
981   (let (gnus-agent-article-alist group alist beg end)
982     (save-excursion
983       (set-buffer gnus-agent-overview-buffer)
984       (when (nnheader-find-nov-line article)
985         (forward-word 1)
986         (setq beg (point))
987         (setq end (progn (forward-line 1) (point)))))
988     (while crosses
989       (setq group (caar crosses))
990       (unless (setq alist (assoc group gnus-agent-group-alist))
991         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
992               gnus-agent-group-alist))
993       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
994       (save-excursion
995         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
996                                                     group)))
997         (when (= (point-max) (point-min))
998           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
999           (ignore-errors
1000             (nnheader-insert-file-contents
1001              (gnus-agent-article-name ".overview" group))))
1002         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1003         (insert (string-to-number (cdar crosses)))
1004         (insert-buffer-substring gnus-agent-overview-buffer beg end))
1005       (pop crosses))))
1006
1007 (defun gnus-agent-flush-cache ()
1008   (save-excursion
1009     (while gnus-agent-buffer-alist
1010       (set-buffer (cdar gnus-agent-buffer-alist))
1011       (let ((coding-system-for-write
1012              gnus-agent-file-coding-system))
1013         (write-region (point-min) (point-max)
1014                       (gnus-agent-article-name ".overview"
1015                                                (caar gnus-agent-buffer-alist))
1016                       nil 'silent))
1017       (pop gnus-agent-buffer-alist))
1018     (while gnus-agent-group-alist
1019       (with-temp-file (caar gnus-agent-group-alist)
1020         (princ (cdar gnus-agent-group-alist))
1021         (insert "\n"))
1022       (pop gnus-agent-group-alist))))
1023
1024 (defun gnus-agent-fetch-headers (group &optional force)
1025   (let ((articles (gnus-list-of-unread-articles group))
1026         (gnus-decode-encoded-word-function 'identity)
1027         (file (gnus-agent-article-name ".overview" group))
1028         gnus-agent-cache)
1029     ;; Add article with marks to list of article headers we want to fetch.
1030     (dolist (arts (gnus-info-marks (gnus-get-info group)))
1031       (unless (memq (car arts) '(seen recent))
1032         (setq articles (gnus-range-add articles (cdr arts)))))
1033     (setq articles (sort (gnus-uncompress-sequence articles) '<))
1034     ;; Remove known articles.
1035     (when (gnus-agent-load-alist group)
1036       (setq articles (gnus-list-range-intersection 
1037                       articles
1038                       (list
1039                        (cons (1+ (caar (last gnus-agent-article-alist)))
1040                              (cdr (gnus-active group)))))))
1041     ;; Fetch them.
1042     (gnus-make-directory (nnheader-translate-file-chars
1043                           (file-name-directory file) t))
1044     (when articles
1045       (gnus-message 7 "Fetching headers for %s..." group)
1046       (save-excursion
1047         (set-buffer nntp-server-buffer)
1048         (unless (eq 'nov (gnus-retrieve-headers articles group))
1049           (nnvirtual-convert-headers))
1050         ;; Save these headers for later processing.
1051         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1052         (when (file-exists-p file)
1053           (gnus-agent-braid-nov group articles file))
1054         (let ((coding-system-for-write
1055                gnus-agent-file-coding-system))
1056           (write-region (point-min) (point-max) file nil 'silent))
1057         (gnus-agent-save-alist group articles nil)
1058         (gnus-agent-enter-history
1059          "last-header-fetched-for-session"
1060          (list (cons group (nth (- (length  articles) 1) articles)))
1061          (time-to-days (current-time)))
1062         articles))))
1063
1064 (defsubst gnus-agent-copy-nov-line (article)
1065   (let (b e)
1066     (set-buffer gnus-agent-overview-buffer)
1067     (unless (eobp)
1068       (setq b (point))
1069       (if (eq article (read (current-buffer)))
1070           (setq e (progn (forward-line 1) (point)))
1071         (progn
1072           (beginning-of-line)
1073           (setq e b)))
1074       (set-buffer nntp-server-buffer)
1075       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1076
1077 (defun gnus-agent-braid-nov (group articles file)
1078   (set-buffer gnus-agent-overview-buffer)
1079   (goto-char (point-min))
1080   (set-buffer nntp-server-buffer)
1081   (erase-buffer)
1082   (nnheader-insert-file-contents file)
1083   (goto-char (point-max))
1084   (if (or (= (point-min) (point-max))
1085           (progn
1086             (forward-line -1)
1087             (< (read (current-buffer)) (car articles))))
1088       ;; We have only headers that are after the older headers,
1089       ;; so we just append them.
1090       (progn
1091         (goto-char (point-max))
1092         (insert-buffer-substring gnus-agent-overview-buffer))
1093     ;; We do it the hard way.
1094     (nnheader-find-nov-line (car articles))
1095     (gnus-agent-copy-nov-line (car articles))
1096     (pop articles)
1097     (while (and articles
1098                 (not (eobp)))
1099       (while (and (not (eobp))
1100                   (< (read (current-buffer)) (car articles)))
1101         (forward-line 1))
1102       (beginning-of-line)
1103       (unless (eobp)
1104         (gnus-agent-copy-nov-line (car articles))
1105         (setq articles (cdr articles))))
1106     (set-buffer nntp-server-buffer)
1107     (when articles
1108       (let (b e)
1109         (set-buffer gnus-agent-overview-buffer)
1110         (setq b (point)
1111               e (point-max))
1112         (while (and (not (eobp))
1113                     (<= (read (current-buffer)) (car articles)))
1114           (forward-line 1)
1115           (setq b (point)))
1116         (set-buffer nntp-server-buffer)
1117         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
1118
1119 (defun gnus-agent-load-alist (group &optional dir)
1120   "Load the article-state alist for GROUP."
1121   (let ((file ))
1122   (setq gnus-agent-article-alist
1123         (gnus-cache-file-contents
1124          (if dir
1125                   (expand-file-name ".agentview" dir)
1126                 (gnus-agent-article-name ".agentview" group))
1127          'gnus-agent-file-loading-cache
1128          'gnus-agent-read-file))))
1129
1130 (defun gnus-agent-save-alist (group &optional articles state dir)
1131   "Save the article-state alist for GROUP."
1132   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1133          (prev (cons nil gnus-agent-article-alist))
1134          (all prev)
1135          print-level print-length item article)
1136     (while (setq article (pop articles))
1137       (while (and (cdr prev)
1138                  (< (caadr prev) article))
1139         (setq prev (cdr prev)))
1140       (cond
1141        ((not (cdr prev))
1142         (setcdr prev (list (cons article state))))
1143        ((> (caadr prev) article)
1144         (setcdr prev (cons (cons article state) (cdr prev))))
1145        ((= (caadr prev) article)
1146         (setcdr (cadr prev) state)))
1147       (setq prev (cdr prev)))
1148     (setq gnus-agent-article-alist (cdr all))
1149     (with-temp-file (if dir
1150                         (expand-file-name ".agentview" dir)
1151                       (gnus-agent-article-name ".agentview" group))
1152       (princ gnus-agent-article-alist (current-buffer))
1153       (insert "\n"))))
1154
1155 (defun gnus-agent-article-name (article group)
1156   (expand-file-name (if (stringp article) article (string-to-number article))
1157                     (file-name-as-directory
1158                      (expand-file-name (gnus-agent-group-path group)
1159                                        (gnus-agent-directory)))))
1160
1161 (defun gnus-agent-batch-confirmation (msg)
1162   "Show error message and return t."
1163   (gnus-message 1 msg)
1164   t)
1165
1166 ;;;###autoload
1167 (defun gnus-agent-batch-fetch ()
1168   "Start Gnus and fetch session."
1169   (interactive)
1170   (gnus)
1171   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1172     (gnus-agent-fetch-session))
1173   (gnus-group-exit))
1174
1175 (defun gnus-agent-fetch-session ()
1176   "Fetch all articles and headers that are eligible for fetching."
1177   (interactive)
1178   (unless gnus-agent-covered-methods
1179     (error "No servers are covered by the Gnus agent"))
1180   (unless gnus-plugged
1181     (error "Can't fetch articles while Gnus is unplugged"))
1182   (let ((methods gnus-agent-covered-methods)
1183         groups group gnus-command-method)
1184     (save-excursion
1185       (while methods
1186         (condition-case err
1187             (progn
1188               (setq gnus-command-method (car methods))
1189               (when (and (or (gnus-server-opened gnus-command-method)
1190                              (gnus-open-server gnus-command-method))
1191                          (gnus-online gnus-command-method))
1192                 (setq groups (gnus-groups-from-server (car methods)))
1193                 (gnus-agent-with-fetch
1194                   (while (setq group (pop groups))
1195                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1196                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1197           (error
1198            (unless (funcall gnus-agent-confirmation-function
1199                             (format "Error (%s).  Continue? " err))
1200              (error "Cannot fetch articles into the Gnus agent")))
1201           (quit
1202            (unless (funcall gnus-agent-confirmation-function
1203                             (format "Quit fetching session (%s).  Continue? "
1204                                     err))
1205              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1206         (pop methods))
1207       (run-hooks 'gnus-agent-fetch-hook)
1208       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1209
1210 (defun gnus-agent-fetch-group-1 (group method)
1211   "Fetch GROUP."
1212   (let ((gnus-command-method method)
1213         (gnus-newsgroup-name group)
1214         gnus-newsgroup-dependencies gnus-newsgroup-headers
1215         gnus-newsgroup-scored gnus-headers gnus-score
1216         gnus-use-cache articles arts
1217         category predicate info marks score-param
1218         (gnus-summary-expunge-below gnus-summary-expunge-below)
1219         (gnus-summary-mark-below gnus-summary-mark-below)
1220         (gnus-orphan-score gnus-orphan-score)
1221         ;; Maybe some other gnus-summary local variables should also
1222         ;; be put here.
1223         )
1224     (unless (gnus-check-group group)
1225       (error "Can't open server for %s" group))
1226     ;; Fetch headers.
1227     (when (and (or (gnus-active group)
1228                    (gnus-activate-group group))
1229                (setq articles (gnus-agent-fetch-headers group))
1230                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1231                  ;; Parse them and see which articles we want to fetch.
1232                  (setq gnus-newsgroup-dependencies
1233                        (make-vector (length articles) 0))
1234                  (setq gnus-newsgroup-headers
1235                        (gnus-get-newsgroup-headers-xover articles nil nil
1236                                                          group))
1237                  ;; `gnus-agent-overview-buffer' may be killed for
1238                  ;; timeout reason.  If so, recreate it.
1239                  (gnus-agent-create-buffer)))
1240       (setq category (gnus-group-category group))
1241       (setq predicate
1242             (gnus-get-predicate
1243              (or (gnus-group-find-parameter group 'agent-predicate t)
1244                  (cadr category))))
1245       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1246           ;; Simple implementation
1247           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1248         (setq arts nil)
1249         (setq score-param
1250               (or (gnus-group-get-parameter group 'agent-score t)
1251                   (caddr category)))
1252         ;; Translate score-param into real one
1253         (cond
1254          ((not score-param))
1255          ((eq score-param 'file)
1256           (setq score-param (gnus-all-score-files group)))
1257          ((stringp (car score-param)))
1258          (t
1259           (setq score-param (list (list score-param)))))
1260         (when score-param
1261           (gnus-score-headers score-param))
1262         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1263           (setq gnus-score
1264                 (or (cdr (assq (mail-header-number gnus-headers)
1265                                gnus-newsgroup-scored))
1266                     gnus-summary-default-score))
1267           (when (funcall predicate)
1268             (push (mail-header-number gnus-headers)
1269                   arts))))
1270       ;; Fetch the articles.
1271       (when arts
1272         (gnus-agent-fetch-articles group arts)))
1273     ;; Perhaps we have some additional articles to fetch.
1274     (setq arts (assq 'download (gnus-info-marks
1275                                 (setq info (gnus-get-info group)))))
1276     (when (cdr arts)
1277       (gnus-message 8 "Agent is downloading marked articles...")
1278       (gnus-agent-fetch-articles
1279        group (gnus-uncompress-range (cdr arts)))
1280       (setq marks (delq arts (gnus-info-marks info)))
1281       (gnus-info-set-marks info marks)
1282       (gnus-dribble-enter
1283        (concat "(gnus-group-set-info '"
1284                (gnus-prin1-to-string info)
1285                ")")))))
1286
1287 ;;;
1288 ;;; Agent Category Mode
1289 ;;;
1290
1291 (defvar gnus-category-mode-hook nil
1292   "Hook run in `gnus-category-mode' buffers.")
1293
1294 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1295   "Format of category lines.
1296
1297 Valid specifiers include:
1298 %c  Topic name (string)
1299 %g  The number of groups in the topic (integer)
1300
1301 General format specifiers can also be used.  See
1302 (gnus)Formatting Variables.")
1303
1304 (defvar gnus-category-mode-line-format "Gnus: %%b"
1305   "The format specification for the category mode line.")
1306
1307 (defvar gnus-agent-short-article 100
1308   "Articles that have fewer lines than this are short.")
1309
1310 (defvar gnus-agent-long-article 200
1311   "Articles that have more lines than this are long.")
1312
1313 (defvar gnus-agent-low-score 0
1314   "Articles that have a score lower than this have a low score.")
1315
1316 (defvar gnus-agent-high-score 0
1317   "Articles that have a score higher than this have a high score.")
1318
1319
1320 ;;; Internal variables.
1321
1322 (defvar gnus-category-buffer "*Agent Category*")
1323
1324 (defvar gnus-category-line-format-alist
1325   `((?c gnus-tmp-name ?s)
1326     (?g gnus-tmp-groups ?d)))
1327
1328 (defvar gnus-category-mode-line-format-alist
1329   `((?u user-defined ?s)))
1330
1331 (defvar gnus-category-line-format-spec nil)
1332 (defvar gnus-category-mode-line-format-spec nil)
1333
1334 (defvar gnus-category-mode-map nil)
1335 (put 'gnus-category-mode 'mode-class 'special)
1336
1337 (unless gnus-category-mode-map
1338   (setq gnus-category-mode-map (make-sparse-keymap))
1339   (suppress-keymap gnus-category-mode-map)
1340
1341   (gnus-define-keys gnus-category-mode-map
1342     "q" gnus-category-exit
1343     "k" gnus-category-kill
1344     "c" gnus-category-copy
1345     "a" gnus-category-add
1346     "p" gnus-category-edit-predicate
1347     "g" gnus-category-edit-groups
1348     "s" gnus-category-edit-score
1349     "l" gnus-category-list
1350
1351     "\C-c\C-i" gnus-info-find-node
1352     "\C-c\C-b" gnus-bug))
1353
1354 (defvar gnus-category-menu-hook nil
1355   "*Hook run after the creation of the menu.")
1356
1357 (defun gnus-category-make-menu-bar ()
1358   (gnus-turn-off-edit-menu 'category)
1359   (unless (boundp 'gnus-category-menu)
1360     (easy-menu-define
1361      gnus-category-menu gnus-category-mode-map ""
1362      '("Categories"
1363        ["Add" gnus-category-add t]
1364        ["Kill" gnus-category-kill t]
1365        ["Copy" gnus-category-copy t]
1366        ["Edit predicate" gnus-category-edit-predicate t]
1367        ["Edit score" gnus-category-edit-score t]
1368        ["Edit groups" gnus-category-edit-groups t]
1369        ["Exit" gnus-category-exit t]))
1370
1371     (gnus-run-hooks 'gnus-category-menu-hook)))
1372
1373 (defun gnus-category-mode ()
1374   "Major mode for listing and editing agent categories.
1375
1376 All normal editing commands are switched off.
1377 \\<gnus-category-mode-map>
1378 For more in-depth information on this mode, read the manual
1379 (`\\[gnus-info-find-node]').
1380
1381 The following commands are available:
1382
1383 \\{gnus-category-mode-map}"
1384   (interactive)
1385   (when (gnus-visual-p 'category-menu 'menu)
1386     (gnus-category-make-menu-bar))
1387   (kill-all-local-variables)
1388   (gnus-simplify-mode-line)
1389   (setq major-mode 'gnus-category-mode)
1390   (setq mode-name "Category")
1391   (gnus-set-default-directory)
1392   (setq mode-line-process nil)
1393   (use-local-map gnus-category-mode-map)
1394   (buffer-disable-undo)
1395   (setq truncate-lines t)
1396   (setq buffer-read-only t)
1397   (gnus-run-hooks 'gnus-category-mode-hook))
1398
1399 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1400
1401 (defun gnus-category-insert-line (category)
1402   (let* ((gnus-tmp-name (format "%s" (car category)))
1403          (gnus-tmp-groups (length (cadddr category))))
1404     (beginning-of-line)
1405     (gnus-add-text-properties
1406      (point)
1407      (prog1 (1+ (point))
1408        ;; Insert the text.
1409        (eval gnus-category-line-format-spec))
1410      (list 'gnus-category gnus-tmp-name))))
1411
1412 (defun gnus-enter-category-buffer ()
1413   "Go to the Category buffer."
1414   (interactive)
1415   (gnus-category-setup-buffer)
1416   (gnus-configure-windows 'category)
1417   (gnus-category-prepare))
1418
1419 (defun gnus-category-setup-buffer ()
1420   (unless (get-buffer gnus-category-buffer)
1421     (save-excursion
1422       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1423       (gnus-category-mode))))
1424
1425 (defun gnus-category-prepare ()
1426   (gnus-set-format 'category-mode)
1427   (gnus-set-format 'category t)
1428   (let ((alist gnus-category-alist)
1429         (buffer-read-only nil))
1430     (erase-buffer)
1431     (while alist
1432       (gnus-category-insert-line (pop alist)))
1433     (goto-char (point-min))
1434     (gnus-category-position-point)))
1435
1436 (defun gnus-category-name ()
1437   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1438       (error "No category on the current line")))
1439
1440 (defun gnus-category-read ()
1441   "Read the category alist."
1442   (setq gnus-category-alist
1443         (or (gnus-agent-read-file
1444              (nnheader-concat gnus-agent-directory "lib/categories"))
1445             (list (list 'default 'short nil nil)))))
1446
1447 (defun gnus-category-write ()
1448   "Write the category alist."
1449   (setq gnus-category-predicate-cache nil
1450         gnus-category-group-cache nil)
1451   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1452   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1453     (prin1 gnus-category-alist (current-buffer))))
1454
1455 (defun gnus-category-edit-predicate (category)
1456   "Edit the predicate for CATEGORY."
1457   (interactive (list (gnus-category-name)))
1458   (let ((info (assq category gnus-category-alist)))
1459     (gnus-edit-form
1460      (cadr info) (format "Editing the predicate for category %s" category)
1461      `(lambda (predicate)
1462         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1463         (gnus-category-write)
1464         (gnus-category-list)))))
1465
1466 (defun gnus-category-edit-score (category)
1467   "Edit the score expression for CATEGORY."
1468   (interactive (list (gnus-category-name)))
1469   (let ((info (assq category gnus-category-alist)))
1470     (gnus-edit-form
1471      (caddr info)
1472      (format "Editing the score expression for category %s" category)
1473      `(lambda (groups)
1474         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1475         (gnus-category-write)
1476         (gnus-category-list)))))
1477
1478 (defun gnus-category-edit-groups (category)
1479   "Edit the group list for CATEGORY."
1480   (interactive (list (gnus-category-name)))
1481   (let ((info (assq category gnus-category-alist)))
1482     (gnus-edit-form
1483      (cadddr info) (format "Editing the group list for category %s" category)
1484      `(lambda (groups)
1485         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1486         (gnus-category-write)
1487         (gnus-category-list)))))
1488
1489 (defun gnus-category-kill (category)
1490   "Kill the current category."
1491   (interactive (list (gnus-category-name)))
1492   (let ((info (assq category gnus-category-alist))
1493         (buffer-read-only nil))
1494     (gnus-delete-line)
1495     (setq gnus-category-alist (delq info gnus-category-alist))
1496     (gnus-category-write)))
1497
1498 (defun gnus-category-copy (category to)
1499   "Copy the current category."
1500   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1501   (let ((info (assq category gnus-category-alist)))
1502     (push (list to (gnus-copy-sequence (cadr info))
1503                 (gnus-copy-sequence (caddr info)) nil)
1504           gnus-category-alist)
1505     (gnus-category-write)
1506     (gnus-category-list)))
1507
1508 (defun gnus-category-add (category)
1509   "Create a new category."
1510   (interactive "SCategory name: ")
1511   (when (assq category gnus-category-alist)
1512     (error "Category %s already exists" category))
1513   (push (list category 'false nil nil)
1514         gnus-category-alist)
1515   (gnus-category-write)
1516   (gnus-category-list))
1517
1518 (defun gnus-category-list ()
1519   "List all categories."
1520   (interactive)
1521   (gnus-category-prepare))
1522
1523 (defun gnus-category-exit ()
1524   "Return to the group buffer."
1525   (interactive)
1526   (kill-buffer (current-buffer))
1527   (gnus-configure-windows 'group t))
1528
1529 ;; To avoid having 8-bit characters in the source file.
1530 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1531
1532 (defvar gnus-category-predicate-alist
1533   '((spam . gnus-agent-spam-p)
1534     (short . gnus-agent-short-p)
1535     (long . gnus-agent-long-p)
1536     (low . gnus-agent-low-scored-p)
1537     (high . gnus-agent-high-scored-p)
1538     (true . gnus-agent-true)
1539     (false . gnus-agent-false))
1540   "Mapping from short score predicate symbols to predicate functions.")
1541
1542 (defun gnus-agent-spam-p ()
1543   "Say whether an article is spam or not."
1544   (unless gnus-agent-spam-hashtb
1545     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1546   (if (not (equal (mail-header-references gnus-headers) ""))
1547       nil
1548     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1549       (prog1
1550           (gnus-gethash string gnus-agent-spam-hashtb)
1551         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1552
1553 (defun gnus-agent-short-p ()
1554   "Say whether an article is short or not."
1555   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1556
1557 (defun gnus-agent-long-p ()
1558   "Say whether an article is long or not."
1559   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1560
1561 (defun gnus-agent-low-scored-p ()
1562   "Say whether an article has a low score or not."
1563   (< gnus-score gnus-agent-low-score))
1564
1565 (defun gnus-agent-high-scored-p ()
1566   "Say whether an article has a high score or not."
1567   (> gnus-score gnus-agent-high-score))
1568
1569 (defun gnus-category-make-function (cat)
1570   "Make a function from category CAT."
1571   (let ((func (gnus-category-make-function-1 cat)))
1572     (if (and (= (length func) 1)
1573              (symbolp (car func)))
1574         (car func)
1575       (gnus-byte-compile `(lambda () ,func)))))
1576
1577 (defun gnus-agent-true ()
1578   "Return t."
1579   t)
1580
1581 (defun gnus-agent-false ()
1582   "Return nil."
1583   nil)
1584
1585 (defun gnus-category-make-function-1 (cat)
1586   "Make a function from category CAT."
1587   (cond
1588    ;; Functions are just returned as is.
1589    ((or (symbolp cat)
1590         (gnus-functionp cat))
1591     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1592            cat)))
1593    ;; More complex category.
1594    ((consp cat)
1595     `(,(cond
1596         ((memq (car cat) '(& and))
1597          'and)
1598         ((memq (car cat) '(| or))
1599          'or)
1600         ((memq (car cat) gnus-category-not)
1601          'not))
1602       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1603    (t
1604     (error "Unknown category type: %s" cat))))
1605
1606 (defun gnus-get-predicate (predicate)
1607   "Return the predicate for CATEGORY."
1608   (or (cdr (assoc predicate gnus-category-predicate-cache))
1609       (cdar (push (cons predicate
1610                         (gnus-category-make-function predicate))
1611                   gnus-category-predicate-cache))))
1612
1613 (defun gnus-group-category (group)
1614   "Return the category GROUP belongs to."
1615   (unless gnus-category-group-cache
1616     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1617     (let ((cs gnus-category-alist)
1618           groups cat)
1619       (while (setq cat (pop cs))
1620         (setq groups (cadddr cat))
1621         (while groups
1622           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1623   (or (gnus-gethash group gnus-category-group-cache)
1624       (assq 'default gnus-category-alist)))
1625
1626 (defun gnus-agent-expire ()
1627   "Expire all old articles."
1628   (interactive)
1629   (let ((methods gnus-agent-covered-methods)
1630         (day (if (numberp gnus-agent-expire-days)
1631                  (- (time-to-days (current-time)) gnus-agent-expire-days)
1632                nil))
1633         (current-day (time-to-days (current-time)))
1634         gnus-command-method sym group articles
1635         history overview file histories elem art nov-file low info
1636         unreads marked article orig lowest highest found days)
1637     (save-excursion
1638       (setq overview (gnus-get-buffer-create " *expire overview*"))
1639       (while (setq gnus-command-method (pop methods))
1640         (when (file-exists-p (gnus-agent-lib-file "active"))
1641           (with-temp-buffer
1642             (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1643             (gnus-active-to-gnus-format
1644              gnus-command-method
1645              (setq orig (gnus-make-hashtable
1646                          (count-lines (point-min) (point-max))))))
1647           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1648             (gnus-agent-open-history)
1649             (set-buffer
1650              (setq gnus-agent-current-history
1651                    (setq history (gnus-agent-history-buffer))))
1652             (goto-char (point-min))
1653             (when (> (buffer-size) 1)
1654               (goto-char (point-min))
1655               (while (not (eobp))
1656                 (skip-chars-forward "^\t")
1657                 (if (let ((fetch-date (read (current-buffer))))
1658                       (if (numberp fetch-date)
1659                           ;; We now have the arrival day, so we see
1660                           ;; whether it's old enough to be expired.
1661                           (if (numberp day)
1662                               (> fetch-date day)
1663                             (skip-chars-forward "\t")
1664                             (setq found nil
1665                                   days gnus-agent-expire-days)
1666                             (while (and (not found)
1667                                         days)
1668                               (when (looking-at (caar days))
1669                                 (setq found (cadar days)))
1670                               (pop days))
1671                             (> fetch-date (- current-day found)))
1672                         ;; History file is corrupted.
1673                         (gnus-message
1674                          5
1675                          (format "File %s is corrupted!"
1676                                  (gnus-agent-lib-file "history")))
1677                         (sit-for 1)
1678                         ;; Ignore it
1679                         t))
1680                     ;; New article; we don't expire it.
1681                     (forward-line 1)
1682                   ;; Old article.  Schedule it for possible nuking.
1683                   (while (not (eolp))
1684                     (setq sym (let ((obarray expiry-hashtb) s)
1685                                 (setq s (read (current-buffer)))
1686                                 (if (stringp s) (intern s) s)))
1687                     (if (boundp sym)
1688                         (set sym (cons (cons (read (current-buffer)) (point))
1689                                        (symbol-value sym)))
1690                       (set sym (list (cons (read (current-buffer)) (point)))))
1691                     (skip-chars-forward " "))
1692                   (forward-line 1)))
1693               ;; We now have all articles that can possibly be expired.
1694               (mapatoms
1695                (lambda (sym)
1696                  (setq group (symbol-name sym)
1697                        articles (sort (symbol-value sym) 'car-less-than-car)
1698                        low (car (gnus-active group))
1699                        info (gnus-get-info group)
1700                        unreads (ignore-errors
1701                                  (gnus-list-of-unread-articles group))
1702                        marked (nconc
1703                                (gnus-uncompress-range
1704                                 (cdr (assq 'tick (gnus-info-marks info))))
1705                                (gnus-uncompress-range
1706                                 (cdr (assq 'dormant
1707                                            (gnus-info-marks info)))))
1708                        nov-file (gnus-agent-article-name ".overview" group)
1709                        lowest nil
1710                        highest nil)
1711                  (gnus-agent-load-alist group)
1712                  (gnus-message 5 "Expiring articles in %s" group)
1713                  (set-buffer overview)
1714                  (erase-buffer)
1715                  (when (file-exists-p nov-file)
1716                    (nnheader-insert-file-contents nov-file))
1717                  (goto-char (point-min))
1718                  (setq article 0)
1719                  (while (setq elem (pop articles))
1720                    (setq article (car elem))
1721                    (when (or (null low)
1722                              (< article low)
1723                              gnus-agent-expire-all
1724                              (and (not (memq article unreads))
1725                                   (not (memq article marked))))
1726                      ;; Find and nuke the NOV line.
1727                      (while (and (not (eobp))
1728                                  (or (not (numberp
1729                                            (setq art (read (current-buffer)))))
1730                                      (< art article)))
1731                        (if (and (numberp art)
1732                                 (file-exists-p
1733                                  (gnus-agent-article-name
1734                                   (number-to-string art) group)))
1735                            (progn
1736                              (unless lowest
1737                                (setq lowest art))
1738                              (setq highest art)
1739                              (forward-line 1))
1740                          ;; Remove old NOV lines that have no articles.
1741                          (gnus-delete-line)))
1742                      (if (or (eobp)
1743                              (/= art article))
1744                          (beginning-of-line)
1745                        (gnus-delete-line))
1746                      ;; Nuke the article.
1747                      (when (file-exists-p
1748                             (setq file (gnus-agent-article-name
1749                                         (number-to-string article)
1750                                         group)))
1751                        (delete-file file))
1752                      ;; Schedule the history line for nuking.
1753                      (push (cdr elem) histories)))
1754                  (gnus-make-directory (file-name-directory nov-file))
1755                  (let ((coding-system-for-write
1756                         gnus-agent-file-coding-system))
1757                    (write-region (point-min) (point-max) nov-file nil 'silent))
1758                  ;; Delete the unwanted entries in the alist.
1759                  (setq gnus-agent-article-alist
1760                        (sort gnus-agent-article-alist 'car-less-than-car))
1761                  (let* ((alist gnus-agent-article-alist)
1762                         (prev (cons nil alist))
1763                         (first prev)
1764                         expired)
1765                    (while (and alist
1766                                (<= (caar alist) article))
1767                      (if (or (not (cdar alist))
1768                              (not (file-exists-p
1769                                    (gnus-agent-article-name
1770                                     (number-to-string
1771                                      (caar alist))
1772                                     group))))
1773                          (progn
1774                            (push (caar alist) expired)
1775                            (setcdr prev (setq alist (cdr alist))))
1776                        (setq prev alist
1777                              alist (cdr alist))))
1778                    (setq gnus-agent-article-alist (cdr first))
1779                    (gnus-agent-save-alist group)
1780                    ;; Mark all articles up to the first article
1781                    ;; in `gnus-article-alist' as read.
1782                    (when (and info (caar gnus-agent-article-alist))
1783                      (setcar (nthcdr 2 info)
1784                              (gnus-range-add
1785                               (nth 2 info)
1786                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1787                    ;; Maybe everything has been expired from
1788                    ;; `gnus-article-alist' and so the above marking as
1789                    ;; read could not be conducted, or there are
1790                    ;; expired article within the range of the alist.
1791                    (when (and info
1792                               expired
1793                               (or (not (caar gnus-agent-article-alist))
1794                                   (> (car expired)
1795                                      (caar gnus-agent-article-alist))))
1796                      (setcar (nthcdr 2 info)
1797                              (gnus-add-to-range
1798                               (nth 2 info)
1799                               (nreverse expired))))
1800                    (gnus-dribble-enter
1801                     (concat "(gnus-group-set-info '"
1802                             (gnus-prin1-to-string info)
1803                             ")")))
1804                  (when lowest
1805                    (if (gnus-gethash group orig)
1806                        (setcar (gnus-gethash group orig) lowest)
1807                      (gnus-sethash group (cons lowest highest) orig))))
1808                expiry-hashtb)
1809               (set-buffer history)
1810               (setq histories (nreverse (sort histories '<)))
1811               (while histories
1812                 (goto-char (pop histories))
1813                 (gnus-delete-line))
1814               (gnus-agent-save-history)
1815               (gnus-agent-close-history)
1816               (gnus-write-active-file
1817                (gnus-agent-lib-file "active") orig))
1818             (gnus-message 4 "Expiry...done")))))))
1819
1820 ;;;###autoload
1821 (defun gnus-agent-batch ()
1822   (interactive)
1823   (let ((init-file-user "")
1824         (gnus-always-read-dribble-file t))
1825     (gnus))
1826   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1827     (gnus-group-send-queue)
1828     (gnus-agent-fetch-session)))
1829
1830 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
1831   (save-excursion
1832     (gnus-agent-create-buffer)
1833     (let ((gnus-decode-encoded-word-function 'identity)
1834           (file (gnus-agent-article-name ".overview" group))
1835           cached-articles uncached-articles)
1836       (gnus-make-directory (nnheader-translate-file-chars
1837                             (file-name-directory file) t))
1838       (when (file-exists-p file)
1839         (with-current-buffer gnus-agent-overview-buffer
1840           (erase-buffer)
1841           (let ((nnheader-file-coding-system
1842                  gnus-agent-file-coding-system))
1843             (nnheader-insert-nov-file file (car articles)))
1844           (nnheader-find-nov-line (car articles))
1845           (while (not (eobp))
1846             (when (looking-at "[0-9]")
1847               (push (read (current-buffer)) cached-articles))
1848             (forward-line 1))
1849           (setq cached-articles (nreverse cached-articles))))
1850       (if (setq uncached-articles 
1851                 (gnus-set-difference articles cached-articles))
1852           (progn
1853             (set-buffer nntp-server-buffer)
1854             (erase-buffer)
1855             (let (gnus-agent-cache)
1856               (unless (eq 'nov 
1857                           (gnus-retrieve-headers 
1858                            uncached-articles group fetch-old))
1859                 (nnvirtual-convert-headers)))
1860             (set-buffer gnus-agent-overview-buffer)
1861             (erase-buffer)
1862             (set-buffer nntp-server-buffer)
1863             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1864             (when (and uncached-articles (file-exists-p file))
1865               (gnus-agent-braid-nov group uncached-articles file))
1866             (set-buffer nntp-server-buffer)
1867             (let ((coding-system-for-write
1868                    gnus-agent-file-coding-system))
1869               (write-region (point-min) (point-max) file nil 'silent))
1870             (gnus-agent-load-alist group)
1871             (gnus-agent-save-alist group uncached-articles nil)
1872             (gnus-agent-open-history)
1873             (setq gnus-agent-current-history (gnus-agent-history-buffer))
1874             (gnus-agent-enter-history
1875              "last-header-fetched-for-session"
1876              (list (cons group (nth (- (length  articles) 1) articles)))
1877              (time-to-days (current-time)))
1878             (gnus-agent-save-history))
1879         (set-buffer nntp-server-buffer)
1880         (erase-buffer)
1881         (insert-buffer-substring gnus-agent-overview-buffer)))
1882     (if (and fetch-old
1883              (not (numberp fetch-old)))
1884         t                               ; Don't remove anything.
1885       (nnheader-nov-delete-outside-range
1886        (if fetch-old (max 1 (- (car articles) fetch-old))
1887          (car articles))
1888        (car (last articles)))
1889       t)
1890     'nov))
1891
1892 (defun gnus-agent-request-article (article group)
1893   "Retrieve ARTICLE in GROUP from the agent cache."
1894   (let* ((gnus-command-method (gnus-find-method-for-group group))
1895          (file (concat
1896                   (gnus-agent-directory)
1897                   (gnus-agent-group-path group) "/"
1898                   (number-to-string article)))
1899          (buffer-read-only nil))
1900     (when (and (file-exists-p file)
1901                (> (nth 7 (file-attributes file)) 0))
1902       (erase-buffer)
1903       (gnus-kill-all-overlays)
1904       (let ((coding-system-for-read gnus-cache-coding-system))
1905         (insert-file-contents file))
1906       t)))
1907
1908 (defun gnus-agent-regenerate-group (group &optional clean)
1909   "Regenerate GROUP."
1910   (let ((dir (concat (gnus-agent-directory)
1911                      (gnus-agent-group-path group) "/"))
1912         (file (gnus-agent-article-name ".overview" group))
1913         n point arts alist header new-alist changed)
1914     (when (file-exists-p dir)
1915       (setq arts
1916             (sort (mapcar (lambda (name) (string-to-int name))
1917                           (directory-files dir nil "^[0-9]+$" t))
1918                   '<)))
1919     (gnus-make-directory (nnheader-translate-file-chars
1920                           (file-name-directory file) t))
1921     (mm-with-unibyte-buffer
1922       (if (file-exists-p file)
1923           (let ((nnheader-file-coding-system
1924                  gnus-agent-file-coding-system))
1925             (nnheader-insert-file-contents file)))
1926       (goto-char (point-min)) 
1927       (while (not (eobp))
1928         (while (not (or (eobp) (looking-at "[0-9]")))
1929           (setq point (point))
1930           (forward-line 1)
1931           (delete-region point (point)))
1932         (unless (eobp)
1933           (setq n (read (current-buffer)))
1934           (when (and arts (> n (car arts)))
1935             (beginning-of-line)
1936             (while (and arts (> n (car arts)))
1937               (message "Regenerating NOV %s %d..." group (car arts))
1938               (mm-with-unibyte-buffer
1939                 (nnheader-insert-file-contents 
1940                  (concat dir (number-to-string (car arts))))
1941                 (goto-char (point-min))
1942                 (if (search-forward "\n\n" nil t)
1943                     (delete-region (point) (point-max))
1944                   (goto-char (point-max)))
1945                 (setq header (nnheader-parse-head t)))
1946               (mail-header-set-number header (car arts))
1947               (nnheader-insert-nov header)
1948               (setq changed t)
1949               (push (cons (car arts) t) alist)
1950               (pop arts)))
1951           (if (and arts (= n (car arts)))
1952               (progn
1953                 (push (cons n t) alist)
1954                 (pop arts))
1955             (push (cons n nil) alist))
1956           (forward-line 1)))
1957       (if changed
1958           (let ((coding-system-for-write gnus-agent-file-coding-system))
1959             (write-region (point-min) (point-max) file nil 'silent))))
1960     (setq gnus-agent-article-alist nil)
1961     (unless clean
1962       (gnus-agent-load-alist group))
1963     (setq alist (sort alist 'car-less-than-car))
1964     (setq gnus-agent-article-alist (sort gnus-agent-article-alist 
1965                                          'car-less-than-car))
1966     (while (and alist gnus-agent-article-alist)
1967       (cond 
1968        ((< (caar alist) (caar gnus-agent-article-alist))
1969         (push (pop alist) new-alist))
1970        ((> (caar alist) (caar gnus-agent-article-alist))
1971         (push (list (car (pop gnus-agent-article-alist))) new-alist))
1972        (t 
1973         (pop gnus-agent-article-alist)
1974         (while (and gnus-agent-article-alist
1975                     (= (caar alist) (caar gnus-agent-article-alist)))
1976           (pop gnus-agent-article-alist))
1977         (push (pop alist) new-alist))))
1978     (while alist
1979       (push (pop alist) new-alist))
1980     (while gnus-agent-article-alist
1981       (push (list (car (pop gnus-agent-article-alist))) new-alist))
1982     (setq gnus-agent-article-alist (nreverse new-alist))
1983     (gnus-agent-save-alist group)))
1984
1985 (defun gnus-agent-regenerate-history (group article)
1986   (let ((file (concat (gnus-agent-directory)
1987                       (gnus-agent-group-path group) "/"
1988                       (number-to-string article))) id)
1989     (mm-with-unibyte-buffer
1990       (nnheader-insert-file-contents file)
1991       (message-narrow-to-head)
1992       (goto-char (point-min))
1993       (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1994           (setq id "No-Message-ID-in-article")
1995         (setq id (buffer-substring (match-beginning 1) (match-end 1))))
1996       (gnus-agent-enter-history 
1997        id (list (cons group article)) 
1998        (time-to-days (nth 5 (file-attributes file)))))))
1999
2000 ;;;###autoload
2001 (defun gnus-agent-regenerate (&optional clean)
2002   "Regenerate all agent covered files.
2003 If CLEAN, don't read existing active and agentview files."
2004   (interactive "P")
2005   (message "Regenerating Gnus agent files...")
2006   (dolist (gnus-command-method gnus-agent-covered-methods)
2007     (let ((active-file (gnus-agent-lib-file "active"))
2008           history-hashtb active-hashtb active-changed 
2009           history-changed point)
2010       (gnus-make-directory (file-name-directory active-file))
2011       (if clean
2012           (setq active-hashtb (gnus-make-hashtable 1000))
2013         (mm-with-unibyte-buffer
2014           (if (file-exists-p active-file)
2015               (let ((nnheader-file-coding-system
2016                      gnus-agent-file-coding-system))
2017                 (nnheader-insert-file-contents active-file))
2018             (setq active-changed t))
2019           (gnus-active-to-gnus-format
2020            nil (setq active-hashtb
2021                      (gnus-make-hashtable
2022                       (count-lines (point-min) (point-max)))))))
2023       (gnus-agent-open-history)
2024       (setq history-hashtb (gnus-make-hashtable 1000))
2025       (with-current-buffer
2026           (setq gnus-agent-current-history (gnus-agent-history-buffer))
2027         (goto-char (point-min))
2028         (forward-line 1)
2029         (while (not (eobp))
2030           (if (looking-at 
2031                "\\([^\t\n]+\\)\t[0-9]+\t\\([^ \n]+\\) \\([0-9]+\\)")
2032               (progn
2033                 (unless (string= (match-string 1) 
2034                                  "last-header-fetched-for-session")
2035                   (gnus-sethash (match-string 2) 
2036                                 (cons (string-to-number (match-string 3))
2037                                       (gnus-gethash-safe (match-string 2)
2038                                                          history-hashtb))
2039                                 history-hashtb))
2040                 (forward-line 1))
2041             (setq point (point))
2042             (forward-line 1)
2043             (delete-region point (point))
2044             (setq history-changed t))))
2045       (dolist (group (gnus-groups-from-server gnus-command-method))
2046         (gnus-agent-regenerate-group group clean)
2047         (let ((min (or (caar gnus-agent-article-alist) 1))
2048               (max (or (caar (last gnus-agent-article-alist)) 0))
2049               (active (gnus-gethash-safe (gnus-group-real-name group)
2050                                          active-hashtb)))
2051           (if (not active)
2052               (progn
2053                 (setq active (cons min max)
2054                       active-changed t)
2055                 (gnus-sethash group active active-hashtb))
2056             (when (> (car active) min)
2057               (setcar active min)
2058               (setq active-changed t))
2059             (when (< (cdr active) max)
2060               (setcdr active max)
2061               (setq active-changed t))))
2062         (let ((arts (sort (gnus-gethash-safe group history-hashtb) '<))
2063               n)
2064           (gnus-sethash group arts history-hashtb)
2065           (while (and arts gnus-agent-article-alist)
2066             (cond 
2067              ((> (car arts) (caar gnus-agent-article-alist))
2068               (when (cdar gnus-agent-article-alist)
2069                 (gnus-agent-regenerate-history 
2070                  group (caar gnus-agent-article-alist))
2071                 (setq history-changed t))
2072               (setq n (car (pop gnus-agent-article-alist)))
2073               (while (and gnus-agent-article-alist 
2074                           (= n (caar gnus-agent-article-alist)))
2075                 (pop gnus-agent-article-alist)))
2076              ((< (car arts) (caar gnus-agent-article-alist))
2077               (setq n (pop arts))
2078               (while (and arts (= n (car arts)))
2079                 (pop arts)))
2080              (t
2081               (setq n (car (pop gnus-agent-article-alist)))
2082               (while (and gnus-agent-article-alist 
2083                           (= n (caar gnus-agent-article-alist)))
2084                 (pop gnus-agent-article-alist))
2085               (setq n (pop arts))
2086               (while (and arts (= n (car arts)))
2087                 (pop arts)))))
2088           (while gnus-agent-article-alist
2089             (when (cdar gnus-agent-article-alist)
2090               (gnus-agent-regenerate-history 
2091                group (caar gnus-agent-article-alist))
2092               (setq history-changed t))
2093             (pop gnus-agent-article-alist))))
2094       (when history-changed
2095         (message "Regenerate the history file of %s:%s" 
2096                  (car gnus-command-method)
2097                  (cadr gnus-command-method))
2098         (gnus-agent-save-history))
2099       (gnus-agent-close-history)
2100       (when active-changed
2101         (message "Regenerate %s" active-file) 
2102         (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2103           (gnus-write-active-file active-file active-hashtb)))))
2104   (message "Regenerating Gnus agent files...done"))
2105
2106 (defun gnus-agent-go-online (&optional force)
2107   "Switch servers into online status."
2108   (interactive (list t))
2109   (dolist (server gnus-opened-servers)
2110     (when (eq (nth 1 server) 'offline)
2111       (if (if (eq force 'ask) 
2112               (gnus-y-or-n-p 
2113                (format "Switch %s:%s into online status? "
2114                        (caar server) (cadar server)))
2115             force)
2116           (setcar (nthcdr 1 server) 'close)))))
2117
2118 (defun gnus-agent-toggle-group-plugged (group)
2119   "Toggle the status of the server of the current group."
2120   (interactive (list (gnus-group-group-name)))
2121   (let* ((method (gnus-find-method-for-group group))
2122          (status (cadr (assoc method gnus-opened-servers))))
2123     (if (eq status 'offline)
2124         (gnus-server-set-status method 'closed)
2125       (gnus-close-server method)
2126       (gnus-server-set-status method 'offline))
2127     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2128              (if (eq status 'offline) 'offline 'online)
2129              (if (eq status 'offline) 'online 'offline))))
2130
2131 (provide 'gnus-agent)
2132
2133 ;;; gnus-agent.el ends here