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