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