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