7eb4fe9a51265bf6d8fe64d5983540ae7e437860
[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       (let ((articles (append gnus-newsgroup-unreads
659                               gnus-newsgroup-marked
660                               gnus-newsgroup-dormant))
661             article)
662         (while (setq article (pop articles))
663           (unless (or (cdr (assq article gnus-agent-article-alist))
664                       (memq article gnus-newsgroup-downloadable)
665                       (memq article gnus-newsgroup-cached))
666             (push article gnus-newsgroup-undownloaded))))
667       ;; Then mark downloaded downloadable as not-downloadable,
668       ;; if you get my drift.
669       (let ((articles gnus-newsgroup-downloadable)
670             article)
671         (while (setq article (pop articles))
672           (when (cdr (assq article gnus-agent-article-alist))
673             (setq gnus-newsgroup-downloadable
674                   (delq article gnus-newsgroup-downloadable))))))))
675
676 (defun gnus-agent-catchup ()
677   "Mark all undownloaded articles as read."
678   (interactive)
679   (save-excursion
680     (while gnus-newsgroup-undownloaded
681       (gnus-summary-mark-article
682        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
683   (gnus-summary-position-point))
684
685 ;;;
686 ;;; Internal functions
687 ;;;
688
689 (defun gnus-agent-save-active (method)
690   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
691
692 (defun gnus-agent-save-active-1 (method function)
693   (when (gnus-agent-method-p method)
694     (let* ((gnus-command-method method)
695            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
696            (file (gnus-agent-lib-file "active")))
697       (funcall function nil new)
698       (gnus-agent-write-active file new)
699       (erase-buffer)
700       (insert-file-contents-as-coding-system gnus-agent-file-coding-system
701                                              file))))
702
703 (defun gnus-agent-write-active (file new)
704   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
705         (file (gnus-agent-lib-file "active"))
706         elem osym)
707     (when (file-exists-p file)
708       (with-temp-buffer
709         (insert-file-contents-as-coding-system gnus-agent-file-coding-system
710                                                file)
711         (gnus-active-to-gnus-format nil orig))
712       (mapatoms
713        (lambda (sym)
714          (when (and sym (boundp sym))
715            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
716                     (setq elem (symbol-value osym)))
717                (setcdr elem (cdr (symbol-value sym)))
718              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
719        new))
720     (gnus-make-directory (file-name-directory file))
721     ;; The hashtable contains real names of groups,  no more prefix
722     ;; removing, so set `full' to `t'.
723     (gnus-write-active-file file orig t)))
724
725 (defun gnus-agent-save-groups (method)
726   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
727
728 (defun gnus-agent-save-group-info (method group active)
729   (when (gnus-agent-method-p method)
730     (let* ((gnus-command-method method)
731            (coding-system-for-write nnheader-file-coding-system)
732            (output-coding-system nnheader-file-coding-system)
733            (file-name-coding-system nnmail-pathname-coding-system)
734            (pathname-coding-system nnmail-pathname-coding-system)
735            (file (gnus-agent-lib-file "active"))
736            oactive)
737       (gnus-make-directory (file-name-directory file))
738       (with-temp-file file
739         (when (file-exists-p file)
740           (nnheader-insert-file-contents file))
741         (goto-char (point-min))
742         (when (re-search-forward
743                (concat "^" (regexp-quote group) " ") nil t)
744           (save-excursion
745             (save-restriction
746               (narrow-to-region (match-beginning 0)
747                                 (progn
748                                   (forward-line 1)
749                                   (point)))
750               (setq oactive (car (nnmail-parse-active)))))
751           (gnus-delete-line))
752         (insert (format "%S %d %d y\n" (intern group)
753                         (cdr active)
754                         (or (car oactive) (car active))))
755         (goto-char (point-max))
756         (while (search-backward "\\." nil t)
757           (delete-char 1))))))
758
759 (defun gnus-agent-group-path (group)
760   "Translate GROUP into a path."
761   (if nnmail-use-long-file-names
762       (gnus-group-real-name group)
763     (nnheader-translate-file-chars
764      (nnheader-replace-chars-in-string
765       (nnheader-replace-duplicate-chars-in-string
766        (nnheader-replace-chars-in-string
767         (gnus-group-real-name group)
768         ?/ ?_)
769        ?. ?_)
770       ?. ?/))))
771
772 \f
773
774 (defun gnus-agent-method-p (method)
775   "Say whether METHOD is covered by the agent."
776   (member method gnus-agent-covered-methods))
777
778 (defun gnus-agent-get-function (method)
779   (if (and (not gnus-plugged)
780            (gnus-agent-method-p method))
781       (progn
782         (require 'nnagent)
783         'nnagent)
784     (car method)))
785
786 ;;; History functions
787
788 (defun gnus-agent-history-buffer ()
789   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
790
791 (defun gnus-agent-open-history ()
792   (save-excursion
793     (push (cons (gnus-agent-method)
794                 (set-buffer (gnus-get-buffer-create
795                              (format " *Gnus agent %s history*"
796                                      (gnus-agent-method)))))
797           gnus-agent-history-buffers)
798     (erase-buffer)
799     (insert "\n")
800     (let ((file (gnus-agent-lib-file "history")))
801       (when (file-exists-p file)
802         (nnheader-insert-file-contents file))
803       (set (make-local-variable 'gnus-agent-file-name) file))))
804
805 (defun gnus-agent-save-history ()
806   (save-excursion
807     (set-buffer gnus-agent-current-history)
808     (gnus-make-directory (file-name-directory gnus-agent-file-name))
809     (write-region-as-coding-system
810      gnus-agent-file-coding-system
811      (1+ (point-min)) (point-max) gnus-agent-file-name nil 'silent)))
812
813 (defun gnus-agent-close-history ()
814   (when (gnus-buffer-live-p gnus-agent-current-history)
815     (kill-buffer gnus-agent-current-history)
816     (setq gnus-agent-history-buffers
817           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
818                 gnus-agent-history-buffers))))
819
820 (defun gnus-agent-enter-history (id group-arts date)
821   (save-excursion
822     (set-buffer gnus-agent-current-history)
823     (goto-char (point-max))
824     (let ((p (point)))
825       (insert id "\t" (number-to-string date) "\t")
826       (while group-arts
827         (insert (format "%S" (intern (caar group-arts)))
828                 " " (number-to-string (cdr (pop group-arts)))
829                 " "))
830       (insert "\n")
831       (while (search-backward "\\." p t)
832         (delete-char 1)))))
833
834 (defun gnus-agent-article-in-history-p (id)
835   (save-excursion
836     (set-buffer (gnus-agent-history-buffer))
837     (goto-char (point-min))
838     (search-forward (concat "\n" id "\t") nil t)))
839
840 (defun gnus-agent-history-path (id)
841   (save-excursion
842     (set-buffer (gnus-agent-history-buffer))
843     (goto-char (point-min))
844     (when (search-forward (concat "\n" id "\t") nil t)
845       (let ((method (gnus-agent-method)))
846         (let (paths group)
847           (while (not (numberp (setq group (read (current-buffer)))))
848             (push (concat method "/" group) paths))
849           (nreverse paths))))))
850
851 ;;;
852 ;;; Fetching
853 ;;;
854
855 (defun gnus-agent-fetch-articles (group articles)
856   "Fetch ARTICLES from GROUP and put them into the Agent."
857   (when articles
858     ;; Prune off articles that we have already fetched.
859     (while (and articles
860                 (cdr (assq (car articles) gnus-agent-article-alist)))
861       (pop articles))
862     (let ((arts articles))
863       (while (cdr arts)
864         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
865             (setcdr arts (cddr arts))
866           (setq arts (cdr arts)))))
867     (when articles
868       (let ((dir (concat
869                   (gnus-agent-directory)
870                   (gnus-agent-group-path group) "/"))
871             (date (time-to-days (current-time)))
872             (case-fold-search t)
873             pos crosses id elem)
874         (gnus-make-directory dir)
875         (gnus-message 7 "Fetching articles for %s..." group)
876         ;; Fetch the articles from the backend.
877         (if (gnus-check-backend-function 'retrieve-articles group)
878             (setq pos (gnus-retrieve-articles articles group))
879           (with-temp-buffer
880             (let (article)
881               (while (setq article (pop articles))
882                 (when (or
883                        (gnus-backlog-request-article group article
884                                                      nntp-server-buffer)
885                        (gnus-request-article article group))
886                   (goto-char (point-max))
887                   (push (cons article (point)) pos)
888                   (insert-buffer-substring nntp-server-buffer)))
889               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
890               (setq pos (nreverse pos)))))
891         ;; Then save these articles into the Agent.
892         (save-excursion
893           (set-buffer nntp-server-buffer)
894           (while pos
895             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
896             (goto-char (point-min))
897             (when (search-forward "\n\n" nil t)
898               (when (search-backward "\nXrefs: " nil t)
899                 ;; Handle crossposting.
900                 (skip-chars-forward "^ ")
901                 (skip-chars-forward " ")
902                 (setq crosses nil)
903                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
904                   (push (cons (buffer-substring (match-beginning 1)
905                                                 (match-end 1))
906                               (buffer-substring (match-beginning 2)
907                                                 (match-end 2)))
908                         crosses)
909                   (goto-char (match-end 0)))
910                 (gnus-agent-crosspost crosses (caar pos))))
911             (goto-char (point-min))
912             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
913                 (setq id "No-Message-ID-in-article")
914               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
915             (write-region-as-coding-system
916              gnus-agent-file-coding-system
917              (point-min) (point-max)
918              (concat dir (number-to-string (caar pos))) nil 'silent)
919             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
920               (setcdr elem t))
921             (gnus-agent-enter-history
922              id (or crosses (list (cons group (caar pos)))) date)
923             (widen)
924             (pop pos)))
925         (gnus-agent-save-alist group)))))
926
927 (defun gnus-agent-crosspost (crosses article)
928   (let (gnus-agent-article-alist group alist beg end)
929     (save-excursion
930       (set-buffer gnus-agent-overview-buffer)
931       (when (nnheader-find-nov-line article)
932         (forward-word 1)
933         (setq beg (point))
934         (setq end (progn (forward-line 1) (point)))))
935     (while crosses
936       (setq group (caar crosses))
937       (unless (setq alist (assoc group gnus-agent-group-alist))
938         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
939               gnus-agent-group-alist))
940       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
941       (save-excursion
942         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
943                                                     group)))
944         (when (= (point-max) (point-min))
945           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
946           (ignore-errors
947             (nnheader-insert-file-contents
948              (gnus-agent-article-name ".overview" group))))
949         (nnheader-find-nov-line (string-to-number (cdar crosses)))
950         (insert (string-to-number (cdar crosses)))
951         (insert-buffer-substring gnus-agent-overview-buffer beg end))
952       (pop crosses))))
953
954 (defun gnus-agent-flush-cache ()
955   (save-excursion
956     (while gnus-agent-buffer-alist
957       (set-buffer (cdar gnus-agent-buffer-alist))
958       (write-region-as-coding-system
959        gnus-agent-file-coding-system
960        (point-min) (point-max)
961        (gnus-agent-article-name ".overview"
962                                 (caar gnus-agent-buffer-alist))
963        nil 'silent)
964       (pop gnus-agent-buffer-alist))
965     (while gnus-agent-group-alist
966       (with-temp-file (caar gnus-agent-group-alist)
967         (princ (cdar gnus-agent-group-alist))
968         (insert "\n"))
969       (pop gnus-agent-group-alist))))
970
971 (defun gnus-agent-fetch-headers (group &optional force)
972   (let* ((articles (gnus-list-of-unread-articles group))
973          (len (length articles))
974          (gnus-decode-encoded-word-function 'identity)
975          (file (gnus-agent-article-name ".overview" group))
976          i)
977     ;; Check the number of articles is not too large.
978     (when (and (integerp gnus-agent-large-newsgroup)
979                (< 0 gnus-agent-large-newsgroup))
980       (and (< 0 (setq i (- len gnus-agent-large-newsgroup)))
981            (setq articles (nthcdr i articles))))
982     ;; add article with marks to list of article headers we want to fetch.
983     (dolist (arts (gnus-info-marks (gnus-get-info group)))
984       (setq articles (gnus-union (gnus-uncompress-sequence (cdr arts))
985                                  articles)))
986     (setq articles (sort articles '<))
987     ;; Remove known articles.
988     (when (gnus-agent-load-alist group)
989       (setq articles (gnus-sorted-intersection
990                       articles
991                       (gnus-uncompress-range
992                        (cons (1+ (caar (last gnus-agent-article-alist)))
993                              (cdr (gnus-active group)))))))
994     ;; Fetch them.
995     (gnus-make-directory (nnheader-translate-file-chars
996                           (file-name-directory file) t))
997     (when articles
998       (gnus-message 7 "Fetching headers for %s..." group)
999       (save-excursion
1000         (set-buffer nntp-server-buffer)
1001         (unless (eq 'nov (gnus-retrieve-headers articles group))
1002           (nnvirtual-convert-headers))
1003         ;; Save these headers for later processing.
1004         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1005         (when (file-exists-p file)
1006           (gnus-agent-braid-nov group articles file))
1007         (write-region-as-coding-system
1008          gnus-agent-file-coding-system
1009          (point-min) (point-max) file nil 'silent)
1010         (gnus-agent-save-alist group articles nil)
1011         (gnus-agent-enter-history
1012          "last-header-fetched-for-session"
1013          (list (cons group (nth (- (length  articles) 1) articles)))
1014          (time-to-days (current-time)))
1015         articles))))
1016
1017 (defsubst gnus-agent-copy-nov-line (article)
1018   (let (b e)
1019     (set-buffer gnus-agent-overview-buffer)
1020     (setq b (point))
1021     (if (eq article (read (current-buffer)))
1022         (setq e (progn (forward-line 1) (point)))
1023       (progn
1024         (beginning-of-line)
1025         (setq e b)))
1026     (set-buffer nntp-server-buffer)
1027     (insert-buffer-substring gnus-agent-overview-buffer b e)))
1028
1029 (defun gnus-agent-braid-nov (group articles file)
1030   (set-buffer gnus-agent-overview-buffer)
1031   (goto-char (point-min))
1032   (set-buffer nntp-server-buffer)
1033   (erase-buffer)
1034   (nnheader-insert-file-contents file)
1035   (goto-char (point-max))
1036   (if (or (= (point-min) (point-max))
1037           (progn
1038             (forward-line -1)
1039             (< (read (current-buffer)) (car articles))))
1040       ;; We have only headers that are after the older headers,
1041       ;; so we just append them.
1042       (progn
1043         (goto-char (point-max))
1044         (insert-buffer-substring gnus-agent-overview-buffer))
1045     ;; We do it the hard way.
1046     (nnheader-find-nov-line (car articles))
1047     (gnus-agent-copy-nov-line (car articles))
1048     (pop articles)
1049     (while (and articles
1050                 (not (eobp)))
1051       (while (and (not (eobp))
1052                   (< (read (current-buffer)) (car articles)))
1053         (forward-line 1))
1054       (beginning-of-line)
1055       (unless (eobp)
1056         (gnus-agent-copy-nov-line (car articles))
1057         (setq articles (cdr articles))))
1058     (when articles
1059       (let (b e)
1060         (set-buffer gnus-agent-overview-buffer)
1061         (setq b (point)
1062               e (point-max))
1063         (set-buffer nntp-server-buffer)
1064         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
1065
1066 (defun gnus-agent-load-alist (group &optional dir)
1067   "Load the article-state alist for GROUP."
1068   (setq gnus-agent-article-alist
1069         (gnus-agent-read-file
1070          (if dir
1071              (expand-file-name ".agentview" dir)
1072            (gnus-agent-article-name ".agentview" group)))))
1073
1074 (defun gnus-agent-save-alist (group &optional articles state dir)
1075   "Save the article-state alist for GROUP."
1076   (let ((file-name-coding-system nnmail-pathname-coding-system)
1077         (pathname-coding-system nnmail-pathname-coding-system))
1078     (with-temp-file (if dir
1079                         (expand-file-name ".agentview" dir)
1080                       (gnus-agent-article-name ".agentview" group))
1081       (princ (setq gnus-agent-article-alist
1082                    (nconc gnus-agent-article-alist
1083                           (mapcar (lambda (article) (cons article state))
1084                                   articles)))
1085              (current-buffer))
1086       (insert "\n"))))
1087
1088 (defun gnus-agent-article-name (article group)
1089   (expand-file-name (if (stringp article) article (string-to-number article))
1090                     (file-name-as-directory
1091                      (expand-file-name (gnus-agent-group-path group)
1092                                        (gnus-agent-directory)))))
1093
1094 ;;;###autoload
1095 (defun gnus-agent-batch-fetch ()
1096   "Start Gnus and fetch session."
1097   (interactive)
1098   (gnus)
1099   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1100     (gnus-agent-fetch-session))
1101   (gnus-group-exit))
1102
1103 (defun gnus-agent-fetch-session ()
1104   "Fetch all articles and headers that are eligible for fetching."
1105   (interactive)
1106   (unless gnus-agent-covered-methods
1107     (error "No servers are covered by the Gnus agent"))
1108   (unless gnus-plugged
1109     (error "Can't fetch articles while Gnus is unplugged"))
1110   (let ((methods gnus-agent-covered-methods)
1111         groups group gnus-command-method)
1112     (save-excursion
1113       (while methods
1114         (condition-case err
1115             (progn
1116               (setq gnus-command-method (car methods))
1117               (when (or (gnus-server-opened gnus-command-method)
1118                         (gnus-open-server gnus-command-method))
1119                 (setq groups (gnus-groups-from-server (car methods)))
1120                 (gnus-agent-with-fetch
1121                   (while (setq group (pop groups))
1122                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1123                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1124           (error
1125            (unless (funcall gnus-agent-confirmation-function
1126                             (format "Error (%s).  Continue? " err))
1127              (error "Cannot fetch articles into the Gnus agent.")))
1128           (quit
1129            (unless (funcall gnus-agent-confirmation-function
1130                             (format "Quit fetching session (%s).  Continue? "
1131                                     err))
1132              (signal 'quit "Cannot fetch articles into the Gnus agent."))))
1133         (pop methods))
1134       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1135
1136 (defun gnus-agent-fetch-group-1 (group method)
1137   "Fetch GROUP."
1138   (let ((gnus-command-method method)
1139         (gnus-newsgroup-name group)
1140         gnus-newsgroup-dependencies gnus-newsgroup-headers
1141         gnus-newsgroup-scored gnus-headers gnus-score
1142         gnus-use-cache articles arts
1143         category predicate info marks score-param
1144         (gnus-summary-expunge-below gnus-summary-expunge-below)
1145         (gnus-summary-mark-below gnus-summary-mark-below)
1146         (gnus-orphan-score gnus-orphan-score)
1147         ;; Maybe some other gnus-summary local variables should also
1148         ;; be put here.
1149         )
1150     (unless (gnus-check-group group)
1151       (error "Can't open server for %s" group))
1152     ;; Fetch headers.
1153     (when (and (or (gnus-active group) (gnus-activate-group group))
1154                (setq articles (gnus-agent-fetch-headers group))
1155                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1156                  ;; Parse them and see which articles we want to fetch.
1157                  (setq gnus-newsgroup-dependencies
1158                        (make-vector (length articles) 0))
1159                  (setq gnus-newsgroup-headers
1160                        (gnus-get-newsgroup-headers-xover articles nil nil
1161                                                          group))
1162                  ;; `gnus-agent-overview-buffer' may be killed for
1163                  ;; timeout reason.  If so, recreate it.
1164                  (gnus-agent-create-buffer)))
1165       (setq category (gnus-group-category group))
1166       (setq predicate
1167             (gnus-get-predicate
1168              (or (gnus-group-find-parameter group 'agent-predicate t)
1169                  (cadr category))))
1170       (if (memq (caaddr predicate) '(gnus-agent-true gnus-agent-false))
1171           ;; Simple implementation
1172           (setq arts
1173                 (and (eq (caaddr predicate) 'gnus-agent-true) articles))
1174         (setq arts nil)
1175         (setq score-param
1176               (or (gnus-group-get-parameter group 'agent-score t)
1177                   (caddr category)))
1178         ;; Translate score-param into real one
1179         (cond
1180          ((not score-param))
1181          ((eq score-param 'file)
1182           (setq score-param (gnus-all-score-files group)))
1183          ((stringp (car score-param)))
1184          (t
1185           (setq score-param (list (list score-param)))))
1186         (when score-param
1187           (gnus-score-headers score-param))
1188         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1189           (setq gnus-score
1190                 (or (cdr (assq (mail-header-number gnus-headers)
1191                                gnus-newsgroup-scored))
1192                     gnus-summary-default-score))
1193           (when (funcall predicate)
1194             (push (mail-header-number gnus-headers)
1195                   arts))))
1196       ;; Fetch the articles.
1197       (when arts
1198         (gnus-agent-fetch-articles group arts)))
1199     ;; Perhaps we have some additional articles to fetch.
1200     (setq arts (assq 'download (gnus-info-marks
1201                                 (setq info (gnus-get-info group)))))
1202     (when (cdr arts)
1203       (gnus-agent-fetch-articles
1204        group (gnus-uncompress-range (cdr arts)))
1205       (setq marks (delq arts (gnus-info-marks info)))
1206       (gnus-info-set-marks info marks)
1207       (gnus-dribble-enter
1208        (concat "(gnus-group-set-info '"
1209                (gnus-prin1-to-string info)
1210                ")")))))
1211
1212 ;;;
1213 ;;; Agent Category Mode
1214 ;;;
1215
1216 (defvar gnus-category-mode-hook nil
1217   "Hook run in `gnus-category-mode' buffers.")
1218
1219 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1220   "Format of category lines.")
1221
1222 (defvar gnus-category-mode-line-format "Gnus: %%b"
1223   "The format specification for the category mode line.")
1224
1225 (defvar gnus-agent-short-article 100
1226   "Articles that have fewer lines than this are short.")
1227
1228 (defvar gnus-agent-long-article 200
1229   "Articles that have more lines than this are long.")
1230
1231 (defvar gnus-agent-low-score 0
1232   "Articles that have a score lower than this have a low score.")
1233
1234 (defvar gnus-agent-high-score 0
1235   "Articles that have a score higher than this have a high score.")
1236
1237
1238 ;;; Internal variables.
1239
1240 (defvar gnus-category-buffer "*Agent Category*")
1241
1242 (defvar gnus-category-line-format-alist
1243   `((?c gnus-tmp-name ?s)
1244     (?g gnus-tmp-groups ?d)))
1245
1246 (defvar gnus-category-mode-line-format-alist
1247   `((?u user-defined ?s)))
1248
1249 (defvar gnus-category-line-format-spec nil)
1250 (defvar gnus-category-mode-line-format-spec nil)
1251
1252 (defvar gnus-category-mode-map nil)
1253 (put 'gnus-category-mode 'mode-class 'special)
1254
1255 (unless gnus-category-mode-map
1256   (setq gnus-category-mode-map (make-sparse-keymap))
1257   (suppress-keymap gnus-category-mode-map)
1258
1259   (gnus-define-keys gnus-category-mode-map
1260     "q" gnus-category-exit
1261     "k" gnus-category-kill
1262     "c" gnus-category-copy
1263     "a" gnus-category-add
1264     "p" gnus-category-edit-predicate
1265     "g" gnus-category-edit-groups
1266     "s" gnus-category-edit-score
1267     "l" gnus-category-list
1268
1269     "\C-c\C-i" gnus-info-find-node
1270     "\C-c\C-b" gnus-bug))
1271
1272 (defvar gnus-category-menu-hook nil
1273   "*Hook run after the creation of the menu.")
1274
1275 (defun gnus-category-make-menu-bar ()
1276   (gnus-turn-off-edit-menu 'category)
1277   (unless (boundp 'gnus-category-menu)
1278     (easy-menu-define
1279      gnus-category-menu gnus-category-mode-map ""
1280      '("Categories"
1281        ["Add" gnus-category-add t]
1282        ["Kill" gnus-category-kill t]
1283        ["Copy" gnus-category-copy t]
1284        ["Edit predicate" gnus-category-edit-predicate t]
1285        ["Edit score" gnus-category-edit-score t]
1286        ["Edit groups" gnus-category-edit-groups t]
1287        ["Exit" gnus-category-exit t]))
1288
1289     (gnus-run-hooks 'gnus-category-menu-hook)))
1290
1291 (defun gnus-category-mode ()
1292   "Major mode for listing and editing agent categories.
1293
1294 All normal editing commands are switched off.
1295 \\<gnus-category-mode-map>
1296 For more in-depth information on this mode, read the manual
1297 (`\\[gnus-info-find-node]').
1298
1299 The following commands are available:
1300
1301 \\{gnus-category-mode-map}"
1302   (interactive)
1303   (when (gnus-visual-p 'category-menu 'menu)
1304     (gnus-category-make-menu-bar))
1305   (kill-all-local-variables)
1306   (gnus-simplify-mode-line)
1307   (setq major-mode 'gnus-category-mode)
1308   (setq mode-name "Category")
1309   (gnus-set-default-directory)
1310   (setq mode-line-process nil)
1311   (use-local-map gnus-category-mode-map)
1312   (buffer-disable-undo)
1313   (setq truncate-lines t)
1314   (setq buffer-read-only t)
1315   (gnus-run-hooks 'gnus-category-mode-hook))
1316
1317 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1318
1319 (defun gnus-category-insert-line (category)
1320   (let* ((gnus-tmp-name (car category))
1321          (gnus-tmp-groups (length (cadddr category))))
1322     (beginning-of-line)
1323     (gnus-add-text-properties
1324      (point)
1325      (prog1 (1+ (point))
1326        ;; Insert the text.
1327        (eval gnus-category-line-format-spec))
1328      (list 'gnus-category gnus-tmp-name))))
1329
1330 (defun gnus-enter-category-buffer ()
1331   "Go to the Category buffer."
1332   (interactive)
1333   (gnus-category-setup-buffer)
1334   (gnus-configure-windows 'category)
1335   (gnus-category-prepare))
1336
1337 (defun gnus-category-setup-buffer ()
1338   (unless (get-buffer gnus-category-buffer)
1339     (save-excursion
1340       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1341       (gnus-category-mode))))
1342
1343 (defun gnus-category-prepare ()
1344   (gnus-set-format 'category-mode)
1345   (gnus-set-format 'category t)
1346   (let ((alist gnus-category-alist)
1347         (buffer-read-only nil))
1348     (erase-buffer)
1349     (while alist
1350       (gnus-category-insert-line (pop alist)))
1351     (goto-char (point-min))
1352     (gnus-category-position-point)))
1353
1354 (defun gnus-category-name ()
1355   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1356       (error "No category on the current line")))
1357
1358 (defun gnus-category-read ()
1359   "Read the category alist."
1360   (setq gnus-category-alist
1361         (or (gnus-agent-read-file
1362              (nnheader-concat gnus-agent-directory "lib/categories"))
1363             (list (list 'default 'short nil nil)))))
1364
1365 (defun gnus-category-write ()
1366   "Write the category alist."
1367   (setq gnus-category-predicate-cache nil
1368         gnus-category-group-cache nil)
1369   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1370   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1371     (prin1 gnus-category-alist (current-buffer))))
1372
1373 (defun gnus-category-edit-predicate (category)
1374   "Edit the predicate for CATEGORY."
1375   (interactive (list (gnus-category-name)))
1376   (let ((info (assq category gnus-category-alist)))
1377     (gnus-edit-form
1378      (cadr info) (format "Editing the predicate for category %s" category)
1379      `(lambda (predicate)
1380         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1381         (gnus-category-write)
1382         (gnus-category-list)))))
1383
1384 (defun gnus-category-edit-score (category)
1385   "Edit the score expression for CATEGORY."
1386   (interactive (list (gnus-category-name)))
1387   (let ((info (assq category gnus-category-alist)))
1388     (gnus-edit-form
1389      (caddr info)
1390      (format "Editing the score expression for category %s" category)
1391      `(lambda (groups)
1392         (setcar (nthcdr 2 (assq ',category gnus-category-alist)) groups)
1393         (gnus-category-write)
1394         (gnus-category-list)))))
1395
1396 (defun gnus-category-edit-groups (category)
1397   "Edit the group list for CATEGORY."
1398   (interactive (list (gnus-category-name)))
1399   (let ((info (assq category gnus-category-alist)))
1400     (gnus-edit-form
1401      (cadddr info) (format "Editing the group list for category %s" category)
1402      `(lambda (groups)
1403         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1404         (gnus-category-write)
1405         (gnus-category-list)))))
1406
1407 (defun gnus-category-kill (category)
1408   "Kill the current category."
1409   (interactive (list (gnus-category-name)))
1410   (let ((info (assq category gnus-category-alist))
1411         (buffer-read-only nil))
1412     (gnus-delete-line)
1413     (setq gnus-category-alist (delq info gnus-category-alist))
1414     (gnus-category-write)))
1415
1416 (defun gnus-category-copy (category to)
1417   "Copy the current category."
1418   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1419   (let ((info (assq category gnus-category-alist)))
1420     (push (list to (gnus-copy-sequence (cadr info))
1421                 (gnus-copy-sequence (caddr info)) nil)
1422           gnus-category-alist)
1423     (gnus-category-write)
1424     (gnus-category-list)))
1425
1426 (defun gnus-category-add (category)
1427   "Create a new category."
1428   (interactive "SCategory name: ")
1429   (when (assq category gnus-category-alist)
1430     (error "Category %s already exists" category))
1431   (push (list category 'false nil nil)
1432         gnus-category-alist)
1433   (gnus-category-write)
1434   (gnus-category-list))
1435
1436 (defun gnus-category-list ()
1437   "List all categories."
1438   (interactive)
1439   (gnus-category-prepare))
1440
1441 (defun gnus-category-exit ()
1442   "Return to the group buffer."
1443   (interactive)
1444   (kill-buffer (current-buffer))
1445   (gnus-configure-windows 'group t))
1446
1447 ;; To avoid having 8-bit characters in the source file.
1448 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1449
1450 (defvar gnus-category-predicate-alist
1451   '((spam . gnus-agent-spam-p)
1452     (short . gnus-agent-short-p)
1453     (long . gnus-agent-long-p)
1454     (low . gnus-agent-low-scored-p)
1455     (high . gnus-agent-high-scored-p)
1456     (true . gnus-agent-true)
1457     (false . gnus-agent-false))
1458   "Mapping from short score predicate symbols to predicate functions.")
1459
1460 (defun gnus-agent-spam-p ()
1461   "Say whether an article is spam or not."
1462   (unless gnus-agent-spam-hashtb
1463     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1464   (if (not (equal (mail-header-references gnus-headers) ""))
1465       nil
1466     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1467       (prog1
1468           (gnus-gethash string gnus-agent-spam-hashtb)
1469         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1470
1471 (defun gnus-agent-short-p ()
1472   "Say whether an article is short or not."
1473   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1474
1475 (defun gnus-agent-long-p ()
1476   "Say whether an article is long or not."
1477   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1478
1479 (defun gnus-agent-low-scored-p ()
1480   "Say whether an article has a low score or not."
1481   (< gnus-score gnus-agent-low-score))
1482
1483 (defun gnus-agent-high-scored-p ()
1484   "Say whether an article has a high score or not."
1485   (> gnus-score gnus-agent-high-score))
1486
1487 (defun gnus-category-make-function (cat)
1488   "Make a function from category CAT."
1489   `(lambda () ,(gnus-category-make-function-1 cat)))
1490
1491 (defun gnus-agent-true ()
1492   "Return t."
1493   t)
1494
1495 (defun gnus-agent-false ()
1496   "Return nil."
1497   nil)
1498
1499 (defun gnus-category-make-function-1 (cat)
1500   "Make a function from category CAT."
1501   (cond
1502    ;; Functions are just returned as is.
1503    ((or (symbolp cat)
1504         (gnus-functionp cat))
1505     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1506            cat)))
1507    ;; More complex category.
1508    ((consp cat)
1509     `(,(cond
1510         ((memq (car cat) '(& and))
1511          'and)
1512         ((memq (car cat) '(| or))
1513          'or)
1514         ((memq (car cat) gnus-category-not)
1515          'not))
1516       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1517    (t
1518     (error "Unknown category type: %s" cat))))
1519
1520 (defun gnus-get-predicate (predicate)
1521   "Return the predicate for CATEGORY."
1522   (or (cdr (assoc predicate gnus-category-predicate-cache))
1523       (cdar (push (cons predicate
1524                         (gnus-category-make-function predicate))
1525                   gnus-category-predicate-cache))))
1526
1527 (defun gnus-group-category (group)
1528   "Return the category GROUP belongs to."
1529   (unless gnus-category-group-cache
1530     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1531     (let ((cs gnus-category-alist)
1532           groups cat)
1533       (while (setq cat (pop cs))
1534         (setq groups (cadddr cat))
1535         (while groups
1536           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1537   (or (gnus-gethash group gnus-category-group-cache)
1538       (assq 'default gnus-category-alist)))
1539
1540 (defun gnus-agent-expire ()
1541   "Expire all old articles."
1542   (interactive)
1543   (let ((methods gnus-agent-covered-methods)
1544         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1545         gnus-command-method sym group articles
1546         history overview file histories elem art nov-file low info
1547         unreads marked article orig lowest highest)
1548     (save-excursion
1549       (setq overview (gnus-get-buffer-create " *expire overview*"))
1550       (while (setq gnus-command-method (pop methods))
1551         (when (file-exists-p (gnus-agent-lib-file "active"))
1552           (with-temp-buffer
1553             (insert-file-contents-as-coding-system
1554              gnus-agent-file-coding-system (gnus-agent-lib-file "active"))
1555             (gnus-active-to-gnus-format
1556              gnus-command-method
1557              (setq orig (gnus-make-hashtable
1558                          (count-lines (point-min) (point-max))))))
1559           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1560             (gnus-agent-open-history)
1561             (set-buffer
1562              (setq gnus-agent-current-history
1563                    (setq history (gnus-agent-history-buffer))))
1564             (goto-char (point-min))
1565             (when (> (buffer-size) 1)
1566               (goto-char (point-min))
1567               (while (not (eobp))
1568                 (skip-chars-forward "^\t")
1569                 (if (let ((fetch-date (read (current-buffer))))
1570                       (if (numberp fetch-date)
1571                           (>  fetch-date day)
1572                         ;; History file is corrupted.
1573                         (gnus-message
1574                          5
1575                          (format "File %s is corrupted!"
1576                                  (gnus-agent-lib-file "history")))
1577                         (sit-for 1)
1578                         ;; Ignore it
1579                         t))
1580                     ;; New article; we don't expire it.
1581                     (forward-line 1)
1582                   ;; Old article.  Schedule it for possible nuking.
1583                   (while (not (eolp))
1584                     (setq sym (let ((obarray expiry-hashtb) s)
1585                                 (setq s (read (current-buffer)))
1586                                 (if (stringp s) (intern s) s)))
1587                     (if (boundp sym)
1588                         (set sym (cons (cons (read (current-buffer)) (point))
1589                                        (symbol-value sym)))
1590                       (set sym (list (cons (read (current-buffer)) (point)))))
1591                     (skip-chars-forward " "))
1592                   (forward-line 1)))
1593               ;; We now have all articles that can possibly be expired.
1594               (mapatoms
1595                (lambda (sym)
1596                  (setq group (symbol-name sym)
1597                        articles (sort (symbol-value sym) 'car-less-than-car)
1598                        low (car (gnus-active group))
1599                        info (gnus-get-info group)
1600                        unreads (ignore-errors
1601                                  (gnus-list-of-unread-articles group))
1602                        marked (nconc
1603                                (gnus-uncompress-range
1604                                 (cdr (assq 'tick (gnus-info-marks info))))
1605                                (gnus-uncompress-range
1606                                 (cdr (assq 'dormant (gnus-info-marks info))))
1607                                (gnus-uncompress-range
1608                                 (cdr (assq 'save (gnus-info-marks info))))
1609                                (gnus-uncompress-range
1610                                 (cdr (assq 'reply (gnus-info-marks info)))))
1611                        nov-file (gnus-agent-article-name ".overview" group)
1612                        lowest nil
1613                        highest nil)
1614                  (gnus-agent-load-alist group)
1615                  (gnus-message 5 "Expiring articles in %s" group)
1616                  (set-buffer overview)
1617                  (erase-buffer)
1618                  (when (file-exists-p nov-file)
1619                    (nnheader-insert-file-contents nov-file))
1620                  (goto-char (point-min))
1621                  (setq article 0)
1622                  (while (setq elem (pop articles))
1623                    (setq article (car elem))
1624                    (when (or (null low)
1625                              (< article low)
1626                              gnus-agent-expire-all
1627                              (and (not (memq article unreads))
1628                                   (not (memq article marked))))
1629                      ;; Find and nuke the NOV line.
1630                      (while (and (not (eobp))
1631                                  (or (not (numberp
1632                                            (setq art (read (current-buffer)))))
1633                                      (< art article)))
1634                        (if (and (numberp art)
1635                                 (file-exists-p
1636                                  (gnus-agent-article-name
1637                                   (number-to-string art) group)))
1638                            (progn
1639                              (unless lowest
1640                                (setq lowest art))
1641                              (setq highest art)
1642                              (forward-line 1))
1643                          ;; Remove old NOV lines that have no articles.
1644                          (gnus-delete-line)))
1645                      (if (or (eobp)
1646                              (/= art article))
1647                          (beginning-of-line)
1648                        (gnus-delete-line))
1649                      ;; Nuke the article.
1650                      (when (file-exists-p
1651                             (setq file (gnus-agent-article-name
1652                                         (number-to-string article)
1653                                         group)))
1654                        (delete-file file))
1655                      ;; Schedule the history line for nuking.
1656                      (push (cdr elem) histories)))
1657                  (gnus-make-directory (file-name-directory nov-file))
1658                  (write-region-as-coding-system
1659                   gnus-agent-file-coding-system
1660                   (point-min) (point-max) nov-file nil 'silent)
1661                  ;; Delete the unwanted entries in the alist.
1662                  (setq gnus-agent-article-alist
1663                        (sort gnus-agent-article-alist 'car-less-than-car))
1664                  (let* ((alist gnus-agent-article-alist)
1665                         (prev (cons nil alist))
1666                         (first prev)
1667                         expired)
1668                    (while (and alist
1669                                (<= (caar alist) article))
1670                      (if (or (not (cdar alist))
1671                              (not (file-exists-p
1672                                    (gnus-agent-article-name
1673                                     (number-to-string
1674                                      (caar alist))
1675                                     group))))
1676                          (progn
1677                            (push (caar alist) expired)
1678                            (setcdr prev (setq alist (cdr alist))))
1679                        (setq prev alist
1680                              alist (cdr alist))))
1681                    (setq gnus-agent-article-alist (cdr first))
1682                    (gnus-agent-save-alist group)
1683                    ;; Mark all articles up to the first article
1684                    ;; in `gnus-article-alist' as read.
1685                    (when (and info (caar gnus-agent-article-alist))
1686                      (setcar (nthcdr 2 info)
1687                              (gnus-range-add
1688                               (nth 2 info)
1689                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1690                    ;; Maybe everything has been expired from `gnus-article-alist'
1691                    ;; and so the above marking as read could not be conducted,
1692                    ;; or there are expired article within the range of the alist.
1693                    (when (and info
1694                               expired
1695                               (or (not (caar gnus-agent-article-alist))
1696                                   (> (car expired)
1697                                      (caar gnus-agent-article-alist))))
1698                      (setcar (nthcdr 2 info)
1699                              (gnus-add-to-range
1700                               (nth 2 info)
1701                               (nreverse expired))))
1702                    (gnus-dribble-enter
1703                     (concat "(gnus-group-set-info '"
1704                             (gnus-prin1-to-string info)
1705                             ")")))
1706                  (when lowest
1707                    (if (gnus-gethash group orig)
1708                        (setcar (gnus-gethash group orig) lowest)
1709                      (gnus-sethash group (cons lowest highest) orig))))
1710                expiry-hashtb)
1711               (set-buffer history)
1712               (setq histories (nreverse (sort histories '<)))
1713               (while histories
1714                 (goto-char (pop histories))
1715                 (gnus-delete-line))
1716               (gnus-agent-save-history)
1717               (gnus-agent-close-history)
1718               (gnus-write-active-file (gnus-agent-lib-file "active") orig))
1719             (gnus-message 4 "Expiry...done")))))))
1720
1721 ;;;###autoload
1722 (defun gnus-agent-batch ()
1723   (interactive)
1724   (let ((init-file-user "")
1725         (gnus-always-read-dribble-file t))
1726     (gnus))
1727   (gnus-group-send-drafts)
1728   (gnus-agent-fetch-session))
1729
1730 (provide 'gnus-agent)
1731
1732 ;;; gnus-agent.el ends here