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