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