Sync up with Pterodactyl Gnus v0.91, etc. See ChangeLog for more details.
[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)
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 (setq elem (symbol-value (intern (symbol-name sym) orig)))
574                (setcdr elem (cdr (symbol-value sym)))
575              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
576        new))
577     (gnus-make-directory (file-name-directory file))
578     (gnus-write-active-file-as-coding-system gnus-agent-file-coding-system
579                                              file orig)))
580
581 (defun gnus-agent-save-groups (method)
582   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
583
584 (defun gnus-agent-save-group-info (method group active)
585   (when (gnus-agent-method-p method)
586     (let* ((gnus-command-method method)
587            (file (gnus-agent-lib-file "active")))
588       (gnus-make-directory (file-name-directory file))
589       (with-temp-file file
590         (when (file-exists-p file)
591           (nnheader-insert-file-contents file))
592         (goto-char (point-min))
593         (when (re-search-forward
594                (concat "^" (regexp-quote group) " ") nil t)
595           (gnus-delete-line))
596         (insert group " " (number-to-string (cdr active)) " "
597                 (number-to-string (car active)) " y\n")))))
598
599 (defun gnus-agent-group-path (group)
600   "Translate GROUP into a path."
601   (if nnmail-use-long-file-names
602       (gnus-group-real-name group)
603     (nnheader-replace-chars-in-string
604      (nnheader-translate-file-chars (gnus-group-real-name group))
605      ?. ?/)))
606
607 \f
608
609 (defun gnus-agent-method-p (method)
610   "Say whether METHOD is covered by the agent."
611   (member method gnus-agent-covered-methods))
612
613 (defun gnus-agent-get-function (method)
614   (if (and (not gnus-plugged)
615            (gnus-agent-method-p method))
616       (progn
617         (require 'nnagent)
618         'nnagent)
619     (car method)))
620
621 ;;; History functions
622
623 (defun gnus-agent-history-buffer ()
624   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
625
626 (defun gnus-agent-open-history ()
627   (save-excursion
628     (push (cons (gnus-agent-method)
629                 (set-buffer (gnus-get-buffer-create
630                              (format " *Gnus agent %s history*"
631                                      (gnus-agent-method)))))
632           gnus-agent-history-buffers)
633     (erase-buffer)
634     (insert "\n")
635     (let ((file (gnus-agent-lib-file "history")))
636       (when (file-exists-p file)
637         (insert-file file))
638       (set (make-local-variable 'gnus-agent-file-name) file))))
639
640 (defun gnus-agent-save-history ()
641   (save-excursion
642     (set-buffer gnus-agent-current-history)
643     (gnus-make-directory (file-name-directory gnus-agent-file-name))
644     (write-region-as-coding-system
645      gnus-agent-file-coding-system
646      (1+ (point-min)) (point-max) gnus-agent-file-name nil 'silent)))
647
648 (defun gnus-agent-close-history ()
649   (when (gnus-buffer-live-p gnus-agent-current-history)
650     (kill-buffer gnus-agent-current-history)
651     (setq gnus-agent-history-buffers
652           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
653                 gnus-agent-history-buffers))))
654
655 (defun gnus-agent-enter-history (id group-arts date)
656   (save-excursion
657     (set-buffer gnus-agent-current-history)
658     (goto-char (point-max))
659     (insert id "\t" (number-to-string date) "\t")
660     (while group-arts
661       (insert (caar group-arts) " " (number-to-string (cdr (pop group-arts)))
662               " "))
663     (insert "\n")))
664
665 (defun gnus-agent-article-in-history-p (id)
666   (save-excursion
667     (set-buffer (gnus-agent-history-buffer))
668     (goto-char (point-min))
669     (search-forward (concat "\n" id "\t") nil t)))
670
671 (defun gnus-agent-history-path (id)
672   (save-excursion
673     (set-buffer (gnus-agent-history-buffer))
674     (goto-char (point-min))
675     (when (search-forward (concat "\n" id "\t") nil t)
676       (let ((method (gnus-agent-method)))
677         (let (paths group)
678           (while (not (numberp (setq group (read (current-buffer)))))
679             (push (concat method "/" group) paths))
680           (nreverse paths))))))
681
682 ;;;
683 ;;; Fetching
684 ;;;
685
686 (defun gnus-agent-fetch-articles (group articles)
687   "Fetch ARTICLES from GROUP and put them into the Agent."
688   (when articles
689     ;; Prune off articles that we have already fetched.
690     (while (and articles
691                 (cdr (assq (car articles) gnus-agent-article-alist)))
692      (pop articles))
693     (let ((arts articles))
694       (while (cdr arts)
695         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
696             (setcdr arts (cddr arts))
697           (setq arts (cdr arts)))))
698     (when articles
699       (let ((dir (concat
700                   (gnus-agent-directory)
701                   (gnus-agent-group-path group) "/"))
702             (date (time-to-days (current-time)))
703             (case-fold-search t)
704             pos crosses id elem)
705         (gnus-make-directory dir)
706         (gnus-message 7 "Fetching articles for %s..." group)
707         ;; Fetch the articles from the backend.
708         (if (gnus-check-backend-function 'retrieve-articles group)
709             (setq pos (gnus-retrieve-articles articles group))
710           (with-temp-buffer
711             (let (article)
712               (while (setq article (pop articles))
713                 (when (gnus-request-article article group)
714                   (goto-char (point-max))
715                   (push (cons article (point)) pos)
716                   (insert-buffer-substring nntp-server-buffer)))
717               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
718               (setq pos (nreverse pos)))))
719         ;; Then save these articles into the Agent.
720         (save-excursion
721           (set-buffer nntp-server-buffer)
722           (while pos
723             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
724             (goto-char (point-min))
725             (when (search-forward "\n\n" nil t)
726               (when (search-backward "\nXrefs: " nil t)
727                 ;; Handle crossposting.
728                 (skip-chars-forward "^ ")
729                 (skip-chars-forward " ")
730                 (setq crosses nil)
731                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
732                   (push (cons (buffer-substring (match-beginning 1)
733                                                 (match-end 1))
734                               (buffer-substring (match-beginning 2)
735                                                 (match-end 2)))
736                         crosses)
737                   (goto-char (match-end 0)))
738                 (gnus-agent-crosspost crosses (caar pos))))
739             (goto-char (point-min))
740             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
741                 (setq id "No-Message-ID-in-article")
742               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
743             (write-region-as-coding-system
744              gnus-agent-file-coding-system
745              (point-min) (point-max)
746              (concat dir (number-to-string (caar pos))) nil 'silent)
747             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
748               (setcdr elem t))
749             (gnus-agent-enter-history
750              id (or crosses (list (cons group (caar pos)))) date)
751             (widen)
752             (pop pos)))
753         (gnus-agent-save-alist group)))))
754
755 (defun gnus-agent-crosspost (crosses article)
756   (let (gnus-agent-article-alist group alist beg end)
757     (save-excursion
758       (set-buffer gnus-agent-overview-buffer)
759       (when (nnheader-find-nov-line article)
760         (forward-word 1)
761         (setq beg (point))
762         (setq end (progn (forward-line 1) (point)))))
763     (while crosses
764       (setq group (caar crosses))
765       (unless (setq alist (assoc group gnus-agent-group-alist))
766         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
767               gnus-agent-group-alist))
768       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
769       (save-excursion
770         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
771                                                group)))
772         (when (= (point-max) (point-min))
773           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
774           (ignore-errors
775             (nnheader-insert-file-contents
776              (gnus-agent-article-name ".overview" group))))
777         (nnheader-find-nov-line (string-to-number (cdar crosses)))
778         (insert (string-to-number (cdar crosses)))
779         (insert-buffer-substring gnus-agent-overview-buffer beg end))
780       (pop crosses))))
781
782 (defun gnus-agent-flush-cache ()
783   (save-excursion
784     (while gnus-agent-buffer-alist
785       (set-buffer (cdar gnus-agent-buffer-alist))
786       (write-region-as-coding-system
787        gnus-agent-file-coding-system
788        (point-min) (point-max)
789        (gnus-agent-article-name ".overview"
790                                 (caar gnus-agent-buffer-alist))
791        nil 'silent)
792       (pop gnus-agent-buffer-alist))
793     (while gnus-agent-group-alist
794       (with-temp-file (caar gnus-agent-group-alist)
795         (princ (cdar gnus-agent-group-alist))
796         (insert "\n"))
797       (pop gnus-agent-group-alist))))
798
799 (defun gnus-agent-fetch-headers (group &optional force)
800   (let ((articles (gnus-list-of-unread-articles group))
801         (gnus-decode-encoded-word-function 'identity)
802         (file (gnus-agent-article-name ".overview" group)))
803     ;; add article with marks to list of article headers we want to fetch
804     (dolist (arts (gnus-info-marks (gnus-get-info group)))
805       (setq articles (union (gnus-uncompress-sequence (cdr arts))
806                             articles)))
807     (setq articles (sort articles '<))
808     ;; remove known articles
809     (when (gnus-agent-load-alist group)
810       (setq articles (gnus-sorted-intersection
811                       articles
812                       (gnus-uncompress-range
813                        (cons (1+ (caar (last gnus-agent-article-alist)))
814                              (cdr (gnus-active group)))))))
815     ;; Fetch them.
816     (gnus-make-directory (nnheader-translate-file-chars
817                           (file-name-directory file)))
818     (when articles
819       (gnus-message 7 "Fetching headers for %s..." group)
820       (save-excursion
821         (set-buffer nntp-server-buffer)
822         (unless (eq 'nov (gnus-retrieve-headers articles group))
823           (nnvirtual-convert-headers))
824         ;; Save these headers for later processing.
825         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
826         (when (file-exists-p file)
827           (gnus-agent-braid-nov group articles file))
828         (write-region-as-coding-system
829          gnus-agent-file-coding-system
830          (point-min) (point-max) file nil 'silent)
831         (gnus-agent-save-alist group articles nil)
832         (gnus-agent-enter-history
833          "last-header-fetched-for-session"
834          (list (cons group (nth (- (length  articles) 1) articles)))
835          (time-to-days (current-time)))
836         articles))))
837
838 (defsubst gnus-agent-copy-nov-line (article)
839   (let (b e)
840     (set-buffer gnus-agent-overview-buffer)
841     (setq b (point))
842     (if (eq article (read (current-buffer)))
843         (setq e (progn (forward-line 1) (point)))
844       (progn
845         (beginning-of-line)
846         (setq e b)))
847     (set-buffer nntp-server-buffer)
848     (insert-buffer-substring gnus-agent-overview-buffer b e)))
849
850 (defun gnus-agent-braid-nov (group articles file)
851   (set-buffer gnus-agent-overview-buffer)
852   (goto-char (point-min))
853   (set-buffer nntp-server-buffer)
854   (erase-buffer)
855   (nnheader-insert-file-contents file)
856   (goto-char (point-max))
857   (if (or (= (point-min) (point-max))
858           (progn
859             (forward-line -1)
860             (< (read (current-buffer)) (car articles))))
861       ;; We have only headers that are after the older headers,
862       ;; so we just append them.
863       (progn
864         (goto-char (point-max))
865         (insert-buffer-substring gnus-agent-overview-buffer))
866     ;; We do it the hard way.
867     (nnheader-find-nov-line (car articles))
868     (gnus-agent-copy-nov-line (car articles))
869     (pop articles)
870     (while (and articles
871                 (not (eobp)))
872       (while (and (not (eobp))
873                   (< (read (current-buffer)) (car articles)))
874         (forward-line 1))
875       (beginning-of-line)
876       (unless (eobp)
877         (gnus-agent-copy-nov-line (car articles))
878         (setq articles (cdr articles))))
879     (when articles
880       (let (b e)
881         (set-buffer gnus-agent-overview-buffer)
882         (setq b (point)
883               e (point-max))
884         (set-buffer nntp-server-buffer)
885         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
886
887 (defun gnus-agent-load-alist (group &optional dir)
888   "Load the article-state alist for GROUP."
889   (setq gnus-agent-article-alist
890         (gnus-agent-read-file
891          (if dir
892              (concat dir ".agentview")
893            (gnus-agent-article-name ".agentview" group)))))
894
895 (defun gnus-agent-save-alist (group &optional articles state dir)
896   "Save the article-state alist for GROUP."
897   (with-temp-file (if dir
898                       (concat dir ".agentview")
899                     (gnus-agent-article-name ".agentview" group))
900     (princ (setq gnus-agent-article-alist
901                  (nconc gnus-agent-article-alist
902                         (mapcar (lambda (article) (cons article state))
903                                 articles)))
904            (current-buffer))
905     (insert "\n")))
906
907 (defun gnus-agent-article-name (article group)
908   (concat (gnus-agent-directory) (gnus-agent-group-path group) "/"
909           (if (stringp article) article (string-to-number article))))
910
911 ;;;###autoload
912 (defun gnus-agent-batch-fetch ()
913   "Start Gnus and fetch session."
914   (interactive)
915   (gnus)
916   (gnus-agent-fetch-session)
917   (gnus-group-exit))
918
919 (defun gnus-agent-fetch-session ()
920   "Fetch all articles and headers that are eligible for fetching."
921   (interactive)
922   (unless gnus-agent-covered-methods
923     (error "No servers are covered by the Gnus agent"))
924   (unless gnus-plugged
925     (error "Can't fetch articles while Gnus is unplugged"))
926   (let ((methods gnus-agent-covered-methods)
927         groups group gnus-command-method)
928     (save-excursion
929       (while methods
930         (setq gnus-command-method (car methods))
931         (when (or (gnus-server-opened gnus-command-method)
932                   (gnus-open-server gnus-command-method))
933           (setq groups (gnus-groups-from-server (car methods)))
934           (gnus-agent-with-fetch
935             (while (setq group (pop groups))
936               (when (<= (gnus-group-level group) gnus-agent-handle-level)
937                 (gnus-agent-fetch-group-1 group gnus-command-method)))))
938         (pop methods))
939       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
940
941 (defun gnus-agent-fetch-group-1 (group method)
942   "Fetch GROUP."
943   (let ((gnus-command-method method)
944         (gnus-newsgroup-name group)
945         gnus-newsgroup-dependencies gnus-newsgroup-headers
946         gnus-newsgroup-scored gnus-headers gnus-score
947         gnus-use-cache articles arts
948         category predicate info marks score-param)
949     ;; Fetch headers.
950     (when (and (or (gnus-active group) (gnus-activate-group group))
951                (setq articles (gnus-agent-fetch-headers group)))
952       ;; Parse them and see which articles we want to fetch.
953       (setq gnus-newsgroup-dependencies
954             (make-vector (length articles) 0))
955       ;; No need to call `gnus-get-newsgroup-headers-xover' with
956       ;; the entire .overview for group as we still have the just
957       ;; downloaded headers in `gnus-agent-overview-buffer'.
958       (let ((nntp-server-buffer gnus-agent-overview-buffer))
959         (setq gnus-newsgroup-headers
960               (gnus-get-newsgroup-headers-xover articles nil nil group)))
961       (setq category (gnus-group-category group))
962       (setq predicate
963             (gnus-get-predicate
964              (or (gnus-group-get-parameter group 'agent-predicate t)
965                  (cadr category))))
966       ;; Do we want to download everything, or nothing?
967       (if (or (eq (caaddr predicate) 'gnus-agent-true)
968               (eq (caaddr predicate) 'gnus-agent-false))
969           ;; Yes.
970           (setq arts (symbol-value
971                       (cadr (assoc (caaddr predicate)
972                                    '((gnus-agent-true articles)
973                                      (gnus-agent-false nil))))))
974         ;; No, we need to decide what we want.
975         (setq score-param
976               (let ((score-method
977                      (or
978                       (gnus-group-get-parameter group 'agent-score t)
979                       (caddr category))))
980                 (when score-method
981                   (require 'gnus-score)
982                   (if (eq score-method 'file)
983                       (let ((entries
984                              (gnus-score-load-files
985                               (gnus-all-score-files group)))
986                             list score-file)
987                         (while (setq list (car entries))
988                           (push (car list) score-file)
989                           (setq list (cdr list))
990                           (while list
991                             (when (member (caar list)
992                                           gnus-agent-scoreable-headers)
993                               (push (car list) score-file))
994                             (setq list (cdr list)))
995                           (setq score-param
996                                 (append score-param (list (nreverse score-file)))
997                                 score-file nil entries (cdr entries)))
998                         (list score-param))
999                     (if (stringp (car score-method))
1000                         score-method
1001                       (list (list score-method)))))))
1002         (when score-param
1003           (gnus-score-headers score-param))
1004         (setq arts nil)
1005         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1006           (setq gnus-score
1007                 (or (cdr (assq (mail-header-number gnus-headers)
1008                                gnus-newsgroup-scored))
1009                     gnus-summary-default-score))
1010           (when (funcall predicate)
1011             (push (mail-header-number gnus-headers)
1012                   arts))))
1013       ;; Fetch the articles.
1014       (when arts
1015         (gnus-agent-fetch-articles group arts)))
1016     ;; Perhaps we have some additional articles to fetch.
1017     (setq arts (assq 'download (gnus-info-marks
1018                                 (setq info (gnus-get-info group)))))
1019     (when (cdr arts)
1020       (gnus-agent-fetch-articles
1021        group (gnus-uncompress-range (cdr arts)))
1022       (setq marks (delq arts (gnus-info-marks info)))
1023       (gnus-info-set-marks info marks)
1024       (gnus-dribble-enter
1025        (concat "(gnus-group-set-info '"
1026                (gnus-prin1-to-string info)
1027                ")")))))
1028
1029 ;;;
1030 ;;; Agent Category Mode
1031 ;;;
1032
1033 (defvar gnus-category-mode-hook nil
1034   "Hook run in `gnus-category-mode' buffers.")
1035
1036 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1037   "Format of category lines.")
1038
1039 (defvar gnus-category-mode-line-format "Gnus: %%b"
1040   "The format specification for the category mode line.")
1041
1042 (defvar gnus-agent-short-article 100
1043   "Articles that have fewer lines than this are short.")
1044
1045 (defvar gnus-agent-long-article 200
1046   "Articles that have more lines than this are long.")
1047
1048 (defvar gnus-agent-low-score 0
1049   "Articles that have a score lower than this have a low score.")
1050
1051 (defvar gnus-agent-high-score 0
1052   "Articles that have a score higher than this have a high score.")
1053
1054
1055 ;;; Internal variables.
1056
1057 (defvar gnus-category-buffer "*Agent Category*")
1058
1059 (defvar gnus-category-line-format-alist
1060   `((?c gnus-tmp-name ?s)
1061     (?g gnus-tmp-groups ?d)))
1062
1063 (defvar gnus-category-mode-line-format-alist
1064   `((?u user-defined ?s)))
1065
1066 (defvar gnus-category-line-format-spec nil)
1067 (defvar gnus-category-mode-line-format-spec nil)
1068
1069 (defvar gnus-category-mode-map nil)
1070 (put 'gnus-category-mode 'mode-class 'special)
1071
1072 (unless gnus-category-mode-map
1073   (setq gnus-category-mode-map (make-sparse-keymap))
1074   (suppress-keymap gnus-category-mode-map)
1075
1076   (gnus-define-keys gnus-category-mode-map
1077     "q" gnus-category-exit
1078     "k" gnus-category-kill
1079     "c" gnus-category-copy
1080     "a" gnus-category-add
1081     "p" gnus-category-edit-predicate
1082     "g" gnus-category-edit-groups
1083     "s" gnus-category-edit-score
1084     "l" gnus-category-list
1085
1086     "\C-c\C-i" gnus-info-find-node
1087     "\C-c\C-b" gnus-bug))
1088
1089 (defvar gnus-category-menu-hook nil
1090   "*Hook run after the creation of the menu.")
1091
1092 (defun gnus-category-make-menu-bar ()
1093   (gnus-turn-off-edit-menu 'category)
1094   (unless (boundp 'gnus-category-menu)
1095     (easy-menu-define
1096      gnus-category-menu gnus-category-mode-map ""
1097      '("Categories"
1098        ["Add" gnus-category-add t]
1099        ["Kill" gnus-category-kill t]
1100        ["Copy" gnus-category-copy t]
1101        ["Edit predicate" gnus-category-edit-predicate t]
1102        ["Edit score" gnus-category-edit-score t]
1103        ["Edit groups" gnus-category-edit-groups t]
1104        ["Exit" gnus-category-exit t]))
1105
1106     (gnus-run-hooks 'gnus-category-menu-hook)))
1107
1108 (defun gnus-category-mode ()
1109   "Major mode for listing and editing agent categories.
1110
1111 All normal editing commands are switched off.
1112 \\<gnus-category-mode-map>
1113 For more in-depth information on this mode, read the manual
1114 (`\\[gnus-info-find-node]').
1115
1116 The following commands are available:
1117
1118 \\{gnus-category-mode-map}"
1119   (interactive)
1120   (when (gnus-visual-p 'category-menu 'menu)
1121     (gnus-category-make-menu-bar))
1122   (kill-all-local-variables)
1123   (gnus-simplify-mode-line)
1124   (setq major-mode 'gnus-category-mode)
1125   (setq mode-name "Category")
1126   (gnus-set-default-directory)
1127   (setq mode-line-process nil)
1128   (use-local-map gnus-category-mode-map)
1129   (buffer-disable-undo)
1130   (setq truncate-lines t)
1131   (setq buffer-read-only t)
1132   (gnus-run-hooks 'gnus-category-mode-hook))
1133
1134 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1135
1136 (defun gnus-category-insert-line (category)
1137   (let* ((gnus-tmp-name (car category))
1138          (gnus-tmp-groups (length (cadddr category))))
1139     (beginning-of-line)
1140     (gnus-add-text-properties
1141      (point)
1142      (prog1 (1+ (point))
1143        ;; Insert the text.
1144        (eval gnus-category-line-format-spec))
1145      (list 'gnus-category gnus-tmp-name))))
1146
1147 (defun gnus-enter-category-buffer ()
1148   "Go to the Category buffer."
1149   (interactive)
1150   (gnus-category-setup-buffer)
1151   (gnus-configure-windows 'category)
1152   (gnus-category-prepare))
1153
1154 (defun gnus-category-setup-buffer ()
1155   (unless (get-buffer gnus-category-buffer)
1156     (save-excursion
1157       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1158       (gnus-category-mode))))
1159
1160 (defun gnus-category-prepare ()
1161   (gnus-set-format 'category-mode)
1162   (gnus-set-format 'category t)
1163   (let ((alist gnus-category-alist)
1164         (buffer-read-only nil))
1165     (erase-buffer)
1166     (while alist
1167       (gnus-category-insert-line (pop alist)))
1168     (goto-char (point-min))
1169     (gnus-category-position-point)))
1170
1171 (defun gnus-category-name ()
1172   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1173       (error "No category on the current line")))
1174
1175 (defun gnus-category-read ()
1176   "Read the category alist."
1177   (setq gnus-category-alist
1178         (or (gnus-agent-read-file
1179              (nnheader-concat gnus-agent-directory "lib/categories"))
1180             (list (list 'default 'short nil nil)))))
1181
1182 (defun gnus-category-write ()
1183   "Write the category alist."
1184   (setq gnus-category-predicate-cache nil
1185         gnus-category-group-cache nil)
1186   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1187   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1188     (prin1 gnus-category-alist (current-buffer))))
1189
1190 (defun gnus-category-edit-predicate (category)
1191   "Edit the predicate for CATEGORY."
1192   (interactive (list (gnus-category-name)))
1193   (let ((info (assq category gnus-category-alist)))
1194     (gnus-edit-form
1195      (cadr info) (format "Editing the predicate for category %s" category)
1196      `(lambda (predicate)
1197         (setf (cadr (assq ',category gnus-category-alist)) predicate)
1198         (gnus-category-write)
1199         (gnus-category-list)))))
1200
1201 (defun gnus-category-edit-score (category)
1202   "Edit the score expression for CATEGORY."
1203   (interactive (list (gnus-category-name)))
1204   (let ((info (assq category gnus-category-alist)))
1205     (gnus-edit-form
1206      (caddr info)
1207      (format "Editing the score expression for category %s" category)
1208      `(lambda (groups)
1209         (setf (caddr (assq ',category gnus-category-alist)) groups)
1210         (gnus-category-write)
1211         (gnus-category-list)))))
1212
1213 (defun gnus-category-edit-groups (category)
1214   "Edit the group list for CATEGORY."
1215   (interactive (list (gnus-category-name)))
1216   (let ((info (assq category gnus-category-alist)))
1217     (gnus-edit-form
1218      (cadddr info) (format "Editing the group list for category %s" category)
1219      `(lambda (groups)
1220         (setf (cadddr (assq ',category gnus-category-alist)) groups)
1221         (gnus-category-write)
1222         (gnus-category-list)))))
1223
1224 (defun gnus-category-kill (category)
1225   "Kill the current category."
1226   (interactive (list (gnus-category-name)))
1227   (let ((info (assq category gnus-category-alist))
1228         (buffer-read-only nil))
1229     (gnus-delete-line)
1230     (gnus-category-write)
1231     (setq gnus-category-alist (delq info gnus-category-alist))))
1232
1233 (defun gnus-category-copy (category to)
1234   "Copy the current category."
1235   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1236   (let ((info (assq category gnus-category-alist)))
1237     (push (list to (gnus-copy-sequence (cadr info))
1238                 (gnus-copy-sequence (caddr info)) nil)
1239           gnus-category-alist)
1240     (gnus-category-write)
1241     (gnus-category-list)))
1242
1243 (defun gnus-category-add (category)
1244   "Create a new category."
1245   (interactive "SCategory name: ")
1246   (when (assq category gnus-category-alist)
1247     (error "Category %s already exists" category))
1248   (push (list category 'false nil nil)
1249         gnus-category-alist)
1250   (gnus-category-write)
1251   (gnus-category-list))
1252
1253 (defun gnus-category-list ()
1254   "List all categories."
1255   (interactive)
1256   (gnus-category-prepare))
1257
1258 (defun gnus-category-exit ()
1259   "Return to the group buffer."
1260   (interactive)
1261   (kill-buffer (current-buffer))
1262   (gnus-configure-windows 'group t))
1263
1264 ;; To avoid having 8-bit characters in the source file.
1265 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1266
1267 (defvar gnus-category-predicate-alist
1268   '((spam . gnus-agent-spam-p)
1269     (short . gnus-agent-short-p)
1270     (long . gnus-agent-long-p)
1271     (low . gnus-agent-low-scored-p)
1272     (high . gnus-agent-high-scored-p)
1273     (true . gnus-agent-true)
1274     (false . gnus-agent-false))
1275   "Mapping from short score predicate symbols to predicate functions.")
1276
1277 (defun gnus-agent-spam-p ()
1278   "Say whether an article is spam or not."
1279   (unless gnus-agent-spam-hashtb
1280     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1281   (if (not (equal (mail-header-references gnus-headers) ""))
1282       nil
1283     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1284       (prog1
1285           (gnus-gethash string gnus-agent-spam-hashtb)
1286         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1287
1288 (defun gnus-agent-short-p ()
1289   "Say whether an article is short or not."
1290   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1291
1292 (defun gnus-agent-long-p ()
1293   "Say whether an article is long or not."
1294   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1295
1296 (defun gnus-agent-low-scored-p ()
1297   "Say whether an article has a low score or not."
1298   (< gnus-score gnus-agent-low-score))
1299
1300 (defun gnus-agent-high-scored-p ()
1301   "Say whether an article has a high score or not."
1302   (> gnus-score gnus-agent-high-score))
1303
1304 (defun gnus-category-make-function (cat)
1305   "Make a function from category CAT."
1306   `(lambda () ,(gnus-category-make-function-1 cat)))
1307
1308 (defun gnus-agent-true ()
1309   "Return t."
1310   t)
1311
1312 (defun gnus-agent-false ()
1313   "Return nil."
1314   nil)
1315
1316 (defun gnus-category-make-function-1 (cat)
1317   "Make a function from category CAT."
1318   (cond
1319    ;; Functions are just returned as is.
1320    ((or (symbolp cat)
1321         (gnus-functionp cat))
1322     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1323            cat)))
1324    ;; More complex category.
1325    ((consp cat)
1326     `(,(cond
1327         ((memq (car cat) '(& and))
1328          'and)
1329         ((memq (car cat) '(| or))
1330          'or)
1331         ((memq (car cat) gnus-category-not)
1332          'not))
1333       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1334    (t
1335     (error "Unknown category type: %s" cat))))
1336
1337 (defun gnus-get-predicate (predicate)
1338   "Return the predicate for CATEGORY."
1339   (or (cdr (assoc predicate gnus-category-predicate-cache))
1340       (cdar (push (cons predicate
1341                         (gnus-category-make-function predicate))
1342                   gnus-category-predicate-cache))))
1343
1344 (defun gnus-group-category (group)
1345   "Return the category GROUP belongs to."
1346   (unless gnus-category-group-cache
1347     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1348     (let ((cs gnus-category-alist)
1349           groups cat)
1350       (while (setq cat (pop cs))
1351         (setq groups (cadddr cat))
1352         (while groups
1353           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1354   (or (gnus-gethash group gnus-category-group-cache)
1355       (assq 'default gnus-category-alist)))
1356
1357 (defun gnus-agent-expire ()
1358   "Expire all old articles."
1359   (interactive)
1360   (let ((methods gnus-agent-covered-methods)
1361         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1362         gnus-command-method sym group articles
1363         history overview file histories elem art nov-file low info
1364         unreads marked article orig lowest highest)
1365     (save-excursion
1366       (with-temp-buffer
1367         (insert-file-contents-as-coding-system gnus-agent-file-coding-system
1368                                                file)
1369         (gnus-active-to-gnus-format
1370          nil (setq orig (gnus-make-hashtable
1371                          (count-lines (point-min) (point-max))))))
1372       (setq overview (gnus-get-buffer-create " *expire overview*"))
1373       (while (setq gnus-command-method (pop methods))
1374         (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1375         (gnus-agent-open-history)
1376         (set-buffer
1377          (setq gnus-agent-current-history
1378                (setq history (gnus-agent-history-buffer))))
1379         (goto-char (point-min))
1380         (when (> (buffer-size) 1)
1381           (goto-char (point-min))
1382           (while (not (eobp))
1383             (skip-chars-forward "^\t")
1384             (if (> (read (current-buffer)) day)
1385                 ;; New article; we don't expire it.
1386                 (forward-line 1)
1387               ;; Old article.  Schedule it for possible nuking.
1388               (while (not (eolp))
1389                 (setq sym (let ((obarray expiry-hashtb))
1390                             (read (current-buffer))))
1391                 (if (boundp sym)
1392                     (set sym (cons (cons (read (current-buffer)) (point))
1393                                    (symbol-value sym)))
1394                   (set sym (list (cons (read (current-buffer)) (point)))))
1395                 (skip-chars-forward " "))
1396               (forward-line 1)))
1397           ;; We now have all articles that can possibly be expired.
1398           (mapatoms
1399            (lambda (sym)
1400              (setq group (symbol-name sym)
1401                    articles (sort (symbol-value sym) 'car-less-than-car)
1402                    low (car (gnus-active group))
1403                    info (gnus-get-info group)
1404                    unreads (ignore-errors (gnus-list-of-unread-articles group))
1405                    marked (nconc (gnus-uncompress-range
1406                                   (cdr (assq 'tick (gnus-info-marks info))))
1407                                  (gnus-uncompress-range
1408                                   (cdr (assq 'dormant
1409                                              (gnus-info-marks info)))))
1410                    nov-file (gnus-agent-article-name ".overview" group)
1411                    lowest nil
1412                    highest nil)
1413              (gnus-agent-load-alist group)
1414              (gnus-message 5 "Expiring articles in %s" group)
1415              (set-buffer overview)
1416              (erase-buffer)
1417              (when (file-exists-p nov-file)
1418                (nnheader-insert-file-contents nov-file))
1419              (goto-char (point-min))
1420              (setq article 0)
1421              (while (setq elem (pop articles))
1422                (setq article (car elem))
1423                (when (or (null low)
1424                          (< article low)
1425                          gnus-agent-expire-all
1426                          (and (not (memq article unreads))
1427                               (not (memq article marked))))
1428                  ;; Find and nuke the NOV line.
1429                  (while (and (not (eobp))
1430                              (or (not (numberp
1431                                        (setq art (read (current-buffer)))))
1432                                  (< art article)))
1433                    (if (file-exists-p
1434                         (gnus-agent-article-name
1435                          (number-to-string art) group))
1436                        (progn
1437                          (unless lowest
1438                            (setq lowest art))
1439                          (setq highest art)
1440                          (forward-line 1))
1441                      ;; Remove old NOV lines that have no articles.
1442                      (gnus-delete-line)))
1443                  (if (or (eobp)
1444                          (/= art article))
1445                      (beginning-of-line)
1446                    (gnus-delete-line))
1447                  ;; Nuke the article.
1448                  (when (file-exists-p (setq file (gnus-agent-article-name
1449                                                   (number-to-string article)
1450                                                   group)))
1451                    (delete-file file))
1452                  ;; Schedule the history line for nuking.
1453                  (push (cdr elem) histories)))
1454              (gnus-make-directory (file-name-directory nov-file))
1455              (write-region-as-coding-system
1456               gnus-agent-file-coding-system
1457               (point-min) (point-max) nov-file nil 'silent)
1458              ;; Delete the unwanted entries in the alist.
1459              (setq gnus-agent-article-alist
1460                    (sort gnus-agent-article-alist 'car-less-than-car))
1461              (let* ((alist gnus-agent-article-alist)
1462                     (prev (cons nil alist))
1463                     (first prev)
1464                     expired)
1465                (while (and alist
1466                            (<= (caar alist) article))
1467                  (if (or (not (cdar alist))
1468                          (not (file-exists-p
1469                                (gnus-agent-article-name
1470                                 (number-to-string
1471                                  (caar alist))
1472                                 group))))
1473                      (progn
1474                        (push (caar alist) expired)
1475                        (setcdr prev (setq alist (cdr alist))))
1476                    (setq prev alist
1477                          alist (cdr alist))))
1478                (setq gnus-agent-article-alist (cdr first))
1479                (gnus-agent-save-alist group)
1480                ;; Mark all articles up to the first article
1481                ;; in `gnus-article-alist' as read.
1482                (when (and info (caar gnus-agent-article-alist))
1483                  (setcar (nthcdr 2 info)
1484                          (gnus-range-add
1485                           (nth 2 info)
1486                           (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1487                ;; Maybe everything has been expired from `gnus-article-alist'
1488                ;; and so the above marking as read could not be conducted,
1489                ;; or there are expired article within the range of the alist.
1490                (when (and info
1491                           expired
1492                           (or (not (caar gnus-agent-article-alist))
1493                               (> (car expired)
1494                                  (caar gnus-agent-article-alist))))
1495                  (setcar (nthcdr 2 info)
1496                          (gnus-add-to-range
1497                           (nth 2 info)
1498                           (nreverse expired))))
1499                (gnus-dribble-enter
1500                 (concat "(gnus-group-set-info '"
1501                         (gnus-prin1-to-string info)
1502                         ")")))
1503              (when lowest
1504                (if (gnus-gethash group orig)
1505                    (setcar (gnus-gethash group orig) lowest)
1506                  (gnus-sethash group (cons lowest highest) orig))))
1507            expiry-hashtb)
1508           (set-buffer history)
1509           (setq histories (nreverse (sort histories '<)))
1510           (while histories
1511             (goto-char (pop histories))
1512             (gnus-delete-line))
1513           (gnus-agent-save-history)
1514           (gnus-agent-close-history)
1515           (gnus-write-active-file-as-coding-system
1516            gnus-agent-file-coding-system
1517            (gnus-agent-lib-file "active") orig))
1518         (gnus-message 4 "Expiry...done"))))))
1519
1520 ;;;###autoload
1521 (defun gnus-agent-batch ()
1522   (interactive)
1523   (let ((init-file-user "")
1524         (gnus-always-read-dribble-file t))
1525     (gnus))
1526   (gnus-group-send-drafts)
1527   (gnus-agent-fetch-session))
1528
1529 (provide 'gnus-agent)
1530
1531 ;;; gnus-agent.el ends here