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