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