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