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