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