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