2000-10-07 09:18:53 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 (if (fboundp 'union)
937     (defalias 'gnus-agent-union 'union)
938   (defun gnus-agent-union (l1 l2)
939     "Set union of lists L1 and L2."
940     (cond ((null l1) l2)
941           ((null l2) l1)
942           ((equal l1 l2) l1)
943           (t
944            (or (>= (length l1) (length l2))
945                (setq l1 (prog1 l2 (setq l2 l1))))
946            (while l2
947              (or (memq (car l2) l1)
948                  (push (car l2) l1))
949              (pop l2))
950            l1))))
951
952 (defun gnus-agent-fetch-headers (group &optional force)
953   (let ((articles (gnus-list-of-unread-articles group))
954         (gnus-decode-encoded-word-function 'identity)
955         (file (gnus-agent-article-name ".overview" group)))
956     ;; Add article with marks to list of article headers we want to fetch.
957     (dolist (arts (gnus-info-marks (gnus-get-info group)))
958       (setq articles (gnus-agent-union (gnus-uncompress-sequence (cdr arts))
959                             articles)))
960     (setq articles (sort articles '<))
961     ;; Remove known articles.
962     (when (gnus-agent-load-alist group)
963       (setq articles (gnus-sorted-intersection
964                       articles
965                       (gnus-uncompress-range
966                        (cons (1+ (caar (last gnus-agent-article-alist)))
967                              (cdr (gnus-active group)))))))
968     ;; Fetch them.
969     (gnus-make-directory (nnheader-translate-file-chars
970                           (file-name-directory file) t))
971     (when articles
972       (gnus-message 7 "Fetching headers for %s..." group)
973       (save-excursion
974         (set-buffer nntp-server-buffer)
975         (unless (eq 'nov (gnus-retrieve-headers articles group))
976           (nnvirtual-convert-headers))
977         ;; Save these headers for later processing.
978         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
979         (when (file-exists-p file)
980           (gnus-agent-braid-nov group articles file))
981         (let ((coding-system-for-write
982                gnus-agent-file-coding-system))
983           (write-region (point-min) (point-max) file nil 'silent))
984         (gnus-agent-save-alist group articles nil)
985         (gnus-agent-enter-history
986          "last-header-fetched-for-session"
987          (list (cons group (nth (- (length  articles) 1) articles)))
988          (time-to-days (current-time)))
989         articles))))
990
991 (defsubst gnus-agent-copy-nov-line (article)
992   (let (b e)
993     (set-buffer gnus-agent-overview-buffer)
994     (setq b (point))
995     (if (eq article (read (current-buffer)))
996         (setq e (progn (forward-line 1) (point)))
997       (progn
998         (beginning-of-line)
999         (setq e b)))
1000     (set-buffer nntp-server-buffer)
1001     (insert-buffer-substring gnus-agent-overview-buffer b e)))
1002
1003 (defun gnus-agent-braid-nov (group articles file)
1004   (set-buffer gnus-agent-overview-buffer)
1005   (goto-char (point-min))
1006   (set-buffer nntp-server-buffer)
1007   (erase-buffer)
1008   (nnheader-insert-file-contents file)
1009   (goto-char (point-max))
1010   (if (or (= (point-min) (point-max))
1011           (progn
1012             (forward-line -1)
1013             (< (read (current-buffer)) (car articles))))
1014       ;; We have only headers that are after the older headers,
1015       ;; so we just append them.
1016       (progn
1017         (goto-char (point-max))
1018         (insert-buffer-substring gnus-agent-overview-buffer))
1019     ;; We do it the hard way.
1020     (nnheader-find-nov-line (car articles))
1021     (gnus-agent-copy-nov-line (car articles))
1022     (pop articles)
1023     (while (and articles
1024                 (not (eobp)))
1025       (while (and (not (eobp))
1026                   (< (read (current-buffer)) (car articles)))
1027         (forward-line 1))
1028       (beginning-of-line)
1029       (unless (eobp)
1030         (gnus-agent-copy-nov-line (car articles))
1031         (setq articles (cdr articles))))
1032     (when articles
1033       (let (b e)
1034         (set-buffer gnus-agent-overview-buffer)
1035         (setq b (point)
1036               e (point-max))
1037         (set-buffer nntp-server-buffer)
1038         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
1039
1040 (defun gnus-agent-load-alist (group &optional dir)
1041   "Load the article-state alist for GROUP."
1042   (setq gnus-agent-article-alist
1043         (gnus-agent-read-file
1044          (if dir
1045              (concat dir ".agentview")
1046            (gnus-agent-article-name ".agentview" group)))))
1047
1048 (defun gnus-agent-save-alist (group &optional articles state dir)
1049   "Save the article-state alist for GROUP."
1050   (let ((file-name-coding-system nnmail-pathname-coding-system))
1051       (with-temp-file (if dir
1052                           (concat dir ".agentview")
1053                         (gnus-agent-article-name ".agentview" group))
1054         (princ (setq gnus-agent-article-alist
1055                      (nconc gnus-agent-article-alist
1056                             (mapcar (lambda (article) (cons article state))
1057                                     articles)))
1058                (current-buffer))
1059         (insert "\n"))))
1060
1061 (defun gnus-agent-article-name (article group)
1062   (concat (gnus-agent-directory) (gnus-agent-group-path group) "/"
1063           (if (stringp article) article (string-to-number article))))
1064
1065 (defun gnus-agent-batch-confirmation (msg)
1066   "Show error message and return t."
1067   (gnus-message 1 msg)
1068   t)
1069
1070 ;;;###autoload
1071 (defun gnus-agent-batch-fetch ()
1072   "Start Gnus and fetch session."
1073   (interactive)
1074   (gnus)
1075   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1076     (gnus-agent-fetch-session))
1077   (gnus-group-exit))
1078
1079 (defun gnus-agent-fetch-session ()
1080   "Fetch all articles and headers that are eligible for fetching."
1081   (interactive)
1082   (unless gnus-agent-covered-methods
1083     (error "No servers are covered by the Gnus agent"))
1084   (unless gnus-plugged
1085     (error "Can't fetch articles while Gnus is unplugged"))
1086   (let ((methods gnus-agent-covered-methods)
1087         groups group gnus-command-method)
1088     (save-excursion
1089       (while methods
1090         (condition-case err
1091             (progn
1092               (setq gnus-command-method (car methods))
1093               (when (or (gnus-server-opened gnus-command-method)
1094                         (gnus-open-server gnus-command-method))
1095                 (setq groups (gnus-groups-from-server (car methods)))
1096                 (gnus-agent-with-fetch
1097                   (while (setq group (pop groups))
1098                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1099                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1100           (error 
1101            (unless (funcall gnus-agent-confirmation-function
1102                             (format "Error (%s).  Continue? " err))
1103              (error "Cannot fetch articles into the Gnus agent."))))
1104         (pop methods))
1105       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1106
1107 (defun gnus-agent-fetch-group-1 (group method)
1108   "Fetch GROUP."
1109   (let ((gnus-command-method method)
1110         (gnus-newsgroup-name group)
1111         gnus-newsgroup-dependencies gnus-newsgroup-headers
1112         gnus-newsgroup-scored gnus-headers gnus-score
1113         gnus-use-cache articles arts
1114         category predicate info marks score-param
1115         (gnus-summary-expunge-below gnus-summary-expunge-below)
1116         (gnus-summary-mark-below gnus-summary-mark-below)
1117         (gnus-orphan-score gnus-orphan-score)
1118         ;; Maybe some other gnus-summary local variables should also
1119         ;; be put here.
1120         )
1121     (unless (gnus-check-group group)
1122       (error "Can't open server for %s" group))
1123     ;; Fetch headers.
1124     (when (and (or (gnus-active group) (gnus-activate-group group))
1125                (setq articles (gnus-agent-fetch-headers group))
1126                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1127                  ;; Parse them and see which articles we want to fetch.
1128                  (setq gnus-newsgroup-dependencies
1129                        (make-vector (length articles) 0))
1130                  (setq gnus-newsgroup-headers
1131                        (gnus-get-newsgroup-headers-xover articles nil nil 
1132                                                          group))
1133                  ;; `gnus-agent-overview-buffer' may be killed for
1134                  ;; timeout reason.  If so, recreate it.
1135                  (gnus-agent-create-buffer)))
1136       (setq category (gnus-group-category group))
1137       (setq predicate
1138             (gnus-get-predicate
1139              (or (gnus-group-find-parameter group 'agent-predicate t)
1140                  (cadr category))))
1141       (if (memq (caaddr predicate) '(gnus-agent-true gnus-agent-false))
1142           ;; Simple implementation
1143           (setq arts
1144                 (and (eq (caaddr predicate) 'gnus-agent-true) articles))
1145         (setq arts nil)
1146         (setq score-param
1147               (or (gnus-group-get-parameter group 'agent-score t)
1148                   (caddr category)))
1149         ;; Translate score-param into real one
1150         (cond
1151          ((not score-param))
1152          ((eq score-param 'file)
1153           (setq score-param (gnus-all-score-files group)))
1154          ((stringp (car score-param)))
1155          (t
1156           (setq score-param (list (list score-param)))))
1157         (when score-param
1158           (gnus-score-headers score-param))
1159         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1160           (setq gnus-score
1161                 (or (cdr (assq (mail-header-number gnus-headers)
1162                                gnus-newsgroup-scored))
1163                     gnus-summary-default-score))
1164           (when (funcall predicate)
1165             (push (mail-header-number gnus-headers)
1166                   arts))))
1167       ;; Fetch the articles.
1168       (when arts
1169         (gnus-agent-fetch-articles group arts)))
1170     ;; Perhaps we have some additional articles to fetch.
1171     (setq arts (assq 'download (gnus-info-marks
1172                                 (setq info (gnus-get-info group)))))
1173     (when (cdr arts)
1174       (gnus-agent-fetch-articles
1175        group (gnus-uncompress-range (cdr arts)))
1176       (setq marks (delq arts (gnus-info-marks info)))
1177       (gnus-info-set-marks info marks)
1178       (gnus-dribble-enter
1179        (concat "(gnus-group-set-info '"
1180                (gnus-prin1-to-string info)
1181                ")")))))
1182
1183 ;;;
1184 ;;; Agent Category Mode
1185 ;;;
1186
1187 (defvar gnus-category-mode-hook nil
1188   "Hook run in `gnus-category-mode' buffers.")
1189
1190 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1191   "Format of category lines.")
1192
1193 (defvar gnus-category-mode-line-format "Gnus: %%b"
1194   "The format specification for the category mode line.")
1195
1196 (defvar gnus-agent-short-article 100
1197   "Articles that have fewer lines than this are short.")
1198
1199 (defvar gnus-agent-long-article 200
1200   "Articles that have more lines than this are long.")
1201
1202 (defvar gnus-agent-low-score 0
1203   "Articles that have a score lower than this have a low score.")
1204
1205 (defvar gnus-agent-high-score 0
1206   "Articles that have a score higher than this have a high score.")
1207
1208
1209 ;;; Internal variables.
1210
1211 (defvar gnus-category-buffer "*Agent Category*")
1212
1213 (defvar gnus-category-line-format-alist
1214   `((?c gnus-tmp-name ?s)
1215     (?g gnus-tmp-groups ?d)))
1216
1217 (defvar gnus-category-mode-line-format-alist
1218   `((?u user-defined ?s)))
1219
1220 (defvar gnus-category-line-format-spec nil)
1221 (defvar gnus-category-mode-line-format-spec nil)
1222
1223 (defvar gnus-category-mode-map nil)
1224 (put 'gnus-category-mode 'mode-class 'special)
1225
1226 (unless gnus-category-mode-map
1227   (setq gnus-category-mode-map (make-sparse-keymap))
1228   (suppress-keymap gnus-category-mode-map)
1229
1230   (gnus-define-keys gnus-category-mode-map
1231     "q" gnus-category-exit
1232     "k" gnus-category-kill
1233     "c" gnus-category-copy
1234     "a" gnus-category-add
1235     "p" gnus-category-edit-predicate
1236     "g" gnus-category-edit-groups
1237     "s" gnus-category-edit-score
1238     "l" gnus-category-list
1239
1240     "\C-c\C-i" gnus-info-find-node
1241     "\C-c\C-b" gnus-bug))
1242
1243 (defvar gnus-category-menu-hook nil
1244   "*Hook run after the creation of the menu.")
1245
1246 (defun gnus-category-make-menu-bar ()
1247   (gnus-turn-off-edit-menu 'category)
1248   (unless (boundp 'gnus-category-menu)
1249     (easy-menu-define
1250      gnus-category-menu gnus-category-mode-map ""
1251      '("Categories"
1252        ["Add" gnus-category-add t]
1253        ["Kill" gnus-category-kill t]
1254        ["Copy" gnus-category-copy t]
1255        ["Edit predicate" gnus-category-edit-predicate t]
1256        ["Edit score" gnus-category-edit-score t]
1257        ["Edit groups" gnus-category-edit-groups t]
1258        ["Exit" gnus-category-exit t]))
1259
1260     (gnus-run-hooks 'gnus-category-menu-hook)))
1261
1262 (defun gnus-category-mode ()
1263   "Major mode for listing and editing agent categories.
1264
1265 All normal editing commands are switched off.
1266 \\<gnus-category-mode-map>
1267 For more in-depth information on this mode, read the manual
1268 (`\\[gnus-info-find-node]').
1269
1270 The following commands are available:
1271
1272 \\{gnus-category-mode-map}"
1273   (interactive)
1274   (when (gnus-visual-p 'category-menu 'menu)
1275     (gnus-category-make-menu-bar))
1276   (kill-all-local-variables)
1277   (gnus-simplify-mode-line)
1278   (setq major-mode 'gnus-category-mode)
1279   (setq mode-name "Category")
1280   (gnus-set-default-directory)
1281   (setq mode-line-process nil)
1282   (use-local-map gnus-category-mode-map)
1283   (buffer-disable-undo)
1284   (setq truncate-lines t)
1285   (setq buffer-read-only t)
1286   (gnus-run-hooks 'gnus-category-mode-hook))
1287
1288 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1289
1290 (defun gnus-category-insert-line (category)
1291   (let* ((gnus-tmp-name (car category))
1292          (gnus-tmp-groups (length (cadddr category))))
1293     (beginning-of-line)
1294     (gnus-add-text-properties
1295      (point)
1296      (prog1 (1+ (point))
1297        ;; Insert the text.
1298        (eval gnus-category-line-format-spec))
1299      (list 'gnus-category gnus-tmp-name))))
1300
1301 (defun gnus-enter-category-buffer ()
1302   "Go to the Category buffer."
1303   (interactive)
1304   (gnus-category-setup-buffer)
1305   (gnus-configure-windows 'category)
1306   (gnus-category-prepare))
1307
1308 (defun gnus-category-setup-buffer ()
1309   (unless (get-buffer gnus-category-buffer)
1310     (save-excursion
1311       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1312       (gnus-category-mode))))
1313
1314 (defun gnus-category-prepare ()
1315   (gnus-set-format 'category-mode)
1316   (gnus-set-format 'category t)
1317   (let ((alist gnus-category-alist)
1318         (buffer-read-only nil))
1319     (erase-buffer)
1320     (while alist
1321       (gnus-category-insert-line (pop alist)))
1322     (goto-char (point-min))
1323     (gnus-category-position-point)))
1324
1325 (defun gnus-category-name ()
1326   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1327       (error "No category on the current line")))
1328
1329 (defun gnus-category-read ()
1330   "Read the category alist."
1331   (setq gnus-category-alist
1332         (or (gnus-agent-read-file
1333              (nnheader-concat gnus-agent-directory "lib/categories"))
1334             (list (list 'default 'short nil nil)))))
1335
1336 (defun gnus-category-write ()
1337   "Write the category alist."
1338   (setq gnus-category-predicate-cache nil
1339         gnus-category-group-cache nil)
1340   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1341   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1342     (prin1 gnus-category-alist (current-buffer))))
1343
1344 (defun gnus-category-edit-predicate (category)
1345   "Edit the predicate for CATEGORY."
1346   (interactive (list (gnus-category-name)))
1347   (let ((info (assq category gnus-category-alist)))
1348     (gnus-edit-form
1349      (cadr info) (format "Editing the predicate for category %s" category)
1350      `(lambda (predicate)
1351         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1352         (gnus-category-write)
1353         (gnus-category-list)))))
1354
1355 (defun gnus-category-edit-score (category)
1356   "Edit the score expression for CATEGORY."
1357   (interactive (list (gnus-category-name)))
1358   (let ((info (assq category gnus-category-alist)))
1359     (gnus-edit-form
1360      (caddr info)
1361      (format "Editing the score expression for category %s" category)
1362      `(lambda (groups)
1363         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1364         (gnus-category-write)
1365         (gnus-category-list)))))
1366
1367 (defun gnus-category-edit-groups (category)
1368   "Edit the group list for CATEGORY."
1369   (interactive (list (gnus-category-name)))
1370   (let ((info (assq category gnus-category-alist)))
1371     (gnus-edit-form
1372      (cadddr info) (format "Editing the group list for category %s" category)
1373      `(lambda (groups)
1374         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1375         (gnus-category-write)
1376         (gnus-category-list)))))
1377
1378 (defun gnus-category-kill (category)
1379   "Kill the current category."
1380   (interactive (list (gnus-category-name)))
1381   (let ((info (assq category gnus-category-alist))
1382         (buffer-read-only nil))
1383     (gnus-delete-line)
1384     (setq gnus-category-alist (delq info gnus-category-alist))
1385     (gnus-category-write)))
1386
1387 (defun gnus-category-copy (category to)
1388   "Copy the current category."
1389   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1390   (let ((info (assq category gnus-category-alist)))
1391     (push (list to (gnus-copy-sequence (cadr info))
1392                 (gnus-copy-sequence (caddr info)) nil)
1393           gnus-category-alist)
1394     (gnus-category-write)
1395     (gnus-category-list)))
1396
1397 (defun gnus-category-add (category)
1398   "Create a new category."
1399   (interactive "SCategory name: ")
1400   (when (assq category gnus-category-alist)
1401     (error "Category %s already exists" category))
1402   (push (list category 'false nil nil)
1403         gnus-category-alist)
1404   (gnus-category-write)
1405   (gnus-category-list))
1406
1407 (defun gnus-category-list ()
1408   "List all categories."
1409   (interactive)
1410   (gnus-category-prepare))
1411
1412 (defun gnus-category-exit ()
1413   "Return to the group buffer."
1414   (interactive)
1415   (kill-buffer (current-buffer))
1416   (gnus-configure-windows 'group t))
1417
1418 ;; To avoid having 8-bit characters in the source file.
1419 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1420
1421 (defvar gnus-category-predicate-alist
1422   '((spam . gnus-agent-spam-p)
1423     (short . gnus-agent-short-p)
1424     (long . gnus-agent-long-p)
1425     (low . gnus-agent-low-scored-p)
1426     (high . gnus-agent-high-scored-p)
1427     (true . gnus-agent-true)
1428     (false . gnus-agent-false))
1429   "Mapping from short score predicate symbols to predicate functions.")
1430
1431 (defun gnus-agent-spam-p ()
1432   "Say whether an article is spam or not."
1433   (unless gnus-agent-spam-hashtb
1434     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1435   (if (not (equal (mail-header-references gnus-headers) ""))
1436       nil
1437     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1438       (prog1
1439           (gnus-gethash string gnus-agent-spam-hashtb)
1440         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1441
1442 (defun gnus-agent-short-p ()
1443   "Say whether an article is short or not."
1444   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1445
1446 (defun gnus-agent-long-p ()
1447   "Say whether an article is long or not."
1448   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1449
1450 (defun gnus-agent-low-scored-p ()
1451   "Say whether an article has a low score or not."
1452   (< gnus-score gnus-agent-low-score))
1453
1454 (defun gnus-agent-high-scored-p ()
1455   "Say whether an article has a high score or not."
1456   (> gnus-score gnus-agent-high-score))
1457
1458 (defun gnus-category-make-function (cat)
1459   "Make a function from category CAT."
1460   `(lambda () ,(gnus-category-make-function-1 cat)))
1461
1462 (defun gnus-agent-true ()
1463   "Return t."
1464   t)
1465
1466 (defun gnus-agent-false ()
1467   "Return nil."
1468   nil)
1469
1470 (defun gnus-category-make-function-1 (cat)
1471   "Make a function from category CAT."
1472   (cond
1473    ;; Functions are just returned as is.
1474    ((or (symbolp cat)
1475         (gnus-functionp cat))
1476     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1477            cat)))
1478    ;; More complex category.
1479    ((consp cat)
1480     `(,(cond
1481         ((memq (car cat) '(& and))
1482          'and)
1483         ((memq (car cat) '(| or))
1484          'or)
1485         ((memq (car cat) gnus-category-not)
1486          'not))
1487       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1488    (t
1489     (error "Unknown category type: %s" cat))))
1490
1491 (defun gnus-get-predicate (predicate)
1492   "Return the predicate for CATEGORY."
1493   (or (cdr (assoc predicate gnus-category-predicate-cache))
1494       (cdar (push (cons predicate
1495                         (gnus-category-make-function predicate))
1496                   gnus-category-predicate-cache))))
1497
1498 (defun gnus-group-category (group)
1499   "Return the category GROUP belongs to."
1500   (unless gnus-category-group-cache
1501     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1502     (let ((cs gnus-category-alist)
1503           groups cat)
1504       (while (setq cat (pop cs))
1505         (setq groups (cadddr cat))
1506         (while groups
1507           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1508   (or (gnus-gethash group gnus-category-group-cache)
1509       (assq 'default gnus-category-alist)))
1510
1511 (defun gnus-agent-expire ()
1512   "Expire all old articles."
1513   (interactive)
1514   (let ((methods gnus-agent-covered-methods)
1515         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1516         gnus-command-method sym group articles
1517         history overview file histories elem art nov-file low info
1518         unreads marked article orig lowest highest)
1519     (save-excursion
1520       (setq overview (gnus-get-buffer-create " *expire overview*"))
1521       (while (setq gnus-command-method (pop methods))
1522         (when (file-exists-p (gnus-agent-lib-file "active"))
1523           (with-temp-buffer
1524             (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1525             (gnus-active-to-gnus-format 
1526              gnus-command-method
1527              (setq orig (gnus-make-hashtable
1528                          (count-lines (point-min) (point-max))))))
1529           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1530             (gnus-agent-open-history)
1531             (set-buffer
1532              (setq gnus-agent-current-history
1533                    (setq history (gnus-agent-history-buffer))))
1534             (goto-char (point-min))
1535             (when (> (buffer-size) 1)
1536               (goto-char (point-min))
1537               (while (not (eobp))
1538                 (skip-chars-forward "^\t")
1539                 (if (> (read (current-buffer)) day)
1540                     ;; New article; we don't expire it.
1541                     (forward-line 1)
1542                   ;; Old article.  Schedule it for possible nuking.
1543                   (while (not (eolp))
1544                     (setq sym (let ((obarray expiry-hashtb) s)
1545                                 (setq s (read (current-buffer)))
1546                                 (if (stringp s) (intern s) s)))
1547                     (if (boundp sym)
1548                         (set sym (cons (cons (read (current-buffer)) (point))
1549                                        (symbol-value sym)))
1550                       (set sym (list (cons (read (current-buffer)) (point)))))
1551                     (skip-chars-forward " "))
1552                   (forward-line 1)))
1553               ;; We now have all articles that can possibly be expired.
1554               (mapatoms
1555                (lambda (sym)
1556                  (setq group (symbol-name sym)
1557                        articles (sort (symbol-value sym) 'car-less-than-car)
1558                        low (car (gnus-active group))
1559                        info (gnus-get-info group)
1560                        unreads (ignore-errors
1561                                  (gnus-list-of-unread-articles group))
1562                        marked (nconc
1563                                (gnus-uncompress-range
1564                                 (cdr (assq 'tick (gnus-info-marks info))))
1565                                (gnus-uncompress-range
1566                                 (cdr (assq 'dormant
1567                                            (gnus-info-marks info)))))
1568                        nov-file (gnus-agent-article-name ".overview" group)
1569                        lowest nil
1570                        highest nil)
1571                  (gnus-agent-load-alist group)
1572                  (gnus-message 5 "Expiring articles in %s" group)
1573                  (set-buffer overview)
1574                  (erase-buffer)
1575                  (when (file-exists-p nov-file)
1576                    (nnheader-insert-file-contents nov-file))
1577                  (goto-char (point-min))
1578                  (setq article 0)
1579                  (while (setq elem (pop articles))
1580                    (setq article (car elem))
1581                    (when (or (null low)
1582                              (< article low)
1583                              gnus-agent-expire-all
1584                              (and (not (memq article unreads))
1585                                   (not (memq article marked))))
1586                      ;; Find and nuke the NOV line.
1587                      (while (and (not (eobp))
1588                                  (or (not (numberp
1589                                            (setq art (read (current-buffer)))))
1590                                      (< art article)))
1591                        (if (and (numberp art) 
1592                                 (file-exists-p
1593                                  (gnus-agent-article-name
1594                                   (number-to-string art) group)))
1595                            (progn
1596                              (unless lowest
1597                                (setq lowest art))
1598                              (setq highest art)
1599                              (forward-line 1))
1600                          ;; Remove old NOV lines that have no articles.
1601                          (gnus-delete-line)))
1602                      (if (or (eobp)
1603                              (/= art article))
1604                          (beginning-of-line)
1605                        (gnus-delete-line))
1606                      ;; Nuke the article.
1607                      (when (file-exists-p
1608                             (setq file (gnus-agent-article-name
1609                                         (number-to-string article)
1610                                         group)))
1611                        (delete-file file))
1612                      ;; Schedule the history line for nuking.
1613                      (push (cdr elem) histories)))
1614                  (gnus-make-directory (file-name-directory nov-file))
1615                  (let ((coding-system-for-write
1616                         gnus-agent-file-coding-system))
1617                    (write-region (point-min) (point-max) nov-file nil 'silent))
1618                  ;; Delete the unwanted entries in the alist.
1619                  (setq gnus-agent-article-alist
1620                        (sort gnus-agent-article-alist 'car-less-than-car))
1621                  (let* ((alist gnus-agent-article-alist)
1622                         (prev (cons nil alist))
1623                         (first prev)
1624                         expired)
1625                    (while (and alist
1626                                (<= (caar alist) article))
1627                      (if (or (not (cdar alist))
1628                              (not (file-exists-p
1629                                    (gnus-agent-article-name
1630                                     (number-to-string
1631                                      (caar alist))
1632                                     group))))
1633                          (progn
1634                            (push (caar alist) expired)
1635                            (setcdr prev (setq alist (cdr alist))))
1636                        (setq prev alist
1637                              alist (cdr alist))))
1638                    (setq gnus-agent-article-alist (cdr first))
1639                    (gnus-agent-save-alist group)
1640                    ;; Mark all articles up to the first article
1641                    ;; in `gnus-article-alist' as read.
1642                    (when (and info (caar gnus-agent-article-alist))
1643                      (setcar (nthcdr 2 info)
1644                              (gnus-range-add
1645                               (nth 2 info)
1646                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1647                    ;; Maybe everything has been expired from `gnus-article-alist'
1648                    ;; and so the above marking as read could not be conducted,
1649                    ;; or there are expired article within the range of the alist.
1650                    (when (and info
1651                               expired
1652                               (or (not (caar gnus-agent-article-alist))
1653                                   (> (car expired)
1654                                      (caar gnus-agent-article-alist))))
1655                      (setcar (nthcdr 2 info)
1656                              (gnus-add-to-range
1657                               (nth 2 info)
1658                               (nreverse expired))))
1659                    (gnus-dribble-enter
1660                     (concat "(gnus-group-set-info '"
1661                             (gnus-prin1-to-string info)
1662                             ")")))
1663                  (when lowest
1664                    (if (gnus-gethash group orig)
1665                        (setcar (gnus-gethash group orig) lowest)
1666                      (gnus-sethash group (cons lowest highest) orig))))
1667                expiry-hashtb)
1668               (set-buffer history)
1669               (setq histories (nreverse (sort histories '<)))
1670               (while histories
1671                 (goto-char (pop histories))
1672                 (gnus-delete-line))
1673               (gnus-agent-save-history)
1674               (gnus-agent-close-history)
1675               (gnus-write-active-file
1676                (gnus-agent-lib-file "active") orig))
1677             (gnus-message 4 "Expiry...done")))))))
1678
1679 ;;;###autoload
1680 (defun gnus-agent-batch ()
1681   (interactive)
1682   (let ((init-file-user "")
1683         (gnus-always-read-dribble-file t))
1684     (gnus))
1685   (gnus-group-send-drafts)
1686   (gnus-agent-fetch-session))
1687
1688 (provide 'gnus-agent)
1689
1690 ;;; gnus-agent.el ends here