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