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