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