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