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