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