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