* nnheader.el (mail-narrow-to-head): Copy from ietf-drums.el;
[elisp/gnus.git-] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Semi-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 ;;      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-queue
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 queue" gnus-group-send-queue 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                (progn
758                  (if (and (integerp (car (symbol-value sym)))
759                           (> (car elem) (car (symbol-value sym))))
760                      (setcar elem (car (symbol-value sym))))
761                  (if (integerp (cdr (symbol-value sym)))
762                      (setcdr elem (cdr (symbol-value sym)))))
763              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
764        new))
765     (gnus-make-directory (file-name-directory file))
766     ;; The hashtable contains real names of groups,  no more prefix
767     ;; removing, so set `full' to `t'.
768     (gnus-write-active-file file orig t)))
769
770 (defun gnus-agent-save-groups (method)
771   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
772
773 (defun gnus-agent-save-group-info (method group active)
774   (when (gnus-agent-method-p method)
775     (let* ((gnus-command-method method)
776            (coding-system-for-write nnheader-file-coding-system)
777            (output-coding-system nnheader-file-coding-system)
778            (file-name-coding-system nnmail-pathname-coding-system)
779            (pathname-coding-system nnmail-pathname-coding-system)
780            (file (gnus-agent-lib-file "active"))
781            oactive-min)
782       (gnus-make-directory (file-name-directory file))
783       (with-temp-file file
784         (when (file-exists-p file)
785           (nnheader-insert-file-contents file))
786         (goto-char (point-min))
787         (when (re-search-forward
788                (concat "^" (regexp-quote group) " ") nil t)
789           (save-excursion
790             (read (current-buffer))                      ;; max
791             (setq oactive-min (read (current-buffer))))  ;; min
792           (gnus-delete-line))
793         (insert (format "%S %d %d y\n" (intern group)
794                         (cdr active)
795                         (or oactive-min (car active))))
796         (goto-char (point-max))
797         (while (search-backward "\\." nil t)
798           (delete-char 1))))))
799
800 (defun gnus-agent-group-path (group)
801   "Translate GROUP into a path."
802   (if nnmail-use-long-file-names
803       (gnus-group-real-name group)
804     (nnheader-translate-file-chars
805      (nnheader-replace-chars-in-string
806       (nnheader-replace-duplicate-chars-in-string
807        (nnheader-replace-chars-in-string
808         (gnus-group-real-name group)
809         ?/ ?_)
810        ?. ?_)
811       ?. ?/))))
812
813 \f
814
815 (defun gnus-agent-method-p (method)
816   "Say whether METHOD is covered by the agent."
817   (member method gnus-agent-covered-methods))
818
819 (defun gnus-agent-get-function (method)
820   (if (and (not gnus-plugged)
821            (gnus-agent-method-p method))
822       (progn
823         (require 'nnagent)
824         'nnagent)
825     (car method)))
826
827 ;;; History functions
828
829 (defun gnus-agent-history-buffer ()
830   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
831
832 (defun gnus-agent-open-history ()
833   (save-excursion
834     (push (cons (gnus-agent-method)
835                 (set-buffer (gnus-get-buffer-create
836                              (format " *Gnus agent %s history*"
837                                      (gnus-agent-method)))))
838           gnus-agent-history-buffers)
839     (erase-buffer)
840     (insert "\n")
841     (let ((file (gnus-agent-lib-file "history")))
842       (when (file-exists-p file)
843         (nnheader-insert-file-contents file))
844       (set (make-local-variable 'gnus-agent-file-name) file))))
845
846 (defun gnus-agent-save-history ()
847   (save-excursion
848     (set-buffer gnus-agent-current-history)
849     (gnus-make-directory (file-name-directory gnus-agent-file-name))
850     (write-region-as-coding-system
851      gnus-agent-file-coding-system
852      (1+ (point-min)) (point-max) gnus-agent-file-name nil 'silent)))
853
854 (defun gnus-agent-close-history ()
855   (when (gnus-buffer-live-p gnus-agent-current-history)
856     (kill-buffer gnus-agent-current-history)
857     (setq gnus-agent-history-buffers
858           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
859                 gnus-agent-history-buffers))))
860
861 (defun gnus-agent-enter-history (id group-arts date)
862   (save-excursion
863     (set-buffer gnus-agent-current-history)
864     (goto-char (point-max))
865     (let ((p (point)))
866       (insert id "\t" (number-to-string date) "\t")
867       (while group-arts
868         (insert (format "%S" (intern (caar group-arts)))
869                 " " (number-to-string (cdr (pop group-arts)))
870                 " "))
871       (insert "\n")
872       (while (search-backward "\\." p t)
873         (delete-char 1)))))
874
875 (defun gnus-agent-article-in-history-p (id)
876   (save-excursion
877     (set-buffer (gnus-agent-history-buffer))
878     (goto-char (point-min))
879     (search-forward (concat "\n" id "\t") nil t)))
880
881 (defun gnus-agent-history-path (id)
882   (save-excursion
883     (set-buffer (gnus-agent-history-buffer))
884     (goto-char (point-min))
885     (when (search-forward (concat "\n" id "\t") nil t)
886       (let ((method (gnus-agent-method)))
887         (let (paths group)
888           (while (not (numberp (setq group (read (current-buffer)))))
889             (push (concat method "/" group) paths))
890           (nreverse paths))))))
891
892 ;;;
893 ;;; Fetching
894 ;;;
895
896 (defun gnus-agent-fetch-articles (group articles)
897   "Fetch ARTICLES from GROUP and put them into the Agent."
898   (when articles
899     ;; Prune off articles that we have already fetched.
900     (while (and articles
901                 (cdr (assq (car articles) gnus-agent-article-alist)))
902       (pop articles))
903     (let ((arts articles))
904       (while (cdr arts)
905         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
906             (setcdr arts (cddr arts))
907           (setq arts (cdr arts)))))
908     (when articles
909       (let ((dir (concat
910                   (gnus-agent-directory)
911                   (gnus-agent-group-path group) "/"))
912             (date (time-to-days (current-time)))
913             (case-fold-search t)
914             pos crosses id elem)
915         (gnus-make-directory dir)
916         (gnus-message 7 "Fetching articles for %s..." group)
917         ;; Fetch the articles from the backend.
918         (if (gnus-check-backend-function 'retrieve-articles group)
919             (setq pos (gnus-retrieve-articles articles group))
920           (with-temp-buffer
921             (let (article)
922               (while (setq article (pop articles))
923                 (when (or
924                        (gnus-backlog-request-article group article
925                                                      nntp-server-buffer)
926                        (gnus-request-article article group))
927                   (goto-char (point-max))
928                   (push (cons article (point)) pos)
929                   (insert-buffer-substring nntp-server-buffer)))
930               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
931               (setq pos (nreverse pos)))))
932         ;; Then save these articles into the Agent.
933         (save-excursion
934           (set-buffer nntp-server-buffer)
935           (while pos
936             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
937             (goto-char (point-min))
938             (when (search-forward "\n\n" nil t)
939               (when (search-backward "\nXrefs: " nil t)
940                 ;; Handle crossposting.
941                 (skip-chars-forward "^ ")
942                 (skip-chars-forward " ")
943                 (setq crosses nil)
944                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
945                   (push (cons (buffer-substring (match-beginning 1)
946                                                 (match-end 1))
947                               (buffer-substring (match-beginning 2)
948                                                 (match-end 2)))
949                         crosses)
950                   (goto-char (match-end 0)))
951                 (gnus-agent-crosspost crosses (caar pos))))
952             (goto-char (point-min))
953             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
954                 (setq id "No-Message-ID-in-article")
955               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
956             (write-region-as-coding-system
957              gnus-agent-file-coding-system
958              (point-min) (point-max)
959              (concat dir (number-to-string (caar pos))) nil 'silent)
960             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
961               (setcdr elem t))
962             (gnus-agent-enter-history
963              id (or crosses (list (cons group (caar pos)))) date)
964             (widen)
965             (pop pos)))
966         (gnus-agent-save-alist group)))))
967
968 (defun gnus-agent-crosspost (crosses article)
969   (let (gnus-agent-article-alist group alist beg end)
970     (save-excursion
971       (set-buffer gnus-agent-overview-buffer)
972       (when (nnheader-find-nov-line article)
973         (forward-word 1)
974         (setq beg (point))
975         (setq end (progn (forward-line 1) (point)))))
976     (while crosses
977       (setq group (caar crosses))
978       (unless (setq alist (assoc group gnus-agent-group-alist))
979         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
980               gnus-agent-group-alist))
981       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
982       (save-excursion
983         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
984                                                     group)))
985         (when (= (point-max) (point-min))
986           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
987           (ignore-errors
988             (nnheader-insert-file-contents
989              (gnus-agent-article-name ".overview" group))))
990         (nnheader-find-nov-line (string-to-number (cdar crosses)))
991         (insert (string-to-number (cdar crosses)))
992         (insert-buffer-substring gnus-agent-overview-buffer beg end))
993       (pop crosses))))
994
995 (defun gnus-agent-flush-cache ()
996   (save-excursion
997     (while gnus-agent-buffer-alist
998       (set-buffer (cdar gnus-agent-buffer-alist))
999       (write-region-as-coding-system
1000        gnus-agent-file-coding-system
1001        (point-min) (point-max)
1002        (gnus-agent-article-name ".overview"
1003                                 (caar gnus-agent-buffer-alist))
1004        nil 'silent)
1005       (pop gnus-agent-buffer-alist))
1006     (while gnus-agent-group-alist
1007       (with-temp-file (caar gnus-agent-group-alist)
1008         (princ (cdar gnus-agent-group-alist))
1009         (insert "\n"))
1010       (pop gnus-agent-group-alist))))
1011
1012 (defun gnus-agent-fetch-headers (group &optional force)
1013   (let* ((articles (gnus-list-of-unread-articles group))
1014          (len (length articles))
1015          (gnus-decode-encoded-word-function 'identity)
1016          (file (gnus-agent-article-name ".overview" group))
1017          i)
1018     ;; Check the number of articles is not too large.
1019     (when (and (integerp gnus-agent-large-newsgroup)
1020                (< 0 gnus-agent-large-newsgroup))
1021       (and (< 0 (setq i (- len gnus-agent-large-newsgroup)))
1022            (setq articles (nthcdr i articles))))
1023     ;; add article with marks to list of article headers we want to fetch.
1024     (dolist (arts (gnus-info-marks (gnus-get-info group)))
1025       (setq articles (gnus-range-add articles (cdr arts))))
1026     (setq articles (sort (gnus-uncompress-sequence articles) '<))
1027     ;; Remove known articles.
1028     (when (gnus-agent-load-alist group)
1029       (setq articles (gnus-sorted-intersection
1030                       articles
1031                       (gnus-uncompress-range
1032                        (cons (1+ (caar (last gnus-agent-article-alist)))
1033                              (cdr (gnus-active group)))))))
1034     ;; Fetch them.
1035     (gnus-make-directory (nnheader-translate-file-chars
1036                           (file-name-directory file) t))
1037     (when articles
1038       (gnus-message 7 "Fetching headers for %s..." group)
1039       (save-excursion
1040         (set-buffer nntp-server-buffer)
1041         (unless (eq 'nov (gnus-retrieve-headers articles group))
1042           (nnvirtual-convert-headers))
1043         ;; Save these headers for later processing.
1044         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1045         (when (file-exists-p file)
1046           (gnus-agent-braid-nov group articles file))
1047         (write-region-as-coding-system
1048          gnus-agent-file-coding-system
1049          (point-min) (point-max) file nil 'silent)
1050         (gnus-agent-save-alist group articles nil)
1051         (gnus-agent-enter-history
1052          "last-header-fetched-for-session"
1053          (list (cons group (nth (- (length  articles) 1) articles)))
1054          (time-to-days (current-time)))
1055         articles))))
1056
1057 (defsubst gnus-agent-copy-nov-line (article)
1058   (let (b e)
1059     (set-buffer gnus-agent-overview-buffer)
1060     (setq b (point))
1061     (if (eq article (read (current-buffer)))
1062         (setq e (progn (forward-line 1) (point)))
1063       (progn
1064         (beginning-of-line)
1065         (setq e b)))
1066     (set-buffer nntp-server-buffer)
1067     (insert-buffer-substring gnus-agent-overview-buffer b e)))
1068
1069 (defun gnus-agent-braid-nov (group articles file)
1070   (set-buffer gnus-agent-overview-buffer)
1071   (goto-char (point-min))
1072   (set-buffer nntp-server-buffer)
1073   (erase-buffer)
1074   (nnheader-insert-file-contents file)
1075   (goto-char (point-max))
1076   (if (or (= (point-min) (point-max))
1077           (progn
1078             (forward-line -1)
1079             (< (read (current-buffer)) (car articles))))
1080       ;; We have only headers that are after the older headers,
1081       ;; so we just append them.
1082       (progn
1083         (goto-char (point-max))
1084         (insert-buffer-substring gnus-agent-overview-buffer))
1085     ;; We do it the hard way.
1086     (nnheader-find-nov-line (car articles))
1087     (gnus-agent-copy-nov-line (car articles))
1088     (pop articles)
1089     (while (and articles
1090                 (not (eobp)))
1091       (while (and (not (eobp))
1092                   (< (read (current-buffer)) (car articles)))
1093         (forward-line 1))
1094       (beginning-of-line)
1095       (unless (eobp)
1096         (gnus-agent-copy-nov-line (car articles))
1097         (setq articles (cdr articles))))
1098     (when articles
1099       (let (b e)
1100         (set-buffer gnus-agent-overview-buffer)
1101         (setq b (point)
1102               e (point-max))
1103         (set-buffer nntp-server-buffer)
1104         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
1105
1106 (defun gnus-agent-load-alist (group &optional dir)
1107   "Load the article-state alist for GROUP."
1108   (setq gnus-agent-article-alist
1109         (gnus-agent-read-file
1110          (if dir
1111              (expand-file-name ".agentview" dir)
1112            (gnus-agent-article-name ".agentview" group)))))
1113
1114 (defun gnus-agent-save-alist (group &optional articles state dir)
1115   "Save the article-state alist for GROUP."
1116   (let ((file-name-coding-system nnmail-pathname-coding-system)
1117         (pathname-coding-system nnmail-pathname-coding-system)
1118         print-level print-length)
1119     (with-temp-file (if dir
1120                         (expand-file-name ".agentview" dir)
1121                       (gnus-agent-article-name ".agentview" group))
1122       (princ (setq gnus-agent-article-alist
1123                    (nconc gnus-agent-article-alist
1124                           (mapcar (lambda (article) (cons article state))
1125                                   articles)))
1126              (current-buffer))
1127       (insert "\n"))))
1128
1129 (defun gnus-agent-article-name (article group)
1130   (expand-file-name (if (stringp article) article (string-to-number article))
1131                     (file-name-as-directory
1132                      (expand-file-name (gnus-agent-group-path group)
1133                                        (gnus-agent-directory)))))
1134
1135 ;;;###autoload
1136 (defun gnus-agent-batch-fetch ()
1137   "Start Gnus and fetch session."
1138   (interactive)
1139   (gnus)
1140   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1141     (gnus-agent-fetch-session))
1142   (gnus-group-exit))
1143
1144 (defun gnus-agent-fetch-session ()
1145   "Fetch all articles and headers that are eligible for fetching."
1146   (interactive)
1147   (unless gnus-agent-covered-methods
1148     (error "No servers are covered by the Gnus agent"))
1149   (unless gnus-plugged
1150     (error "Can't fetch articles while Gnus is unplugged"))
1151   (let ((methods gnus-agent-covered-methods)
1152         groups group gnus-command-method)
1153     (save-excursion
1154       (while methods
1155         (condition-case err
1156             (progn
1157               (setq gnus-command-method (car methods))
1158               (when (or (gnus-server-opened gnus-command-method)
1159                         (gnus-open-server gnus-command-method))
1160                 (setq groups (gnus-groups-from-server (car methods)))
1161                 (gnus-agent-with-fetch
1162                   (while (setq group (pop groups))
1163                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1164                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1165           (error
1166            (unless (funcall gnus-agent-confirmation-function
1167                             (format "Error (%s).  Continue? " err))
1168              (error "Cannot fetch articles into the Gnus agent")))
1169           (quit
1170            (unless (funcall gnus-agent-confirmation-function
1171                             (format "Quit fetching session (%s).  Continue? "
1172                                     err))
1173              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1174         (pop methods))
1175       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1176
1177 (defun gnus-agent-fetch-group-1 (group method)
1178   "Fetch GROUP."
1179   (let ((gnus-command-method method)
1180         (gnus-newsgroup-name group)
1181         gnus-newsgroup-dependencies gnus-newsgroup-headers
1182         gnus-newsgroup-scored gnus-headers gnus-score
1183         gnus-use-cache articles arts
1184         category predicate info marks score-param
1185         (gnus-summary-expunge-below gnus-summary-expunge-below)
1186         (gnus-summary-mark-below gnus-summary-mark-below)
1187         (gnus-orphan-score gnus-orphan-score)
1188         ;; Maybe some other gnus-summary local variables should also
1189         ;; be put here.
1190         )
1191     (unless (gnus-check-group group)
1192       (error "Can't open server for %s" group))
1193     ;; Fetch headers.
1194     (when (and (or (gnus-active group)
1195                    (gnus-activate-group group))
1196                (setq articles (gnus-agent-fetch-headers group))
1197                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1198                  ;; Parse them and see which articles we want to fetch.
1199                  (setq gnus-newsgroup-dependencies
1200                        (make-vector (length articles) 0))
1201                  (setq gnus-newsgroup-headers
1202                        (gnus-get-newsgroup-headers-xover articles nil nil
1203                                                          group))
1204                  ;; `gnus-agent-overview-buffer' may be killed for
1205                  ;; timeout reason.  If so, recreate it.
1206                  (gnus-agent-create-buffer)))
1207       (setq category (gnus-group-category group))
1208       (setq predicate
1209             (gnus-get-predicate
1210              (or (gnus-group-find-parameter group 'agent-predicate t)
1211                  (cadr category))))
1212       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1213           ;; Simple implementation
1214           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1215         (setq arts nil)
1216         (setq score-param
1217               (or (gnus-group-get-parameter group 'agent-score t)
1218                   (caddr category)))
1219         ;; Translate score-param into real one
1220         (cond
1221          ((not score-param))
1222          ((eq score-param 'file)
1223           (setq score-param (gnus-all-score-files group)))
1224          ((stringp (car score-param)))
1225          (t
1226           (setq score-param (list (list score-param)))))
1227         (when score-param
1228           (gnus-score-headers score-param))
1229         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1230           (setq gnus-score
1231                 (or (cdr (assq (mail-header-number gnus-headers)
1232                                gnus-newsgroup-scored))
1233                     gnus-summary-default-score))
1234           (when (funcall predicate)
1235             (push (mail-header-number gnus-headers)
1236                   arts))))
1237       ;; Fetch the articles.
1238       (when arts
1239         (gnus-agent-fetch-articles group arts)))
1240     ;; Perhaps we have some additional articles to fetch.
1241     (setq arts (assq 'download (gnus-info-marks
1242                                 (setq info (gnus-get-info group)))))
1243     (when (cdr arts)
1244       (gnus-message 8 "Agent is downloading marked articles...")
1245       (gnus-agent-fetch-articles
1246        group (gnus-uncompress-range (cdr arts)))
1247       (setq marks (delq arts (gnus-info-marks info)))
1248       (gnus-info-set-marks info marks)
1249       (gnus-dribble-enter
1250        (concat "(gnus-group-set-info '"
1251                (gnus-prin1-to-string info)
1252                ")")))))
1253
1254 ;;;
1255 ;;; Agent Category Mode
1256 ;;;
1257
1258 (defvar gnus-category-mode-hook nil
1259   "Hook run in `gnus-category-mode' buffers.")
1260
1261 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1262   "Format of category lines.")
1263
1264 (defvar gnus-category-mode-line-format "Gnus: %%b"
1265   "The format specification for the category mode line.")
1266
1267 (defvar gnus-agent-short-article 100
1268   "Articles that have fewer lines than this are short.")
1269
1270 (defvar gnus-agent-long-article 200
1271   "Articles that have more lines than this are long.")
1272
1273 (defvar gnus-agent-low-score 0
1274   "Articles that have a score lower than this have a low score.")
1275
1276 (defvar gnus-agent-high-score 0
1277   "Articles that have a score higher than this have a high score.")
1278
1279
1280 ;;; Internal variables.
1281
1282 (defvar gnus-category-buffer "*Agent Category*")
1283
1284 (defvar gnus-category-line-format-alist
1285   `((?c gnus-tmp-name ?s)
1286     (?g gnus-tmp-groups ?d)))
1287
1288 (defvar gnus-category-mode-line-format-alist
1289   `((?u user-defined ?s)))
1290
1291 (defvar gnus-category-line-format-spec nil)
1292 (defvar gnus-category-mode-line-format-spec nil)
1293
1294 (defvar gnus-category-mode-map nil)
1295 (put 'gnus-category-mode 'mode-class 'special)
1296
1297 (unless gnus-category-mode-map
1298   (setq gnus-category-mode-map (make-sparse-keymap))
1299   (suppress-keymap gnus-category-mode-map)
1300
1301   (gnus-define-keys gnus-category-mode-map
1302     "q" gnus-category-exit
1303     "k" gnus-category-kill
1304     "c" gnus-category-copy
1305     "a" gnus-category-add
1306     "p" gnus-category-edit-predicate
1307     "g" gnus-category-edit-groups
1308     "s" gnus-category-edit-score
1309     "l" gnus-category-list
1310
1311     "\C-c\C-i" gnus-info-find-node
1312     "\C-c\C-b" gnus-bug))
1313
1314 (defvar gnus-category-menu-hook nil
1315   "*Hook run after the creation of the menu.")
1316
1317 (defun gnus-category-make-menu-bar ()
1318   (gnus-turn-off-edit-menu 'category)
1319   (unless (boundp 'gnus-category-menu)
1320     (easy-menu-define
1321      gnus-category-menu gnus-category-mode-map ""
1322      '("Categories"
1323        ["Add" gnus-category-add t]
1324        ["Kill" gnus-category-kill t]
1325        ["Copy" gnus-category-copy t]
1326        ["Edit predicate" gnus-category-edit-predicate t]
1327        ["Edit score" gnus-category-edit-score t]
1328        ["Edit groups" gnus-category-edit-groups t]
1329        ["Exit" gnus-category-exit t]))
1330
1331     (gnus-run-hooks 'gnus-category-menu-hook)))
1332
1333 (defun gnus-category-mode ()
1334   "Major mode for listing and editing agent categories.
1335
1336 All normal editing commands are switched off.
1337 \\<gnus-category-mode-map>
1338 For more in-depth information on this mode, read the manual
1339 (`\\[gnus-info-find-node]').
1340
1341 The following commands are available:
1342
1343 \\{gnus-category-mode-map}"
1344   (interactive)
1345   (when (gnus-visual-p 'category-menu 'menu)
1346     (gnus-category-make-menu-bar))
1347   (kill-all-local-variables)
1348   (gnus-simplify-mode-line)
1349   (setq major-mode 'gnus-category-mode)
1350   (setq mode-name "Category")
1351   (gnus-set-default-directory)
1352   (setq mode-line-process nil)
1353   (use-local-map gnus-category-mode-map)
1354   (buffer-disable-undo)
1355   (setq truncate-lines t)
1356   (setq buffer-read-only t)
1357   (gnus-run-hooks 'gnus-category-mode-hook))
1358
1359 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1360
1361 (defun gnus-category-insert-line (category)
1362   (let* ((gnus-tmp-name (format "%s" (car category)))
1363          (gnus-tmp-groups (length (cadddr category))))
1364     (beginning-of-line)
1365     (gnus-add-text-properties
1366      (point)
1367      (prog1 (1+ (point))
1368        ;; Insert the text.
1369        (eval gnus-category-line-format-spec))
1370      (list 'gnus-category gnus-tmp-name))))
1371
1372 (defun gnus-enter-category-buffer ()
1373   "Go to the Category buffer."
1374   (interactive)
1375   (gnus-category-setup-buffer)
1376   (gnus-configure-windows 'category)
1377   (gnus-category-prepare))
1378
1379 (defun gnus-category-setup-buffer ()
1380   (unless (get-buffer gnus-category-buffer)
1381     (save-excursion
1382       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1383       (gnus-category-mode))))
1384
1385 (defun gnus-category-prepare ()
1386   (gnus-set-format 'category-mode)
1387   (gnus-set-format 'category t)
1388   (let ((alist gnus-category-alist)
1389         (buffer-read-only nil))
1390     (erase-buffer)
1391     (while alist
1392       (gnus-category-insert-line (pop alist)))
1393     (goto-char (point-min))
1394     (gnus-category-position-point)))
1395
1396 (defun gnus-category-name ()
1397   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1398       (error "No category on the current line")))
1399
1400 (defun gnus-category-read ()
1401   "Read the category alist."
1402   (setq gnus-category-alist
1403         (or (gnus-agent-read-file
1404              (nnheader-concat gnus-agent-directory "lib/categories"))
1405             (list (list 'default 'short nil nil)))))
1406
1407 (defun gnus-category-write ()
1408   "Write the category alist."
1409   (setq gnus-category-predicate-cache nil
1410         gnus-category-group-cache nil)
1411   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1412   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1413     (prin1 gnus-category-alist (current-buffer))))
1414
1415 (defun gnus-category-edit-predicate (category)
1416   "Edit the predicate for CATEGORY."
1417   (interactive (list (gnus-category-name)))
1418   (let ((info (assq category gnus-category-alist)))
1419     (gnus-edit-form
1420      (cadr info) (format "Editing the predicate for category %s" category)
1421      `(lambda (predicate)
1422         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1423         (gnus-category-write)
1424         (gnus-category-list)))))
1425
1426 (defun gnus-category-edit-score (category)
1427   "Edit the score expression for CATEGORY."
1428   (interactive (list (gnus-category-name)))
1429   (let ((info (assq category gnus-category-alist)))
1430     (gnus-edit-form
1431      (caddr info)
1432      (format "Editing the score expression for category %s" category)
1433      `(lambda (groups)
1434         (setcar (nthcdr 2 (assq ',category gnus-category-alist)) groups)
1435         (gnus-category-write)
1436         (gnus-category-list)))))
1437
1438 (defun gnus-category-edit-groups (category)
1439   "Edit the group list for CATEGORY."
1440   (interactive (list (gnus-category-name)))
1441   (let ((info (assq category gnus-category-alist)))
1442     (gnus-edit-form
1443      (cadddr info) (format "Editing the group list for category %s" category)
1444      `(lambda (groups)
1445         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1446         (gnus-category-write)
1447         (gnus-category-list)))))
1448
1449 (defun gnus-category-kill (category)
1450   "Kill the current category."
1451   (interactive (list (gnus-category-name)))
1452   (let ((info (assq category gnus-category-alist))
1453         (buffer-read-only nil))
1454     (gnus-delete-line)
1455     (setq gnus-category-alist (delq info gnus-category-alist))
1456     (gnus-category-write)))
1457
1458 (defun gnus-category-copy (category to)
1459   "Copy the current category."
1460   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1461   (let ((info (assq category gnus-category-alist)))
1462     (push (list to (gnus-copy-sequence (cadr info))
1463                 (gnus-copy-sequence (caddr info)) nil)
1464           gnus-category-alist)
1465     (gnus-category-write)
1466     (gnus-category-list)))
1467
1468 (defun gnus-category-add (category)
1469   "Create a new category."
1470   (interactive "SCategory name: ")
1471   (when (assq category gnus-category-alist)
1472     (error "Category %s already exists" category))
1473   (push (list category 'false nil nil)
1474         gnus-category-alist)
1475   (gnus-category-write)
1476   (gnus-category-list))
1477
1478 (defun gnus-category-list ()
1479   "List all categories."
1480   (interactive)
1481   (gnus-category-prepare))
1482
1483 (defun gnus-category-exit ()
1484   "Return to the group buffer."
1485   (interactive)
1486   (kill-buffer (current-buffer))
1487   (gnus-configure-windows 'group t))
1488
1489 ;; To avoid having 8-bit characters in the source file.
1490 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1491
1492 (defvar gnus-category-predicate-alist
1493   '((spam . gnus-agent-spam-p)
1494     (short . gnus-agent-short-p)
1495     (long . gnus-agent-long-p)
1496     (low . gnus-agent-low-scored-p)
1497     (high . gnus-agent-high-scored-p)
1498     (true . gnus-agent-true)
1499     (false . gnus-agent-false))
1500   "Mapping from short score predicate symbols to predicate functions.")
1501
1502 (defun gnus-agent-spam-p ()
1503   "Say whether an article is spam or not."
1504   (unless gnus-agent-spam-hashtb
1505     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1506   (if (not (equal (mail-header-references gnus-headers) ""))
1507       nil
1508     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1509       (prog1
1510           (gnus-gethash string gnus-agent-spam-hashtb)
1511         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1512
1513 (defun gnus-agent-short-p ()
1514   "Say whether an article is short or not."
1515   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1516
1517 (defun gnus-agent-long-p ()
1518   "Say whether an article is long or not."
1519   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1520
1521 (defun gnus-agent-low-scored-p ()
1522   "Say whether an article has a low score or not."
1523   (< gnus-score gnus-agent-low-score))
1524
1525 (defun gnus-agent-high-scored-p ()
1526   "Say whether an article has a high score or not."
1527   (> gnus-score gnus-agent-high-score))
1528
1529 (defun gnus-category-make-function (cat)
1530   "Make a function from category CAT."
1531   (let ((func (gnus-category-make-function-1 cat)))
1532     (if (and (= (length func) 1)
1533              (symbolp (car func)))
1534         (car func)
1535       (gnus-byte-compile `(lambda () ,func)))))
1536
1537 (defun gnus-agent-true ()
1538   "Return t."
1539   t)
1540
1541 (defun gnus-agent-false ()
1542   "Return nil."
1543   nil)
1544
1545 (defun gnus-category-make-function-1 (cat)
1546   "Make a function from category CAT."
1547   (cond
1548    ;; Functions are just returned as is.
1549    ((or (symbolp cat)
1550         (gnus-functionp cat))
1551     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1552            cat)))
1553    ;; More complex category.
1554    ((consp cat)
1555     `(,(cond
1556         ((memq (car cat) '(& and))
1557          'and)
1558         ((memq (car cat) '(| or))
1559          'or)
1560         ((memq (car cat) gnus-category-not)
1561          'not))
1562       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1563    (t
1564     (error "Unknown category type: %s" cat))))
1565
1566 (defun gnus-get-predicate (predicate)
1567   "Return the predicate for CATEGORY."
1568   (or (cdr (assoc predicate gnus-category-predicate-cache))
1569       (cdar (push (cons predicate
1570                         (gnus-category-make-function predicate))
1571                   gnus-category-predicate-cache))))
1572
1573 (defun gnus-group-category (group)
1574   "Return the category GROUP belongs to."
1575   (unless gnus-category-group-cache
1576     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1577     (let ((cs gnus-category-alist)
1578           groups cat)
1579       (while (setq cat (pop cs))
1580         (setq groups (cadddr cat))
1581         (while groups
1582           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1583   (or (gnus-gethash group gnus-category-group-cache)
1584       (assq 'default gnus-category-alist)))
1585
1586 (defun gnus-agent-expire ()
1587   "Expire all old articles."
1588   (interactive)
1589   (let ((methods gnus-agent-covered-methods)
1590         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1591         gnus-command-method sym group articles
1592         history overview file histories elem art nov-file low info
1593         unreads marked article orig lowest highest)
1594     (save-excursion
1595       (setq overview (gnus-get-buffer-create " *expire overview*"))
1596       (while (setq gnus-command-method (pop methods))
1597         (when (file-exists-p (gnus-agent-lib-file "active"))
1598           (with-temp-buffer
1599             (insert-file-contents-as-coding-system
1600              gnus-agent-file-coding-system (gnus-agent-lib-file "active"))
1601             (gnus-active-to-gnus-format
1602              gnus-command-method
1603              (setq orig (gnus-make-hashtable
1604                          (count-lines (point-min) (point-max))))))
1605           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1606             (gnus-agent-open-history)
1607             (set-buffer
1608              (setq gnus-agent-current-history
1609                    (setq history (gnus-agent-history-buffer))))
1610             (goto-char (point-min))
1611             (when (> (buffer-size) 1)
1612               (goto-char (point-min))
1613               (while (not (eobp))
1614                 (skip-chars-forward "^\t")
1615                 (if (let ((fetch-date (read (current-buffer))))
1616                       (if (numberp fetch-date)
1617                           (>  fetch-date day)
1618                         ;; History file is corrupted.
1619                         (gnus-message
1620                          5
1621                          (format "File %s is corrupted!"
1622                                  (gnus-agent-lib-file "history")))
1623                         (sit-for 1)
1624                         ;; Ignore it
1625                         t))
1626                     ;; New article; we don't expire it.
1627                     (forward-line 1)
1628                   ;; Old article.  Schedule it for possible nuking.
1629                   (while (not (eolp))
1630                     (setq sym (let ((obarray expiry-hashtb) s)
1631                                 (setq s (read (current-buffer)))
1632                                 (if (stringp s) (intern s) s)))
1633                     (if (boundp sym)
1634                         (set sym (cons (cons (read (current-buffer)) (point))
1635                                        (symbol-value sym)))
1636                       (set sym (list (cons (read (current-buffer)) (point)))))
1637                     (skip-chars-forward " "))
1638                   (forward-line 1)))
1639               ;; We now have all articles that can possibly be expired.
1640               (mapatoms
1641                (lambda (sym)
1642                  (setq group (symbol-name sym)
1643                        articles (sort (symbol-value sym) 'car-less-than-car)
1644                        low (car (gnus-active group))
1645                        info (gnus-get-info group)
1646                        unreads (ignore-errors
1647                                  (gnus-list-of-unread-articles group))
1648                        marked (nconc
1649                                (gnus-uncompress-range
1650                                 (cdr (assq 'tick (gnus-info-marks info))))
1651                                (gnus-uncompress-range
1652                                 (cdr (assq 'dormant (gnus-info-marks info))))
1653                                (gnus-uncompress-range
1654                                 (cdr (assq 'save (gnus-info-marks info))))
1655                                (gnus-uncompress-range
1656                                 (cdr (assq 'reply (gnus-info-marks info)))))
1657                        nov-file (gnus-agent-article-name ".overview" group)
1658                        lowest nil
1659                        highest nil)
1660                  (gnus-agent-load-alist group)
1661                  (gnus-message 5 "Expiring articles in %s" group)
1662                  (set-buffer overview)
1663                  (erase-buffer)
1664                  (when (file-exists-p nov-file)
1665                    (nnheader-insert-file-contents nov-file))
1666                  (goto-char (point-min))
1667                  (setq article 0)
1668                  (while (setq elem (pop articles))
1669                    (setq article (car elem))
1670                    (when (or (null low)
1671                              (< article low)
1672                              gnus-agent-expire-all
1673                              (and (not (memq article unreads))
1674                                   (not (memq article marked))))
1675                      ;; Find and nuke the NOV line.
1676                      (while (and (not (eobp))
1677                                  (or (not (numberp
1678                                            (setq art (read (current-buffer)))))
1679                                      (< art article)))
1680                        (if (and (numberp art)
1681                                 (file-exists-p
1682                                  (gnus-agent-article-name
1683                                   (number-to-string art) group)))
1684                            (progn
1685                              (unless lowest
1686                                (setq lowest art))
1687                              (setq highest art)
1688                              (forward-line 1))
1689                          ;; Remove old NOV lines that have no articles.
1690                          (gnus-delete-line)))
1691                      (if (or (eobp)
1692                              (/= art article))
1693                          (beginning-of-line)
1694                        (gnus-delete-line))
1695                      ;; Nuke the article.
1696                      (when (file-exists-p
1697                             (setq file (gnus-agent-article-name
1698                                         (number-to-string article)
1699                                         group)))
1700                        (delete-file file))
1701                      ;; Schedule the history line for nuking.
1702                      (push (cdr elem) histories)))
1703                  (gnus-make-directory (file-name-directory nov-file))
1704                  (write-region-as-coding-system
1705                   gnus-agent-file-coding-system
1706                   (point-min) (point-max) nov-file nil 'silent)
1707                  ;; Delete the unwanted entries in the alist.
1708                  (setq gnus-agent-article-alist
1709                        (sort gnus-agent-article-alist 'car-less-than-car))
1710                  (let* ((alist gnus-agent-article-alist)
1711                         (prev (cons nil alist))
1712                         (first prev)
1713                         expired)
1714                    (while (and alist
1715                                (<= (caar alist) article))
1716                      (if (or (not (cdar alist))
1717                              (not (file-exists-p
1718                                    (gnus-agent-article-name
1719                                     (number-to-string
1720                                      (caar alist))
1721                                     group))))
1722                          (progn
1723                            (push (caar alist) expired)
1724                            (setcdr prev (setq alist (cdr alist))))
1725                        (setq prev alist
1726                              alist (cdr alist))))
1727                    (setq gnus-agent-article-alist (cdr first))
1728                    (gnus-agent-save-alist group)
1729                    ;; Mark all articles up to the first article
1730                    ;; in `gnus-article-alist' as read.
1731                    (when (and info (caar gnus-agent-article-alist))
1732                      (setcar (nthcdr 2 info)
1733                              (gnus-range-add
1734                               (nth 2 info)
1735                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1736                    ;; Maybe everything has been expired from `gnus-article-alist'
1737                    ;; and so the above marking as read could not be conducted,
1738                    ;; or there are expired article within the range of the alist.
1739                    (when (and info
1740                               expired
1741                               (or (not (caar gnus-agent-article-alist))
1742                                   (> (car expired)
1743                                      (caar gnus-agent-article-alist))))
1744                      (setcar (nthcdr 2 info)
1745                              (gnus-add-to-range
1746                               (nth 2 info)
1747                               (nreverse expired))))
1748                    (gnus-dribble-enter
1749                     (concat "(gnus-group-set-info '"
1750                             (gnus-prin1-to-string info)
1751                             ")")))
1752                  (when lowest
1753                    (if (gnus-gethash group orig)
1754                        (setcar (gnus-gethash group orig) lowest)
1755                      (gnus-sethash group (cons lowest highest) orig))))
1756                expiry-hashtb)
1757               (set-buffer history)
1758               (setq histories (nreverse (sort histories '<)))
1759               (while histories
1760                 (goto-char (pop histories))
1761                 (gnus-delete-line))
1762               (gnus-agent-save-history)
1763               (gnus-agent-close-history)
1764               (gnus-write-active-file (gnus-agent-lib-file "active") orig))
1765             (gnus-message 4 "Expiry...done")))))))
1766
1767 ;;;###autoload
1768 (defun gnus-agent-batch ()
1769   (interactive)
1770   (let ((init-file-user "")
1771         (gnus-always-read-dribble-file t))
1772     (gnus))
1773   (gnus-group-send-queue)
1774   (gnus-agent-fetch-session))
1775
1776 (provide 'gnus-agent)
1777
1778 ;;; gnus-agent.el ends here