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