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