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