d945cacca58d3289f5dbf90a5bcc84b12ae20b1f
[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         (gnus-agent-read-file
644          (nnheader-concat gnus-agent-directory "lib/servers"))))
645
646 (defun gnus-agent-write-servers ()
647   "Write the alist of covered servers."
648   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
649   (let ((coding-system-for-write nnheader-file-coding-system)
650         (output-coding-system nnheader-file-coding-system)
651         (file-name-coding-system nnmail-pathname-coding-system)
652         (pathname-coding-system nnmail-pathname-coding-system))
653     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
654       (prin1 gnus-agent-covered-methods (current-buffer)))))
655
656 ;;;
657 ;;; Summary commands
658 ;;;
659
660 (defun gnus-agent-mark-article (n &optional unmark)
661   "Mark the next N articles as downloadable.
662 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
663 the mark instead.  The difference between N and the actual number of
664 articles marked is returned."
665   (interactive "p")
666   (let ((backward (< n 0))
667         (n (abs n)))
668     (while (and
669             (> n 0)
670             (progn
671               (gnus-summary-set-agent-mark
672                (gnus-summary-article-number) unmark)
673               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
674       (setq n (1- n)))
675     (when (/= 0 n)
676       (gnus-message 7 "No more articles"))
677     (gnus-summary-recenter)
678     (gnus-summary-position-point)
679     n))
680
681 (defun gnus-agent-unmark-article (n)
682   "Remove the downloadable mark from the next N articles.
683 If N is negative, unmark backward instead.  The difference between N and
684 the actual number of articles unmarked is returned."
685   (interactive "p")
686   (gnus-agent-mark-article n t))
687
688 (defun gnus-agent-toggle-mark (n)
689   "Toggle the downloadable mark from the next N articles.
690 If N is negative, toggle backward instead.  The difference between N and
691 the actual number of articles toggled is returned."
692   (interactive "p")
693   (gnus-agent-mark-article n 'toggle))
694
695 (defun gnus-summary-set-agent-mark (article &optional unmark)
696   "Mark ARTICLE as downloadable."
697   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
698                     (memq article gnus-newsgroup-downloadable)
699                   unmark)))
700     (if unmark
701         (progn
702           (setq gnus-newsgroup-downloadable
703                 (delq article gnus-newsgroup-downloadable))
704           (push article gnus-newsgroup-undownloaded))
705       (setq gnus-newsgroup-undownloaded
706             (delq article gnus-newsgroup-undownloaded))
707       (setq gnus-newsgroup-downloadable
708             (gnus-add-to-sorted-list gnus-newsgroup-downloadable article)))
709     (gnus-summary-update-mark
710      (if unmark gnus-undownloaded-mark gnus-downloadable-mark)
711      'unread)))
712
713 (defun gnus-agent-get-undownloaded-list ()
714   "Mark all unfetched articles as read."
715   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
716     (when (and (not (gnus-online gnus-command-method))
717                (gnus-agent-method-p gnus-command-method))
718       (gnus-agent-load-alist gnus-newsgroup-name)
719       ;; First mark all undownloaded articles as undownloaded.
720       (let ((articles (mapcar (lambda (header) (mail-header-number header))
721                               gnus-newsgroup-headers))
722             (agent-articles gnus-agent-article-alist)
723             candidates article)
724         (while (setq article (pop articles))
725           (while (and agent-articles
726                       (< (caar agent-articles) article))
727             (setq agent-articles (cdr agent-articles)))
728           (when (or (not (cdar agent-articles))
729                     (not (= (caar agent-articles) article)))
730             (push article candidates)))
731         (dolist (article candidates)
732           (unless (or (memq article gnus-newsgroup-downloadable)
733                       (memq article gnus-newsgroup-cached))
734             (push article gnus-newsgroup-undownloaded))))
735       ;; Then mark downloaded downloadable as not-downloadable,
736       ;; if you get my drift.
737       (dolist (article gnus-newsgroup-downloadable)
738         (when (cdr (assq article gnus-agent-article-alist))
739           (setq gnus-newsgroup-downloadable
740                 (delq article gnus-newsgroup-downloadable)))))))
741
742 (defun gnus-agent-catchup ()
743   "Mark all undownloaded articles as read."
744   (interactive)
745   (save-excursion
746     (while gnus-newsgroup-undownloaded
747       (gnus-summary-mark-article
748        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
749   (gnus-summary-position-point))
750
751 (defun gnus-agent-summary-fetch-group ()
752   "Fetch the downloadable articles in the group."
753   (interactive)
754   (let ((articles gnus-newsgroup-downloadable)
755         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
756         (state gnus-plugged))
757     (unwind-protect
758         (progn
759           (unless state
760             (gnus-agent-toggle-plugged t))
761           (unless articles
762             (error "No articles to download"))
763           (gnus-agent-with-fetch
764             (gnus-agent-fetch-articles gnus-newsgroup-name articles))
765           (save-excursion
766             (dolist (article articles)
767               (setq gnus-newsgroup-downloadable
768                     (delq article gnus-newsgroup-downloadable))
769               (if gnus-agent-mark-unread-after-downloaded
770                   (gnus-summary-mark-article article gnus-unread-mark)))))
771       (when (and (not state)
772                  gnus-plugged)
773         (gnus-agent-toggle-plugged nil)))))
774
775 ;;;
776 ;;; Internal functions
777 ;;;
778
779 (defun gnus-agent-save-active (method)
780   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
781
782 (defun gnus-agent-save-active-1 (method function)
783   (when (gnus-agent-method-p method)
784     (let* ((gnus-command-method method)
785            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
786            (file (gnus-agent-lib-file "active")))
787       (funcall function nil new)
788       (gnus-agent-write-active file new)
789       (erase-buffer)
790       (insert-file-contents-as-coding-system gnus-agent-file-coding-system
791                                              file))))
792
793 (defun gnus-agent-write-active (file new)
794   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
795         (file (gnus-agent-lib-file "active"))
796         elem osym)
797     (when (file-exists-p file)
798       (with-temp-buffer
799         (insert-file-contents-as-coding-system gnus-agent-file-coding-system
800                                                file)
801         (gnus-active-to-gnus-format nil orig))
802       (mapatoms
803        (lambda (sym)
804          (when (and sym (boundp sym))
805            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
806                     (setq elem (symbol-value osym)))
807                (progn
808                  (if (and (integerp (car (symbol-value sym)))
809                           (> (car elem) (car (symbol-value sym))))
810                      (setcar elem (car (symbol-value sym))))
811                  (if (integerp (cdr (symbol-value sym)))
812                      (setcdr elem (cdr (symbol-value sym)))))
813              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
814        new))
815     (gnus-make-directory (file-name-directory file))
816     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
817       ;; The hashtable contains real names of groups,  no more prefix
818       ;; removing, so set `full' to `t'.
819       (gnus-write-active-file file orig t))))
820
821 (defun gnus-agent-save-groups (method)
822   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
823
824 (defun gnus-agent-save-group-info (method group active)
825   (when (gnus-agent-method-p method)
826     (let* ((gnus-command-method method)
827            (coding-system-for-write nnheader-file-coding-system)
828            (output-coding-system nnheader-file-coding-system)
829            (file-name-coding-system nnmail-pathname-coding-system)
830            (pathname-coding-system nnmail-pathname-coding-system)
831            (file (gnus-agent-lib-file "active"))
832            oactive-min)
833       (gnus-make-directory (file-name-directory file))
834       (with-temp-file file
835         (when (file-exists-p file)
836           (nnheader-insert-file-contents file))
837         (goto-char (point-min))
838         (when (re-search-forward
839                (concat "^" (regexp-quote group) " ") nil t)
840           (save-excursion
841             (read (current-buffer))                      ;; max
842             (setq oactive-min (read (current-buffer))))  ;; min
843           (gnus-delete-line))
844         (insert (format "%S %d %d y\n" (intern group)
845                         (cdr active)
846                         (or oactive-min (car active))))
847         (goto-char (point-max))
848         (while (search-backward "\\." nil t)
849           (delete-char 1))))))
850
851 (defun gnus-agent-group-path (group)
852   "Translate GROUP into a path."
853   (if nnmail-use-long-file-names
854       (gnus-group-real-name group)
855     (nnheader-translate-file-chars
856      (nnheader-replace-chars-in-string
857       (nnheader-replace-duplicate-chars-in-string
858        (nnheader-replace-chars-in-string
859         (gnus-group-real-name group)
860         ?/ ?_)
861        ?. ?_)
862       ?. ?/))))
863
864 \f
865
866 (defun gnus-agent-get-function (method)
867   (if (gnus-online method)
868       (car method)
869     (require 'nnagent)
870     'nnagent))
871
872 ;;; History functions
873
874 (defun gnus-agent-history-buffer ()
875   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
876
877 (defun gnus-agent-open-history ()
878   (save-excursion
879     (push (cons (gnus-agent-method)
880                 (set-buffer (gnus-get-buffer-create
881                              (format " *Gnus agent %s history*"
882                                      (gnus-agent-method)))))
883           gnus-agent-history-buffers)
884     (erase-buffer)
885     (insert "\n")
886     (let ((file (gnus-agent-lib-file "history")))
887       (when (file-exists-p file)
888         (nnheader-insert-file-contents file))
889       (set (make-local-variable 'gnus-agent-file-name) file))))
890
891 (defun gnus-agent-save-history ()
892   (save-excursion
893     (set-buffer gnus-agent-current-history)
894     (gnus-make-directory (file-name-directory gnus-agent-file-name))
895     (write-region-as-coding-system
896      gnus-agent-file-coding-system
897      (1+ (point-min)) (point-max) gnus-agent-file-name nil 'silent)))
898
899 (defun gnus-agent-close-history ()
900   (when (gnus-buffer-live-p gnus-agent-current-history)
901     (kill-buffer gnus-agent-current-history)
902     (setq gnus-agent-history-buffers
903           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
904                 gnus-agent-history-buffers))))
905
906 (defun gnus-agent-enter-history (id group-arts date)
907   (save-excursion
908     (set-buffer gnus-agent-current-history)
909     (goto-char (point-max))
910     (let ((p (point)))
911       (insert id "\t" (number-to-string date) "\t")
912       (while group-arts
913         (insert (format "%S" (intern (caar group-arts)))
914                 " " (number-to-string (cdr (pop group-arts)))
915                 " "))
916       (insert "\n")
917       (while (search-backward "\\." p t)
918         (delete-char 1)))))
919
920 (defun gnus-agent-article-in-history-p (id)
921   (save-excursion
922     (set-buffer (gnus-agent-history-buffer))
923     (goto-char (point-min))
924     (search-forward (concat "\n" id "\t") nil t)))
925
926 (defun gnus-agent-history-path (id)
927   (save-excursion
928     (set-buffer (gnus-agent-history-buffer))
929     (goto-char (point-min))
930     (when (search-forward (concat "\n" id "\t") nil t)
931       (let ((method (gnus-agent-method)))
932         (let (paths group)
933           (while (not (numberp (setq group (read (current-buffer)))))
934             (push (concat method "/" group) paths))
935           (nreverse paths))))))
936
937 ;;;
938 ;;; Fetching
939 ;;;
940
941 (defun gnus-agent-fetch-articles (group articles)
942   "Fetch ARTICLES from GROUP and put them into the Agent."
943   (when articles
944     ;; Prune off articles that we have already fetched.
945     (while (and articles
946                 (cdr (assq (car articles) gnus-agent-article-alist)))
947       (pop articles))
948     (let ((arts articles))
949       (while (cdr arts)
950         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
951             (setcdr arts (cddr arts))
952           (setq arts (cdr arts)))))
953     (when articles
954       (let ((dir (concat
955                   (gnus-agent-directory)
956                   (gnus-agent-group-path group) "/"))
957             (date (time-to-days (current-time)))
958             (case-fold-search t)
959             pos crosses id elem)
960         (gnus-make-directory dir)
961         (gnus-message 7 "Fetching articles for %s..." group)
962         ;; Fetch the articles from the backend.
963         (if (gnus-check-backend-function 'retrieve-articles group)
964             (setq pos (gnus-retrieve-articles articles group))
965           (with-temp-buffer
966             (let (article)
967               (while (setq article (pop articles))
968                 (when (or
969                        (gnus-backlog-request-article group article
970                                                      nntp-server-buffer)
971                        (gnus-request-article article group))
972                   (goto-char (point-max))
973                   (push (cons article (point)) pos)
974                   (insert-buffer-substring nntp-server-buffer)))
975               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
976               (setq pos (nreverse pos)))))
977         ;; Then save these articles into the Agent.
978         (save-excursion
979           (set-buffer nntp-server-buffer)
980           (while pos
981             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
982             (goto-char (point-min))
983             (unless (eobp)  ;; Don't save empty articles.
984               (when (search-forward "\n\n" nil t)
985                 (when (search-backward "\nXrefs: " nil t)
986                   ;; Handle cross posting.
987                   (skip-chars-forward "^ ")
988                   (skip-chars-forward " ")
989                   (setq crosses nil)
990                   (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
991                     (push (cons (buffer-substring (match-beginning 1)
992                                                   (match-end 1))
993                                 (buffer-substring (match-beginning 2)
994                                                   (match-end 2)))
995                           crosses)
996                     (goto-char (match-end 0)))
997                   (gnus-agent-crosspost crosses (caar pos))))
998               (goto-char (point-min))
999               (if (not (re-search-forward
1000                         "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1001                   (setq id "No-Message-ID-in-article")
1002                 (setq id (buffer-substring (match-beginning 1) (match-end 1))))
1003               (write-region-as-coding-system
1004                gnus-agent-file-coding-system (point-min) (point-max)
1005                (concat dir (number-to-string (caar pos))) nil 'silent)
1006               (when (setq elem (assq (caar pos) gnus-agent-article-alist))
1007                 (setcdr elem t))
1008               (gnus-agent-enter-history
1009                id (or crosses (list (cons group (caar pos)))) date))
1010             (widen)
1011             (pop pos)))
1012         (gnus-agent-save-alist group)))))
1013
1014 (defun gnus-agent-crosspost (crosses article)
1015   (let (gnus-agent-article-alist group alist beg end)
1016     (save-excursion
1017       (set-buffer gnus-agent-overview-buffer)
1018       (when (nnheader-find-nov-line article)
1019         (forward-word 1)
1020         (setq beg (point))
1021         (setq end (progn (forward-line 1) (point)))))
1022     (while crosses
1023       (setq group (caar crosses))
1024       (unless (setq alist (assoc group gnus-agent-group-alist))
1025         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1026               gnus-agent-group-alist))
1027       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
1028       (save-excursion
1029         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1030                                                     group)))
1031         (when (= (point-max) (point-min))
1032           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1033           (ignore-errors
1034             (nnheader-insert-file-contents
1035              (gnus-agent-article-name ".overview" group))))
1036         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1037         (insert (string-to-number (cdar crosses)))
1038         (insert-buffer-substring gnus-agent-overview-buffer beg end))
1039       (pop crosses))))
1040
1041 (defun gnus-agent-flush-cache ()
1042   (save-excursion
1043     (while gnus-agent-buffer-alist
1044       (set-buffer (cdar gnus-agent-buffer-alist))
1045       (write-region-as-coding-system
1046        gnus-agent-file-coding-system
1047        (point-min) (point-max)
1048        (gnus-agent-article-name ".overview"
1049                                 (caar gnus-agent-buffer-alist))
1050        nil 'silent)
1051       (pop gnus-agent-buffer-alist))
1052     (while gnus-agent-group-alist
1053       (with-temp-file (caar gnus-agent-group-alist)
1054         (princ (cdar gnus-agent-group-alist))
1055         (insert "\n"))
1056       (pop gnus-agent-group-alist))))
1057
1058 (defun gnus-agent-fetch-headers (group &optional force)
1059   (let* ((articles (gnus-list-of-unread-articles group))
1060          (len (length articles))
1061          (gnus-decode-encoded-word-function 'identity)
1062          (file (gnus-agent-article-name ".overview" group))
1063          i gnus-agent-cache)
1064     ;; Check the number of articles is not too large.
1065     (when (and (integerp gnus-agent-large-newsgroup)
1066                (< 0 gnus-agent-large-newsgroup))
1067       (and (< 0 (setq i (- len gnus-agent-large-newsgroup)))
1068            (setq articles (nthcdr i articles))))
1069     ;; add article with marks to list of article headers we want to fetch.
1070     (dolist (arts (gnus-info-marks (gnus-get-info group)))
1071       (unless (memq (car arts) '(seen recent))
1072         (setq articles (gnus-range-add articles (cdr arts)))))
1073     (setq articles (sort (gnus-uncompress-sequence articles) '<))
1074     ;; Remove known articles.
1075     (when (gnus-agent-load-alist group)
1076       (setq articles (gnus-list-range-intersection
1077                       articles
1078                       (list
1079                        (cons (1+ (caar (last gnus-agent-article-alist)))
1080                              (cdr (gnus-active group)))))))
1081     ;; Fetch them.
1082     (gnus-make-directory (nnheader-translate-file-chars
1083                           (file-name-directory file) t))
1084     (when articles
1085       (gnus-message 7 "Fetching headers for %s..." group)
1086       (save-excursion
1087         (set-buffer nntp-server-buffer)
1088         (unless (eq 'nov (gnus-retrieve-headers articles group))
1089           (nnvirtual-convert-headers))
1090         ;; Save these headers for later processing.
1091         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1092         (when (file-exists-p file)
1093           (gnus-agent-braid-nov group articles file))
1094         (write-region-as-coding-system
1095          gnus-agent-file-coding-system
1096          (point-min) (point-max) file nil 'silent)
1097         (gnus-agent-save-alist group articles nil)
1098         (gnus-agent-enter-history
1099          "last-header-fetched-for-session"
1100          (list (cons group (nth (- (length  articles) 1) articles)))
1101          (time-to-days (current-time)))
1102         articles))))
1103
1104 (defsubst gnus-agent-copy-nov-line (article)
1105   (let (art b e)
1106     (set-buffer gnus-agent-overview-buffer)
1107     (while (and (not (eobp))
1108                 (< (setq art (read (current-buffer))) article))
1109       (forward-line 1))
1110     (beginning-of-line)
1111     (if (or (eobp)
1112             (not (eq article art)))
1113         (set-buffer nntp-server-buffer)
1114       (setq b (point))
1115       (setq e (progn (forward-line 1) (point)))
1116       (set-buffer nntp-server-buffer)
1117       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1118
1119 (defun gnus-agent-braid-nov (group articles file)
1120   (let (start last)
1121     (set-buffer gnus-agent-overview-buffer)
1122     (goto-char (point-min))
1123     (set-buffer nntp-server-buffer)
1124     (erase-buffer)
1125     (nnheader-insert-file-contents file)
1126     (goto-char (point-max))
1127     (unless (or (= (point-min) (point-max))
1128                 (progn
1129                   (forward-line -1)
1130                   (< (setq last (read (current-buffer))) (car articles))))
1131       ;; We do it the hard way.
1132       (nnheader-find-nov-line (car articles))
1133       (gnus-agent-copy-nov-line (pop articles))
1134       (while (and articles
1135                   (not (eobp)))
1136         (while (and (not (eobp))
1137                     (< (read (current-buffer)) (car articles)))
1138           (forward-line 1))
1139         (beginning-of-line)
1140         (unless (eobp)
1141           (gnus-agent-copy-nov-line (pop articles)))))
1142     ;; Copy the rest lines
1143     (set-buffer nntp-server-buffer)
1144     (goto-char (point-max))
1145     (when articles
1146       (when last
1147         (set-buffer gnus-agent-overview-buffer)
1148         (while (and (not (eobp))
1149                     (<= (read (current-buffer)) last))
1150           (forward-line 1))
1151         (beginning-of-line)
1152         (setq start (point))
1153         (set-buffer nntp-server-buffer))
1154       (insert-buffer-substring gnus-agent-overview-buffer start))))
1155
1156 (defun gnus-agent-load-alist (group &optional dir)
1157   "Load the article-state alist for GROUP."
1158   (let ((file))
1159     (setq gnus-agent-article-alist
1160           (gnus-cache-file-contents
1161            (if dir
1162                (expand-file-name ".agentview" dir)
1163              (gnus-agent-article-name ".agentview" group))
1164            'gnus-agent-file-loading-cache
1165            'gnus-agent-read-file))))
1166
1167 (defun gnus-agent-save-alist (group &optional articles state dir)
1168   "Save the article-state alist for GROUP."
1169   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1170          (pathname-coding-system nnmail-pathname-coding-system)
1171          (prev (cons nil gnus-agent-article-alist))
1172          (all prev)
1173          print-level print-length item article)
1174     (while (setq article (pop articles))
1175       (while (and (cdr prev)
1176                   (< (caadr prev) article))
1177         (setq prev (cdr prev)))
1178       (cond
1179        ((not (cdr prev))
1180         (setcdr prev (list (cons article state))))
1181        ((> (caadr prev) article)
1182         (setcdr prev (cons (cons article state) (cdr prev))))
1183        ((= (caadr prev) article)
1184         (setcdr (cadr prev) state)))
1185       (setq prev (cdr prev)))
1186     (setq gnus-agent-article-alist (cdr all))
1187     (with-temp-file (if dir
1188                         (expand-file-name ".agentview" dir)
1189                       (gnus-agent-article-name ".agentview" group))
1190       (princ gnus-agent-article-alist (current-buffer))
1191       (insert "\n"))))
1192
1193 (defun gnus-agent-article-name (article group)
1194   (expand-file-name (if (stringp article) article (string-to-number article))
1195                     (file-name-as-directory
1196                      (expand-file-name (gnus-agent-group-path group)
1197                                        (gnus-agent-directory)))))
1198
1199 ;;;###autoload
1200 (defun gnus-agent-batch-fetch ()
1201   "Start Gnus and fetch session."
1202   (interactive)
1203   (gnus)
1204   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1205     (gnus-agent-fetch-session))
1206   (gnus-group-exit))
1207
1208 (defun gnus-agent-fetch-session ()
1209   "Fetch all articles and headers that are eligible for fetching."
1210   (interactive)
1211   (unless gnus-agent-covered-methods
1212     (error "No servers are covered by the Gnus agent"))
1213   (unless gnus-plugged
1214     (error "Can't fetch articles while Gnus is unplugged"))
1215   (let ((methods gnus-agent-covered-methods)
1216         groups group gnus-command-method)
1217     (save-excursion
1218       (while methods
1219         (condition-case err
1220             (progn
1221               (setq gnus-command-method (car methods))
1222               (when (and (or (gnus-server-opened gnus-command-method)
1223                              (gnus-open-server gnus-command-method))
1224                          (gnus-online gnus-command-method))
1225                 (setq groups (gnus-groups-from-server (car methods)))
1226                 (gnus-agent-with-fetch
1227                   (while (setq group (pop groups))
1228                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1229                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1230           (error
1231            (unless (funcall gnus-agent-confirmation-function
1232                             (format "Error (%s).  Continue? " (cadr err)))
1233              (error "Cannot fetch articles into the Gnus agent")))
1234           (quit
1235            (unless (funcall gnus-agent-confirmation-function
1236                             (format "Quit fetching session (%s).  Continue? "
1237                                     (cadr err)))
1238              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1239         (pop methods))
1240       (run-hooks 'gnus-agent-fetch-hook)
1241       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1242
1243 (defun gnus-agent-fetch-group-1 (group method)
1244   "Fetch GROUP."
1245   (let ((gnus-command-method method)
1246         (gnus-newsgroup-name group)
1247         gnus-newsgroup-dependencies gnus-newsgroup-headers
1248         gnus-newsgroup-scored gnus-headers gnus-score
1249         gnus-use-cache articles arts
1250         category predicate info marks score-param
1251         (gnus-summary-expunge-below gnus-summary-expunge-below)
1252         (gnus-summary-mark-below gnus-summary-mark-below)
1253         (gnus-orphan-score gnus-orphan-score)
1254         ;; Maybe some other gnus-summary local variables should also
1255         ;; be put here.
1256         )
1257     (unless (gnus-check-group group)
1258       (error "Can't open server for %s" group))
1259     ;; Fetch headers.
1260     (when (and (or (gnus-active group)
1261                    (gnus-activate-group group))
1262                (setq articles (gnus-agent-fetch-headers group))
1263                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1264                  ;; Parse them and see which articles we want to fetch.
1265                  (setq gnus-newsgroup-dependencies
1266                        (make-vector (length articles) 0))
1267                  (setq gnus-newsgroup-headers
1268                        (gnus-get-newsgroup-headers-xover articles nil nil
1269                                                          group))
1270                  ;; `gnus-agent-overview-buffer' may be killed for
1271                  ;; timeout reason.  If so, recreate it.
1272                  (gnus-agent-create-buffer)))
1273       (setq category (gnus-group-category group))
1274       (setq predicate
1275             (gnus-get-predicate
1276              (or (gnus-group-find-parameter group 'agent-predicate t)
1277                  (cadr category))))
1278       (if (memq predicate '(gnus-agent-true gnus-agent-false))
1279           ;; Simple implementation
1280           (setq arts (and (eq predicate 'gnus-agent-true) articles))
1281         (setq arts nil)
1282         (setq score-param
1283               (or (gnus-group-get-parameter group 'agent-score t)
1284                   (caddr category)))
1285         ;; Translate score-param into real one
1286         (cond
1287          ((not score-param))
1288          ((eq score-param 'file)
1289           (setq score-param (gnus-all-score-files group)))
1290          ((stringp (car score-param)))
1291          (t
1292           (setq score-param (list (list score-param)))))
1293         (when score-param
1294           (gnus-score-headers score-param))
1295         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1296           (setq gnus-score
1297                 (or (cdr (assq (mail-header-number gnus-headers)
1298                                gnus-newsgroup-scored))
1299                     gnus-summary-default-score))
1300           (when (funcall predicate)
1301             (push (mail-header-number gnus-headers)
1302                   arts))))
1303       ;; Fetch the articles.
1304       (when arts
1305         (gnus-agent-fetch-articles group arts)))
1306     ;; Perhaps we have some additional articles to fetch.
1307     (dolist (mark gnus-agent-download-marks)
1308       (setq arts (assq mark (gnus-info-marks
1309                              (setq info (gnus-get-info group)))))
1310       (when (cdr arts)
1311         (gnus-message 8 "Agent is downloading marked articles...")
1312         (gnus-agent-fetch-articles
1313          group (gnus-uncompress-range (cdr arts)))
1314         (when (eq mark 'download)
1315           (setq marks (delq arts (gnus-info-marks info)))
1316           (gnus-info-set-marks info marks)
1317           (gnus-dribble-enter
1318            (concat "(gnus-group-set-info '"
1319                    (gnus-prin1-to-string info)
1320                    ")")))))))
1321
1322 ;;;
1323 ;;; Agent Category Mode
1324 ;;;
1325
1326 (defvar gnus-category-mode-hook nil
1327   "Hook run in `gnus-category-mode' buffers.")
1328
1329 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1330   "Format of category lines.
1331
1332 Valid specifiers include:
1333 %c  Topic name (string)
1334 %g  The number of groups in the topic (integer)
1335
1336 General format specifiers can also be used.  See
1337 (gnus)Formatting Variables.")
1338
1339 (defvar gnus-category-mode-line-format "Gnus: %%b"
1340   "The format specification for the category mode line.")
1341
1342 (defvar gnus-agent-short-article 100
1343   "Articles that have fewer lines than this are short.")
1344
1345 (defvar gnus-agent-long-article 200
1346   "Articles that have more lines than this are long.")
1347
1348 (defvar gnus-agent-low-score 0
1349   "Articles that have a score lower than this have a low score.")
1350
1351 (defvar gnus-agent-high-score 0
1352   "Articles that have a score higher than this have a high score.")
1353
1354
1355 ;;; Internal variables.
1356
1357 (defvar gnus-category-buffer "*Agent Category*")
1358
1359 (defvar gnus-category-line-format-alist
1360   `((?c gnus-tmp-name ?s)
1361     (?g gnus-tmp-groups ?d)))
1362
1363 (defvar gnus-category-mode-line-format-alist
1364   `((?u user-defined ?s)))
1365
1366 (defvar gnus-category-line-format-spec nil)
1367 (defvar gnus-category-mode-line-format-spec nil)
1368
1369 (defvar gnus-category-mode-map nil)
1370 (put 'gnus-category-mode 'mode-class 'special)
1371
1372 (unless gnus-category-mode-map
1373   (setq gnus-category-mode-map (make-sparse-keymap))
1374   (suppress-keymap gnus-category-mode-map)
1375
1376   (gnus-define-keys gnus-category-mode-map
1377     "q" gnus-category-exit
1378     "k" gnus-category-kill
1379     "c" gnus-category-copy
1380     "a" gnus-category-add
1381     "p" gnus-category-edit-predicate
1382     "g" gnus-category-edit-groups
1383     "s" gnus-category-edit-score
1384     "l" gnus-category-list
1385
1386     "\C-c\C-i" gnus-info-find-node
1387     "\C-c\C-b" gnus-bug))
1388
1389 (defvar gnus-category-menu-hook nil
1390   "*Hook run after the creation of the menu.")
1391
1392 (defun gnus-category-make-menu-bar ()
1393   (gnus-turn-off-edit-menu 'category)
1394   (unless (boundp 'gnus-category-menu)
1395     (easy-menu-define
1396      gnus-category-menu gnus-category-mode-map ""
1397      '("Categories"
1398        ["Add" gnus-category-add t]
1399        ["Kill" gnus-category-kill t]
1400        ["Copy" gnus-category-copy t]
1401        ["Edit predicate" gnus-category-edit-predicate t]
1402        ["Edit score" gnus-category-edit-score t]
1403        ["Edit groups" gnus-category-edit-groups t]
1404        ["Exit" gnus-category-exit t]))
1405
1406     (gnus-run-hooks 'gnus-category-menu-hook)))
1407
1408 (defun gnus-category-mode ()
1409   "Major mode for listing and editing agent categories.
1410
1411 All normal editing commands are switched off.
1412 \\<gnus-category-mode-map>
1413 For more in-depth information on this mode, read the manual
1414 (`\\[gnus-info-find-node]').
1415
1416 The following commands are available:
1417
1418 \\{gnus-category-mode-map}"
1419   (interactive)
1420   (when (gnus-visual-p 'category-menu 'menu)
1421     (gnus-category-make-menu-bar))
1422   (kill-all-local-variables)
1423   (gnus-simplify-mode-line)
1424   (setq major-mode 'gnus-category-mode)
1425   (setq mode-name "Category")
1426   (gnus-set-default-directory)
1427   (setq mode-line-process nil)
1428   (use-local-map gnus-category-mode-map)
1429   (buffer-disable-undo)
1430   (setq truncate-lines t)
1431   (setq buffer-read-only t)
1432   (gnus-run-hooks 'gnus-category-mode-hook))
1433
1434 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1435
1436 (defun gnus-category-insert-line (category)
1437   (let* ((gnus-tmp-name (format "%s" (car category)))
1438          (gnus-tmp-groups (length (cadddr category))))
1439     (beginning-of-line)
1440     (gnus-add-text-properties
1441      (point)
1442      (prog1 (1+ (point))
1443        ;; Insert the text.
1444        (eval gnus-category-line-format-spec))
1445      (list 'gnus-category gnus-tmp-name))))
1446
1447 (defun gnus-enter-category-buffer ()
1448   "Go to the Category buffer."
1449   (interactive)
1450   (gnus-category-setup-buffer)
1451   (gnus-configure-windows 'category)
1452   (gnus-category-prepare))
1453
1454 (defun gnus-category-setup-buffer ()
1455   (unless (get-buffer gnus-category-buffer)
1456     (save-excursion
1457       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1458       (gnus-category-mode))))
1459
1460 (defun gnus-category-prepare ()
1461   (gnus-set-format 'category-mode)
1462   (gnus-set-format 'category t)
1463   (let ((alist gnus-category-alist)
1464         (buffer-read-only nil))
1465     (erase-buffer)
1466     (while alist
1467       (gnus-category-insert-line (pop alist)))
1468     (goto-char (point-min))
1469     (gnus-category-position-point)))
1470
1471 (defun gnus-category-name ()
1472   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1473       (error "No category on the current line")))
1474
1475 (defun gnus-category-read ()
1476   "Read the category alist."
1477   (setq gnus-category-alist
1478         (or (gnus-agent-read-file
1479              (nnheader-concat gnus-agent-directory "lib/categories"))
1480             (list (list 'default 'short nil nil)))))
1481
1482 (defun gnus-category-write ()
1483   "Write the category alist."
1484   (setq gnus-category-predicate-cache nil
1485         gnus-category-group-cache nil)
1486   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1487   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1488     (prin1 gnus-category-alist (current-buffer))))
1489
1490 (defun gnus-category-edit-predicate (category)
1491   "Edit the predicate for CATEGORY."
1492   (interactive (list (gnus-category-name)))
1493   (let ((info (assq category gnus-category-alist)))
1494     (gnus-edit-form
1495      (cadr info) (format "Editing the predicate for category %s" category)
1496      `(lambda (predicate)
1497         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1498         (gnus-category-write)
1499         (gnus-category-list)))))
1500
1501 (defun gnus-category-edit-score (category)
1502   "Edit the score expression for CATEGORY."
1503   (interactive (list (gnus-category-name)))
1504   (let ((info (assq category gnus-category-alist)))
1505     (gnus-edit-form
1506      (caddr info)
1507      (format "Editing the score expression for category %s" category)
1508      `(lambda (groups)
1509         (setcar (nthcdr 2 (assq ',category gnus-category-alist)) groups)
1510         (gnus-category-write)
1511         (gnus-category-list)))))
1512
1513 (defun gnus-category-edit-groups (category)
1514   "Edit the group list for CATEGORY."
1515   (interactive (list (gnus-category-name)))
1516   (let ((info (assq category gnus-category-alist)))
1517     (gnus-edit-form
1518      (cadddr info) (format "Editing the group list for category %s" category)
1519      `(lambda (groups)
1520         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1521         (gnus-category-write)
1522         (gnus-category-list)))))
1523
1524 (defun gnus-category-kill (category)
1525   "Kill the current category."
1526   (interactive (list (gnus-category-name)))
1527   (let ((info (assq category gnus-category-alist))
1528         (buffer-read-only nil))
1529     (gnus-delete-line)
1530     (setq gnus-category-alist (delq info gnus-category-alist))
1531     (gnus-category-write)))
1532
1533 (defun gnus-category-copy (category to)
1534   "Copy the current category."
1535   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1536   (let ((info (assq category gnus-category-alist)))
1537     (push (list to (gnus-copy-sequence (cadr info))
1538                 (gnus-copy-sequence (caddr info)) nil)
1539           gnus-category-alist)
1540     (gnus-category-write)
1541     (gnus-category-list)))
1542
1543 (defun gnus-category-add (category)
1544   "Create a new category."
1545   (interactive "SCategory name: ")
1546   (when (assq category gnus-category-alist)
1547     (error "Category %s already exists" category))
1548   (push (list category 'false nil nil)
1549         gnus-category-alist)
1550   (gnus-category-write)
1551   (gnus-category-list))
1552
1553 (defun gnus-category-list ()
1554   "List all categories."
1555   (interactive)
1556   (gnus-category-prepare))
1557
1558 (defun gnus-category-exit ()
1559   "Return to the group buffer."
1560   (interactive)
1561   (kill-buffer (current-buffer))
1562   (gnus-configure-windows 'group t))
1563
1564 ;; To avoid having 8-bit characters in the source file.
1565 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1566
1567 (defvar gnus-category-predicate-alist
1568   '((spam . gnus-agent-spam-p)
1569     (short . gnus-agent-short-p)
1570     (long . gnus-agent-long-p)
1571     (low . gnus-agent-low-scored-p)
1572     (high . gnus-agent-high-scored-p)
1573     (true . gnus-agent-true)
1574     (false . gnus-agent-false))
1575   "Mapping from short score predicate symbols to predicate functions.")
1576
1577 (defun gnus-agent-spam-p ()
1578   "Say whether an article is spam or not."
1579   (unless gnus-agent-spam-hashtb
1580     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1581   (if (not (equal (mail-header-references gnus-headers) ""))
1582       nil
1583     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1584       (prog1
1585           (gnus-gethash string gnus-agent-spam-hashtb)
1586         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1587
1588 (defun gnus-agent-short-p ()
1589   "Say whether an article is short or not."
1590   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1591
1592 (defun gnus-agent-long-p ()
1593   "Say whether an article is long or not."
1594   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1595
1596 (defun gnus-agent-low-scored-p ()
1597   "Say whether an article has a low score or not."
1598   (< gnus-score gnus-agent-low-score))
1599
1600 (defun gnus-agent-high-scored-p ()
1601   "Say whether an article has a high score or not."
1602   (> gnus-score gnus-agent-high-score))
1603
1604 (defun gnus-category-make-function (cat)
1605   "Make a function from category CAT."
1606   (let ((func (gnus-category-make-function-1 cat)))
1607     (if (and (= (length func) 1)
1608              (symbolp (car func)))
1609         (car func)
1610       (gnus-byte-compile `(lambda () ,func)))))
1611
1612 (defun gnus-agent-true ()
1613   "Return t."
1614   t)
1615
1616 (defun gnus-agent-false ()
1617   "Return nil."
1618   nil)
1619
1620 (defun gnus-category-make-function-1 (cat)
1621   "Make a function from category CAT."
1622   (cond
1623    ;; Functions are just returned as is.
1624    ((or (symbolp cat)
1625         (gnus-functionp cat))
1626     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1627            cat)))
1628    ;; More complex category.
1629    ((consp cat)
1630     `(,(cond
1631         ((memq (car cat) '(& and))
1632          'and)
1633         ((memq (car cat) '(| or))
1634          'or)
1635         ((memq (car cat) gnus-category-not)
1636          'not))
1637       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1638    (t
1639     (error "Unknown category type: %s" cat))))
1640
1641 (defun gnus-get-predicate (predicate)
1642   "Return the predicate for CATEGORY."
1643   (or (cdr (assoc predicate gnus-category-predicate-cache))
1644       (let ((func (gnus-category-make-function predicate)))
1645         (setq gnus-category-predicate-cache
1646               (nconc gnus-category-predicate-cache
1647                      (list (cons predicate func))))
1648         func)))
1649
1650 (defun gnus-group-category (group)
1651   "Return the category GROUP belongs to."
1652   (unless gnus-category-group-cache
1653     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1654     (let ((cs gnus-category-alist)
1655           groups cat)
1656       (while (setq cat (pop cs))
1657         (setq groups (cadddr cat))
1658         (while groups
1659           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1660   (or (gnus-gethash group gnus-category-group-cache)
1661       (assq 'default gnus-category-alist)))
1662
1663 (defun gnus-agent-expire ()
1664   "Expire all old articles."
1665   (interactive)
1666   (let ((methods gnus-agent-covered-methods)
1667         (day (if (numberp gnus-agent-expire-days)
1668                  (- (time-to-days (current-time)) gnus-agent-expire-days)
1669                nil))
1670         (current-day (time-to-days (current-time)))
1671         gnus-command-method sym group articles
1672         history overview file histories elem art nov-file low info
1673         unreads marked article orig lowest highest found days)
1674     (save-excursion
1675       (setq overview (gnus-get-buffer-create " *expire overview*"))
1676       (while (setq gnus-command-method (pop methods))
1677         (when (file-exists-p (gnus-agent-lib-file "active"))
1678           (with-temp-buffer
1679             (insert-file-contents-as-coding-system
1680              gnus-agent-file-coding-system (gnus-agent-lib-file "active"))
1681             (gnus-active-to-gnus-format
1682              gnus-command-method
1683              (setq orig (gnus-make-hashtable
1684                          (count-lines (point-min) (point-max))))))
1685           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1686             (gnus-agent-open-history)
1687             (set-buffer
1688              (setq gnus-agent-current-history
1689                    (setq history (gnus-agent-history-buffer))))
1690             (goto-char (point-min))
1691             (when (> (buffer-size) 1)
1692               (goto-char (point-min))
1693               (while (not (eobp))
1694                 (skip-chars-forward "^\t")
1695                 (if (let ((fetch-date (read (current-buffer))))
1696                       (if (numberp fetch-date)
1697                           ;; We now have the arrival day, so we see
1698                           ;; whether it's old enough to be expired.
1699                           (if (numberp day)
1700                               (> fetch-date day)
1701                             (skip-chars-forward "\t")
1702                             (setq found nil
1703                                   days gnus-agent-expire-days)
1704                             (while (and (not found)
1705                                         days)
1706                               (when (looking-at (caar days))
1707                                 (setq found (cadar days)))
1708                               (pop days))
1709                             (> fetch-date (- current-day found)))
1710                         ;; History file is corrupted.
1711                         (gnus-message
1712                          5
1713                          (format "File %s is corrupted!"
1714                                  (gnus-agent-lib-file "history")))
1715                         (sit-for 1)
1716                         ;; Ignore it
1717                         t))
1718                     ;; New article; we don't expire it.
1719                     (forward-line 1)
1720                   ;; Old article.  Schedule it for possible nuking.
1721                   (while (not (eolp))
1722                     (setq sym (let ((obarray expiry-hashtb) s)
1723                                 (setq s (read (current-buffer)))
1724                                 (if (stringp s) (intern s) s)))
1725                     (if (boundp sym)
1726                         (set sym (cons (cons (read (current-buffer)) (point))
1727                                        (symbol-value sym)))
1728                       (set sym (list (cons (read (current-buffer)) (point)))))
1729                     (skip-chars-forward " "))
1730                   (forward-line 1)))
1731               ;; We now have all articles that can possibly be expired.
1732               (mapatoms
1733                (lambda (sym)
1734                  (setq group (symbol-name sym)
1735                        articles (sort (symbol-value sym) 'car-less-than-car)
1736                        low (car (gnus-active group))
1737                        info (gnus-get-info group)
1738                        unreads (ignore-errors
1739                                  (gnus-list-of-unread-articles group))
1740                        marked (nconc
1741                                (gnus-uncompress-range
1742                                 (cdr (assq 'tick (gnus-info-marks info))))
1743                                (gnus-uncompress-range
1744                                 (cdr (assq 'dormant (gnus-info-marks info))))
1745                                (gnus-uncompress-range
1746                                 (cdr (assq 'save (gnus-info-marks info))))
1747                                (gnus-uncompress-range
1748                                 (cdr (assq 'reply (gnus-info-marks info)))))
1749                        nov-file (gnus-agent-article-name ".overview" group)
1750                        lowest nil
1751                        highest nil)
1752                  (gnus-agent-load-alist group)
1753                  (gnus-message 5 "Expiring articles in %s" group)
1754                  (set-buffer overview)
1755                  (erase-buffer)
1756                  (when (file-exists-p nov-file)
1757                    (nnheader-insert-file-contents nov-file))
1758                  (goto-char (point-min))
1759                  (setq article 0)
1760                  (while (setq elem (pop articles))
1761                    (setq article (car elem))
1762                    (when (or (null low)
1763                              (< article low)
1764                              gnus-agent-expire-all
1765                              (and (not (memq article unreads))
1766                                   (not (memq article marked))))
1767                      ;; Find and nuke the NOV line.
1768                      (while (and (not (eobp))
1769                                  (or (not (numberp
1770                                            (setq art (read (current-buffer)))))
1771                                      (< art article)))
1772                        (if (and (numberp art)
1773                                 (file-exists-p
1774                                  (gnus-agent-article-name
1775                                   (number-to-string art) group)))
1776                            (progn
1777                              (unless lowest
1778                                (setq lowest art))
1779                              (setq highest art)
1780                              (forward-line 1))
1781                          ;; Remove old NOV lines that have no articles.
1782                          (gnus-delete-line)))
1783                      (if (or (eobp)
1784                              (/= art article))
1785                          (beginning-of-line)
1786                        (gnus-delete-line))
1787                      ;; Nuke the article.
1788                      (when (file-exists-p
1789                             (setq file (gnus-agent-article-name
1790                                         (number-to-string article)
1791                                         group)))
1792                        (delete-file file))
1793                      ;; Schedule the history line for nuking.
1794                      (push (cdr elem) histories)))
1795                  (gnus-make-directory (file-name-directory nov-file))
1796                  (write-region-as-coding-system
1797                   gnus-agent-file-coding-system
1798                   (point-min) (point-max) nov-file nil 'silent)
1799                  ;; Delete the unwanted entries in the alist.
1800                  (setq gnus-agent-article-alist
1801                        (sort gnus-agent-article-alist 'car-less-than-car))
1802                  (let* ((alist gnus-agent-article-alist)
1803                         (prev (cons nil alist))
1804                         (first prev)
1805                         expired)
1806                    (while (and alist
1807                                (<= (caar alist) article))
1808                      (if (or (not (cdar alist))
1809                              (not (file-exists-p
1810                                    (gnus-agent-article-name
1811                                     (number-to-string
1812                                      (caar alist))
1813                                     group))))
1814                          (progn
1815                            (push (caar alist) expired)
1816                            (setcdr prev (setq alist (cdr alist))))
1817                        (setq prev alist
1818                              alist (cdr alist))))
1819                    (setq gnus-agent-article-alist (cdr first))
1820                    (gnus-agent-save-alist group)
1821                    ;; Mark all articles up to the first article
1822                    ;; in `gnus-article-alist' as read.
1823                    (when (and info (caar gnus-agent-article-alist))
1824                      (setcar (nthcdr 2 info)
1825                              (gnus-range-add
1826                               (nth 2 info)
1827                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1828                    ;; Maybe everything has been expired from
1829                    ;; `gnus-article-alist' and so the above marking as
1830                    ;; read could not be conducted, or there are
1831                    ;; expired article within the range of the alist.
1832                    (when (and info
1833                               expired
1834                               (or (not (caar gnus-agent-article-alist))
1835                                   (> (car expired)
1836                                      (caar gnus-agent-article-alist))))
1837                      (setcar (nthcdr 2 info)
1838                              (gnus-add-to-range
1839                               (nth 2 info)
1840                               (nreverse expired))))
1841                    (gnus-dribble-enter
1842                     (concat "(gnus-group-set-info '"
1843                             (gnus-prin1-to-string info)
1844                             ")")))
1845                  (when lowest
1846                    (if (gnus-gethash group orig)
1847                        (setcar (gnus-gethash group orig) lowest)
1848                      (gnus-sethash group (cons lowest highest) orig))))
1849                expiry-hashtb)
1850               (set-buffer history)
1851               (setq histories (nreverse (sort histories '<)))
1852               (while histories
1853                 (goto-char (pop histories))
1854                 (gnus-delete-line))
1855               (gnus-agent-save-history)
1856               (gnus-agent-close-history)
1857               (gnus-write-active-file (gnus-agent-lib-file "active") orig))
1858             (gnus-message 4 "Expiry...done")))))))
1859
1860 ;;;###autoload
1861 (defun gnus-agent-batch ()
1862   (interactive)
1863   (let ((init-file-user "")
1864         (gnus-always-read-dribble-file t))
1865     (gnus))
1866   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1867     (gnus-group-send-queue)
1868     (gnus-agent-fetch-session)))
1869
1870 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
1871   (save-excursion
1872     (gnus-agent-create-buffer)
1873     (let ((gnus-decode-encoded-word-function 'identity)
1874           (file (gnus-agent-article-name ".overview" group))
1875           cached-articles uncached-articles)
1876       (gnus-make-directory (nnheader-translate-file-chars
1877                             (file-name-directory file) t))
1878       (when (file-exists-p file)
1879         (with-current-buffer gnus-agent-overview-buffer
1880           (erase-buffer)
1881           (let ((nnheader-file-coding-system
1882                  gnus-agent-file-coding-system))
1883             (nnheader-insert-nov-file file (car articles)))
1884           (nnheader-find-nov-line (car articles))
1885           (while (not (eobp))
1886             (when (looking-at "[0-9]")
1887               (push (read (current-buffer)) cached-articles))
1888             (forward-line 1))
1889           (setq cached-articles (nreverse cached-articles))))
1890       (if (setq uncached-articles
1891                 (gnus-sorted-difference articles cached-articles))
1892           (progn
1893             (set-buffer nntp-server-buffer)
1894             (erase-buffer)
1895             (let (gnus-agent-cache)
1896               (unless (eq 'nov
1897                           (gnus-retrieve-headers
1898                            uncached-articles group fetch-old))
1899                 (nnvirtual-convert-headers)))
1900             (set-buffer gnus-agent-overview-buffer)
1901             (erase-buffer)
1902             (set-buffer nntp-server-buffer)
1903             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
1904             (when (and uncached-articles (file-exists-p file))
1905               (gnus-agent-braid-nov group uncached-articles file))
1906             (set-buffer nntp-server-buffer)
1907             (write-region-as-coding-system gnus-agent-file-coding-system
1908                                            (point-min) (point-max)
1909                                            file nil 'silent)
1910             (gnus-agent-load-alist group)
1911             (gnus-agent-save-alist group uncached-articles nil)
1912             (gnus-agent-open-history)
1913             (setq gnus-agent-current-history (gnus-agent-history-buffer))
1914             (gnus-agent-enter-history
1915              "last-header-fetched-for-session"
1916              (list (cons group (nth (- (length  articles) 1) articles)))
1917              (time-to-days (current-time)))
1918             (gnus-agent-save-history))
1919         (set-buffer nntp-server-buffer)
1920         (erase-buffer)
1921         (insert-buffer-substring gnus-agent-overview-buffer)))
1922     (if (and fetch-old
1923              (not (numberp fetch-old)))
1924         t                               ; Don't remove anything.
1925       (nnheader-nov-delete-outside-range
1926        (if fetch-old (max 1 (- (car articles) fetch-old))
1927          (car articles))
1928        (car (last articles)))
1929       t)
1930     'nov))
1931
1932 (defun gnus-agent-request-article (article group)
1933   "Retrieve ARTICLE in GROUP from the agent cache."
1934   (let* ((gnus-command-method (gnus-find-method-for-group group))
1935          (file (concat
1936                   (gnus-agent-directory)
1937                   (gnus-agent-group-path group) "/"
1938                   (number-to-string article)))
1939          (buffer-read-only nil))
1940     (when (and (file-exists-p file)
1941                (> (nth 7 (file-attributes file)) 0))
1942       (erase-buffer)
1943       (gnus-kill-all-overlays)
1944       (insert-file-contents-as-coding-system gnus-cache-coding-system file)
1945       t)))
1946
1947 (defun gnus-agent-regenerate-group (group &optional clean)
1948   "Regenerate GROUP."
1949   (let ((dir (concat (gnus-agent-directory)
1950                      (gnus-agent-group-path group) "/"))
1951         (file (gnus-agent-article-name ".overview" group))
1952         n point arts alist header new-alist changed)
1953     (when (file-exists-p dir)
1954       (setq arts
1955             (sort (mapcar (lambda (name) (string-to-int name))
1956                           (directory-files dir nil "^[0-9]+$" t))
1957                   '<)))
1958     (gnus-make-directory (nnheader-translate-file-chars
1959                           (file-name-directory file) t))
1960     (mm-with-unibyte-buffer
1961       (if (file-exists-p file)
1962           (let ((nnheader-file-coding-system
1963                  gnus-agent-file-coding-system))
1964             (nnheader-insert-file-contents file)))
1965       (goto-char (point-min))
1966       (while (not (eobp))
1967         (while (not (or (eobp) (looking-at "[0-9]")))
1968           (setq point (point))
1969           (forward-line 1)
1970           (delete-region point (point)))
1971         (unless (eobp)
1972           (setq n (read (current-buffer)))
1973           (when (and arts (> n (car arts)))
1974             (beginning-of-line)
1975             (while (and arts (> n (car arts)))
1976               (message "Regenerating NOV %s %d..." group (car arts))
1977               (mm-with-unibyte-buffer
1978                 (nnheader-insert-file-contents
1979                  (concat dir (number-to-string (car arts))))
1980                 (goto-char (point-min))
1981                 (if (search-forward "\n\n" nil t)
1982                     (delete-region (point) (point-max))
1983                   (goto-char (point-max)))
1984                 (setq header (nnheader-parse-head t)))
1985               (mail-header-set-number header (car arts))
1986               (nnheader-insert-nov header)
1987               (setq changed t)
1988               (push (cons (car arts) t) alist)
1989               (pop arts)))
1990           (if (and arts (= n (car arts)))
1991               (progn
1992                 (push (cons n t) alist)
1993                 (pop arts))
1994             (push (cons n nil) alist))
1995           (forward-line 1)))
1996       (if changed
1997           (write-region-as-coding-system gnus-agent-file-coding-system
1998                                          (point-min) (point-max)
1999                                          file nil 'silent)))
2000     (setq gnus-agent-article-alist nil)
2001     (unless clean
2002       (gnus-agent-load-alist group))
2003     (setq alist (sort alist 'car-less-than-car))
2004     (setq gnus-agent-article-alist (sort gnus-agent-article-alist
2005                                          'car-less-than-car))
2006     (while (and alist gnus-agent-article-alist)
2007       (cond
2008        ((< (caar alist) (caar gnus-agent-article-alist))
2009         (push (pop alist) new-alist))
2010        ((> (caar alist) (caar gnus-agent-article-alist))
2011         (push (list (car (pop gnus-agent-article-alist))) new-alist))
2012        (t
2013         (pop gnus-agent-article-alist)
2014         (while (and gnus-agent-article-alist
2015                     (= (caar alist) (caar gnus-agent-article-alist)))
2016           (pop gnus-agent-article-alist))
2017         (push (pop alist) new-alist))))
2018     (while alist
2019       (push (pop alist) new-alist))
2020     (while gnus-agent-article-alist
2021       (push (list (car (pop gnus-agent-article-alist))) new-alist))
2022     (setq gnus-agent-article-alist (nreverse new-alist))
2023     (gnus-agent-save-alist group)))
2024
2025 (defun gnus-agent-regenerate-history (group article)
2026   (let ((file (concat (gnus-agent-directory)
2027                       (gnus-agent-group-path group) "/"
2028                       (number-to-string article))) id)
2029     (mm-with-unibyte-buffer
2030       (nnheader-insert-file-contents file)
2031       (message-narrow-to-head)
2032       (goto-char (point-min))
2033       (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
2034           (setq id "No-Message-ID-in-article")
2035         (setq id (buffer-substring (match-beginning 1) (match-end 1))))
2036       (gnus-agent-enter-history
2037        id (list (cons group article))
2038        (time-to-days (nth 5 (file-attributes file)))))))
2039
2040 ;;;###autoload
2041 (defun gnus-agent-regenerate (&optional clean)
2042   "Regenerate all agent covered files.
2043 If CLEAN, don't read existing active and agentview files."
2044   (interactive "P")
2045   (message "Regenerating Gnus agent files...")
2046   (dolist (gnus-command-method gnus-agent-covered-methods)
2047     (let ((active-file (gnus-agent-lib-file "active"))
2048           history-hashtb active-hashtb active-changed
2049           history-changed point)
2050       (gnus-make-directory (file-name-directory active-file))
2051       (if clean
2052           (setq active-hashtb (gnus-make-hashtable 1000))
2053         (mm-with-unibyte-buffer
2054           (if (file-exists-p active-file)
2055               (let ((nnheader-file-coding-system
2056                      gnus-agent-file-coding-system))
2057                 (nnheader-insert-file-contents active-file))
2058             (setq active-changed t))
2059           (gnus-active-to-gnus-format
2060            nil (setq active-hashtb
2061                      (gnus-make-hashtable
2062                       (count-lines (point-min) (point-max)))))))
2063       (gnus-agent-open-history)
2064       (setq history-hashtb (gnus-make-hashtable 1000))
2065       (with-current-buffer
2066           (setq gnus-agent-current-history (gnus-agent-history-buffer))
2067         (goto-char (point-min))
2068         (forward-line 1)
2069         (while (not (eobp))
2070           (if (looking-at
2071                "\\([^\t\n]+\\)\t[0-9]+\t\\([^ \n]+\\) \\([0-9]+\\)")
2072               (progn
2073                 (unless (string= (match-string 1)
2074                                  "last-header-fetched-for-session")
2075                   (gnus-sethash (match-string 2)
2076                                 (cons (string-to-number (match-string 3))
2077                                       (gnus-gethash-safe (match-string 2)
2078                                                          history-hashtb))
2079                                 history-hashtb))
2080                 (forward-line 1))
2081             (setq point (point))
2082             (forward-line 1)
2083             (delete-region point (point))
2084             (setq history-changed t))))
2085       (dolist (group (gnus-groups-from-server gnus-command-method))
2086         (gnus-agent-regenerate-group group clean)
2087         (let ((min (or (caar gnus-agent-article-alist) 1))
2088               (max (or (caar (last gnus-agent-article-alist)) 0))
2089               (active (gnus-gethash-safe (gnus-group-real-name group)
2090                                          active-hashtb)))
2091           (if (not active)
2092               (progn
2093                 (setq active (cons min max)
2094                       active-changed t)
2095                 (gnus-sethash group active active-hashtb))
2096             (when (> (car active) min)
2097               (setcar active min)
2098               (setq active-changed t))
2099             (when (< (cdr active) max)
2100               (setcdr active max)
2101               (setq active-changed t))))
2102         (let ((arts (sort (gnus-gethash-safe group history-hashtb) '<))
2103               n)
2104           (gnus-sethash group arts history-hashtb)
2105           (while (and arts gnus-agent-article-alist)
2106             (cond
2107              ((> (car arts) (caar gnus-agent-article-alist))
2108               (when (cdar gnus-agent-article-alist)
2109                 (gnus-agent-regenerate-history
2110                  group (caar gnus-agent-article-alist))
2111                 (setq history-changed t))
2112               (setq n (car (pop gnus-agent-article-alist)))
2113               (while (and gnus-agent-article-alist
2114                           (= n (caar gnus-agent-article-alist)))
2115                 (pop gnus-agent-article-alist)))
2116              ((< (car arts) (caar gnus-agent-article-alist))
2117               (setq n (pop arts))
2118               (while (and arts (= n (car arts)))
2119                 (pop arts)))
2120              (t
2121               (setq n (car (pop gnus-agent-article-alist)))
2122               (while (and gnus-agent-article-alist
2123                           (= n (caar gnus-agent-article-alist)))
2124                 (pop gnus-agent-article-alist))
2125               (setq n (pop arts))
2126               (while (and arts (= n (car arts)))
2127                 (pop arts)))))
2128           (while gnus-agent-article-alist
2129             (when (cdar gnus-agent-article-alist)
2130               (gnus-agent-regenerate-history
2131                group (caar gnus-agent-article-alist))
2132               (setq history-changed t))
2133             (pop gnus-agent-article-alist))))
2134       (when history-changed
2135         (message "Regenerate the history file of %s:%s"
2136                  (car gnus-command-method)
2137                  (cadr gnus-command-method))
2138         (gnus-agent-save-history))
2139       (gnus-agent-close-history)
2140       (when active-changed
2141         (message "Regenerate %s" active-file)
2142         (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2143           (gnus-write-active-file active-file active-hashtb)))))
2144   (message "Regenerating Gnus agent files...done"))
2145
2146 (defun gnus-agent-go-online (&optional force)
2147   "Switch servers into online status."
2148   (interactive (list t))
2149   (dolist (server gnus-opened-servers)
2150     (when (eq (nth 1 server) 'offline)
2151       (if (if (eq force 'ask)
2152               (gnus-y-or-n-p
2153                (format "Switch %s:%s into online status? "
2154                        (caar server) (cadar server)))
2155             force)
2156           (setcar (nthcdr 1 server) 'close)))))
2157
2158 (defun gnus-agent-toggle-group-plugged (group)
2159   "Toggle the status of the server of the current group."
2160   (interactive (list (gnus-group-group-name)))
2161   (let* ((method (gnus-find-method-for-group group))
2162          (status (cadr (assoc method gnus-opened-servers))))
2163     (if (eq status 'offline)
2164         (gnus-server-set-status method 'closed)
2165       (gnus-close-server method)
2166       (gnus-server-set-status method 'offline))
2167     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2168              (if (eq status 'offline) 'offline 'online)
2169              (if (eq status 'offline) 'online 'offline))))
2170
2171 (provide 'gnus-agent)
2172
2173 ;;; gnus-agent.el ends here