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