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