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