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