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