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