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