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