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