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