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