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