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