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