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