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