Synch to Oort Gnus.
[elisp/gnus.git-] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Semi-gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003
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-handle-level gnus-level-subscribed
62   "Groups on levels higher than this variable will be ignored by the Agent."
63   :group 'gnus-agent
64   :type 'integer)
65
66 (defcustom gnus-agent-expire-days 7
67   "Read articles older than this will be expired.
68 This can also be a list of regexp/day pairs.  The regexps will be
69 matched against group names."
70   :group 'gnus-agent
71   :type '(choice (number :tag "days")
72                  (sexp :tag "List" nil)))
73
74 (defcustom gnus-agent-expire-all nil
75   "If non-nil, also expire unread, ticked and dormant articles.
76 If nil, only read articles will be expired."
77   :group 'gnus-agent
78   :type 'boolean)
79
80 (defcustom gnus-agent-group-mode-hook nil
81   "Hook run in Agent group minor modes."
82   :group 'gnus-agent
83   :type 'hook)
84
85 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
86 (when (featurep 'xemacs)
87   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
88
89 (defcustom gnus-agent-summary-mode-hook nil
90   "Hook run in Agent summary minor modes."
91   :group 'gnus-agent
92   :type 'hook)
93
94 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
95 (when (featurep 'xemacs)
96   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
97
98 (defcustom gnus-agent-server-mode-hook nil
99   "Hook run in Agent summary minor modes."
100   :group 'gnus-agent
101   :type 'hook)
102
103 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
104 (when (featurep 'xemacs)
105   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
106
107 (defcustom gnus-agent-confirmation-function 'y-or-n-p
108   "Function to confirm when error happens."
109   :version "21.1"
110   :group 'gnus-agent
111   :type 'function)
112
113 (defcustom gnus-agent-large-newsgroup nil
114   "*The number of articles which indicates a large newsgroup.
115 If the number of unread articles exceeds it, The number of articles to be
116 fetched will be limited to it. If not a positive integer, never consider it."
117   :group 'gnus-agent
118   :type '(choice (const nil)
119                  (integer :tag "Number")))
120
121 (defcustom gnus-agent-synchronize-flags 'ask
122   "Indicate if flags are synchronized when you plug in.
123 If this is `ask' the hook will query the user."
124   :version "21.1"
125   :type '(choice (const :tag "Always" t)
126                  (const :tag "Never" nil)
127                  (const :tag "Ask" ask))
128   :group 'gnus-agent)
129
130 (defcustom gnus-agent-go-online 'ask
131   "Indicate if offline servers go online when you plug in.
132 If this is `ask' the hook will query the user."
133   :version "21.1"
134   :type '(choice (const :tag "Always" t)
135                  (const :tag "Never" nil)
136                  (const :tag "Ask" ask))
137   :group 'gnus-agent)
138
139 (defcustom gnus-agent-mark-unread-after-downloaded t
140   "Indicate whether to mark articles unread after downloaded."
141   :version "21.1"
142   :type 'boolean
143   :group 'gnus-agent)
144
145 (defcustom gnus-agent-download-marks '(download)
146   "Marks for downloading."
147   :version "21.1"
148   :type '(repeat (symbol :tag "Mark"))
149   :group 'gnus-agent)
150
151 (defcustom gnus-agent-consider-all-articles nil
152   "If non-nil, consider also the read articles for downloading."
153   :version "21.4"
154   :type 'boolean
155   :group 'gnus-agent)
156
157 (defcustom gnus-agent-max-fetch-size 10000000 ;; 10 Mb
158   "Chunk size for `gnus-agent-fetch-session'.
159 The function will split its article fetches into chunks smaller than
160 this limit."
161   :group 'gnus-agent
162   :type 'integer)
163
164 ;;; Internal variables
165
166 (defvar gnus-agent-history-buffers nil)
167 (defvar gnus-agent-buffer-alist nil)
168 (defvar gnus-agent-article-alist nil
169 "An assoc list identifying the articles whose headers have been fetched.  
170 If successfully fetched, these headers will be stored in the group's overview
171 file.  The key of each assoc pair is the article ID, the value of each assoc
172 pair is a flag indicating whether the identified article has been downloaded
173 \(gnus-agent-fetch-articles sets the value to the day of the download).
174 NOTES:
175 1) The last element of this list can not be expired as some 
176    routines (for example, get-agent-fetch-headers) use the last
177    value to track which articles have had their headers retrieved.
178 2) The gnus-agent-regenerate may destructively modify the value.
179 ")
180 (defvar gnus-agent-group-alist nil)
181 (defvar gnus-category-alist nil)
182 (defvar gnus-agent-current-history nil)
183 (defvar gnus-agent-overview-buffer nil)
184 (defvar gnus-category-predicate-cache nil)
185 (defvar gnus-category-group-cache nil)
186 (defvar gnus-agent-spam-hashtb nil)
187 (defvar gnus-agent-file-name nil)
188 (defvar gnus-agent-send-mail-function nil)
189 (defvar gnus-agent-file-coding-system 'raw-text)
190 (defvar gnus-agent-file-loading-cache nil)
191 (defvar gnus-agent-file-header-cache nil)
192
193 (defvar gnus-agent-auto-agentize-methods '(nntp nnimap)
194   "Initially, all servers from these methods are agentized.
195 The user may remove or add servers using the Server buffer.  See Info
196 node `(gnus)Server Buffer'.")
197
198 ;; Dynamic variables
199 (defvar gnus-headers)
200 (defvar gnus-score)
201
202 ;;;
203 ;;; Setup
204 ;;;
205
206 (defun gnus-open-agent ()
207   (setq gnus-agent t)
208   (gnus-agent-read-servers)
209   (gnus-category-read)
210   (gnus-agent-create-buffer)
211   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
212   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
213   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
214
215 (defun gnus-agent-create-buffer ()
216   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
217       t
218     (setq gnus-agent-overview-buffer
219           (gnus-get-buffer-create " *Gnus agent overview*"))
220     (with-current-buffer gnus-agent-overview-buffer
221       (set-buffer-multibyte t))
222     nil))
223
224 (gnus-add-shutdown 'gnus-close-agent 'gnus)
225
226 (defun gnus-close-agent ()
227   (setq gnus-category-predicate-cache nil
228         gnus-category-group-cache nil
229         gnus-agent-spam-hashtb nil)
230   (gnus-kill-buffer gnus-agent-overview-buffer))
231
232 ;;;
233 ;;; Utility functions
234 ;;;
235
236 (defun gnus-agent-read-file (file)
237   "Load FILE and do a `read' there."
238   (with-temp-buffer
239     (ignore-errors
240       (nnheader-insert-file-contents file)
241       (goto-char (point-min))
242       (read (current-buffer)))))
243
244 (defsubst gnus-agent-method ()
245   (concat (symbol-name (car gnus-command-method)) "/"
246           (if (equal (cadr gnus-command-method) "")
247               "unnamed"
248             (cadr gnus-command-method))))
249
250 (defsubst gnus-agent-directory ()
251   "The name of the Gnus agent directory."
252   (nnheader-concat gnus-agent-directory
253                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
254
255 (defun gnus-agent-lib-file (file)
256   "The full name of the Gnus agent library FILE."
257   (expand-file-name file
258                     (file-name-as-directory
259                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
260
261 ;;; Fetching setup functions.
262
263 (defun gnus-agent-start-fetch ()
264   "Initialize data structures for efficient fetching."
265   (gnus-agent-create-buffer))
266
267 (defun gnus-agent-stop-fetch ()
268   "Save all data structures and clean up."
269   (setq gnus-agent-spam-hashtb nil)
270   (save-excursion
271     (set-buffer nntp-server-buffer)
272     (widen)))
273
274 (defmacro gnus-agent-with-fetch (&rest forms)
275   "Do FORMS safely."
276   `(unwind-protect
277        (let ((gnus-agent-fetching t))
278          (gnus-agent-start-fetch)
279          ,@forms)
280      (gnus-agent-stop-fetch)))
281
282 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
283 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
284
285 (defmacro gnus-agent-append-to-list (tail value)
286   `(setq ,tail (setcdr ,tail (cons ,value nil))))
287
288 ;;;
289 ;;; Mode infestation
290 ;;;
291
292 (defvar gnus-agent-mode-hook nil
293   "Hook run when installing agent mode.")
294
295 (defvar gnus-agent-mode nil)
296 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
297
298 (defun gnus-agent-mode ()
299   "Minor mode for providing a agent support in Gnus buffers."
300   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
301                                       (symbol-name major-mode))
302                         (match-string 1 (symbol-name major-mode))))
303          (mode (intern (format "gnus-agent-%s-mode" buffer))))
304     (set (make-local-variable 'gnus-agent-mode) t)
305     (set mode nil)
306     (set (make-local-variable mode) t)
307     ;; Set up the menu.
308     (when (gnus-visual-p 'agent-menu 'menu)
309       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
310     (unless (assq 'gnus-agent-mode minor-mode-alist)
311       (push gnus-agent-mode-status minor-mode-alist))
312     (unless (assq mode minor-mode-map-alist)
313       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
314                                                      buffer))))
315             minor-mode-map-alist))
316     (when (eq major-mode 'gnus-group-mode)
317       (gnus-agent-toggle-plugged gnus-plugged))
318     (gnus-run-hooks 'gnus-agent-mode-hook
319                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
320
321 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
322 (gnus-define-keys gnus-agent-group-mode-map
323   "Ju" gnus-agent-fetch-groups
324   "Jc" gnus-enter-category-buffer
325   "Jj" gnus-agent-toggle-plugged
326   "Js" gnus-agent-fetch-session
327   "JY" gnus-agent-synchronize-flags
328   "JS" gnus-group-send-queue
329   "Ja" gnus-agent-add-group
330   "Jr" gnus-agent-remove-group
331   "Jo" gnus-agent-toggle-group-plugged)
332
333 (defun gnus-agent-group-make-menu-bar ()
334   (unless (boundp 'gnus-agent-group-menu)
335     (easy-menu-define
336      gnus-agent-group-menu gnus-agent-group-mode-map ""
337      '("Agent"
338        ["Toggle plugged" gnus-agent-toggle-plugged t]
339        ["Toggle group plugged" gnus-agent-toggle-group-plugged t]
340        ["List categories" gnus-enter-category-buffer t]
341        ["Send queue" gnus-group-send-queue gnus-plugged]
342        ("Fetch"
343         ["All" gnus-agent-fetch-session gnus-plugged]
344         ["Group" gnus-agent-fetch-group gnus-plugged])))))
345
346 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
347 (gnus-define-keys gnus-agent-summary-mode-map
348   "Jj" gnus-agent-toggle-plugged
349   "Ju" gnus-agent-summary-fetch-group
350   "JS" gnus-agent-fetch-group
351   "Js" gnus-agent-summary-fetch-series
352   "J#" gnus-agent-mark-article
353   "J\M-#" gnus-agent-unmark-article
354   "@" gnus-agent-toggle-mark
355   "Jc" gnus-agent-catchup)
356
357 (defun gnus-agent-summary-make-menu-bar ()
358   (unless (boundp 'gnus-agent-summary-menu)
359     (easy-menu-define
360      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
361      '("Agent"
362        ["Toggle plugged" gnus-agent-toggle-plugged t]
363        ["Mark as downloadable" gnus-agent-mark-article t]
364        ["Unmark as downloadable" gnus-agent-unmark-article t]
365        ["Toggle mark" gnus-agent-toggle-mark t]
366        ["Fetch downloadable" gnus-agent-summary-fetch-group t]
367        ["Catchup undownloaded" gnus-agent-catchup t]))))
368
369 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
370 (gnus-define-keys gnus-agent-server-mode-map
371   "Jj" gnus-agent-toggle-plugged
372   "Ja" gnus-agent-add-server
373   "Jr" gnus-agent-remove-server)
374
375 (defun gnus-agent-server-make-menu-bar ()
376   (unless (boundp 'gnus-agent-server-menu)
377     (easy-menu-define
378      gnus-agent-server-menu gnus-agent-server-mode-map ""
379      '("Agent"
380        ["Toggle plugged" gnus-agent-toggle-plugged t]
381        ["Add" gnus-agent-add-server t]
382        ["Remove" gnus-agent-remove-server t]))))
383
384 (defun gnus-agent-make-mode-line-string (string mouse-button mouse-func)
385   (if (and (fboundp 'propertize)
386            (fboundp 'make-mode-line-mouse-map))
387       (propertize string 'local-map
388                   (make-mode-line-mouse-map mouse-button mouse-func))
389     string))
390
391 (defun gnus-agent-toggle-plugged (plugged)
392   "Toggle whether Gnus is unplugged or not."
393   (interactive (list (not gnus-plugged)))
394   (if plugged
395       (progn
396         (setq gnus-plugged plugged)
397         (gnus-run-hooks 'gnus-agent-plugged-hook)
398         (setcar (cdr gnus-agent-mode-status)
399                 (gnus-agent-make-mode-line-string " Plugged"
400                                                   'mouse-2
401                                                   'gnus-agent-toggle-plugged))
402         (gnus-agent-go-online gnus-agent-go-online)
403         (gnus-agent-possibly-synchronize-flags))
404     (gnus-agent-close-connections)
405     (setq gnus-plugged plugged)
406     (gnus-run-hooks 'gnus-agent-unplugged-hook)
407     (setcar (cdr gnus-agent-mode-status)
408             (gnus-agent-make-mode-line-string " Unplugged"
409                                               'mouse-2
410                                               'gnus-agent-toggle-plugged)))
411   (force-mode-line-update)
412   (set-buffer-modified-p t))
413
414 (defun gnus-agent-close-connections ()
415   "Close all methods covered by the Gnus agent."
416   (let ((methods gnus-agent-covered-methods))
417     (while methods
418       (gnus-close-server (pop methods)))))
419
420 ;;;###autoload
421 (defun gnus-unplugged ()
422   "Start Gnus unplugged."
423   (interactive)
424   (setq gnus-plugged nil)
425   (gnus))
426
427 ;;;###autoload
428 (defun gnus-plugged ()
429   "Start Gnus plugged."
430   (interactive)
431   (setq gnus-plugged t)
432   (gnus))
433
434 ;;;###autoload
435 (defun gnus-slave-unplugged (&optional arg)
436   "Read news as a slave unplugged."
437   (interactive "P")
438   (setq gnus-plugged nil)
439   (gnus arg nil 'slave))
440
441 ;;;###autoload
442 (defun gnus-agentize ()
443   "Allow Gnus to be an offline newsreader.
444 The normal usage of this command is to put the following as the
445 last form in your `.gnus.el' file:
446
447 \(gnus-agentize)
448
449 This will modify the `gnus-setup-news-hook', and
450 `message-send-mail-real-function' variables, and install the Gnus agent
451 minor mode in all Gnus buffers."
452   (interactive)
453   (gnus-open-agent)
454   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
455   (unless gnus-agent-send-mail-function
456     (setq gnus-agent-send-mail-function
457           (or message-send-mail-real-function
458               message-send-mail-function)
459           message-send-mail-real-function 'gnus-agent-send-mail))
460
461   (unless gnus-agent-covered-methods
462     (mapcar
463      (lambda (server)
464        (if (memq (car (gnus-server-to-method server)) 
465                  gnus-agent-auto-agentize-methods)
466            (setq gnus-agent-covered-methods 
467                  (cons (gnus-server-to-method server)
468                        gnus-agent-covered-methods ))))
469      (append (list gnus-select-method) gnus-secondary-select-methods))))
470
471 (defun gnus-agent-queue-setup ()
472   "Make sure the queue group exists."
473   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
474     (gnus-request-create-group "queue" '(nndraft ""))
475     (let ((gnus-level-default-subscribed 1))
476       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
477     (gnus-group-set-parameter
478      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
479
480 (defun gnus-agent-send-mail ()
481   (if gnus-plugged
482       (funcall gnus-agent-send-mail-function)
483     (goto-char (point-min))
484     (re-search-forward
485      (concat "^" (regexp-quote mail-header-separator) "\n"))
486     (replace-match "\n")
487     (gnus-agent-insert-meta-information 'mail)
488     (gnus-request-accept-article "nndraft:queue" nil t t)))
489
490 (defun gnus-agent-insert-meta-information (type &optional method)
491   "Insert meta-information into the message that says how it's to be posted.
492 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
493 be a select method."
494   (save-excursion
495     (message-remove-header gnus-agent-meta-information-header)
496     (goto-char (point-min))
497     (insert gnus-agent-meta-information-header ": "
498             (symbol-name type) " " (format "%S" method)
499             "\n")
500     (forward-char -1)
501     (while (search-backward "\n" nil t)
502       (replace-match "\\n" t t))))
503
504 (defun gnus-agent-restore-gcc ()
505   "Restore GCC field from saved header."
506   (save-excursion
507     (goto-char (point-min))
508     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
509       (replace-match "Gcc:" 'fixedcase))))
510
511 (defun gnus-agent-any-covered-gcc ()
512   (save-restriction
513     (message-narrow-to-headers)
514     (let* ((gcc (mail-fetch-field "gcc" nil t))
515            (methods (and gcc
516                          (mapcar 'gnus-inews-group-method
517                                  (message-unquote-tokens
518                                   (message-tokenize-header
519                                    gcc " ,")))))
520            covered)
521       (while (and (not covered) methods)
522         (setq covered (gnus-agent-method-p (car methods))
523               methods (cdr methods)))
524       covered)))
525
526 ;;;###autoload
527 (defun gnus-agent-possibly-save-gcc ()
528   "Save GCC if Gnus is unplugged."
529   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
530     (save-excursion
531       (goto-char (point-min))
532       (let ((case-fold-search t))
533         (while (re-search-forward "^gcc:" nil t)
534           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
535
536 (defun gnus-agent-possibly-do-gcc ()
537   "Do GCC if Gnus is plugged."
538   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
539     (gnus-inews-do-gcc)))
540
541 ;;;
542 ;;; Group mode commands
543 ;;;
544
545 (defun gnus-agent-fetch-groups (n)
546   "Put all new articles in the current groups into the Agent."
547   (interactive "P")
548   (unless gnus-plugged
549     (error "Groups can't be fetched when Gnus is unplugged"))
550   (gnus-group-iterate n 'gnus-agent-fetch-group))
551
552 (defun gnus-agent-fetch-group (&optional group)
553   "Put all new articles in GROUP into the Agent."
554   (interactive (list (gnus-group-group-name)))
555   (let ((state gnus-plugged))
556     (unwind-protect
557         (progn
558           (setq group (or group gnus-newsgroup-name))
559           (unless group
560             (error "No group on the current line"))
561           (unless state
562             (gnus-agent-toggle-plugged gnus-plugged))
563           (let ((gnus-command-method (gnus-find-method-for-group group)))
564             (gnus-agent-with-fetch
565               (gnus-agent-fetch-group-1 group gnus-command-method)
566               (gnus-message 5 "Fetching %s...done" group))))
567       (when (and (not state)
568                  gnus-plugged)
569         (gnus-agent-toggle-plugged gnus-plugged)))))
570
571 (defun gnus-agent-add-group (category arg)
572   "Add the current group to an agent category."
573   (interactive
574    (list
575     (intern
576      (completing-read
577       "Add to category: "
578       (mapcar (lambda (cat) (list (symbol-name (car cat))))
579               gnus-category-alist)
580       nil t))
581     current-prefix-arg))
582   (let ((cat (assq category gnus-category-alist))
583         c groups)
584     (gnus-group-iterate arg
585       (lambda (group)
586         (when (cadddr (setq c (gnus-group-category group)))
587           (setf (cadddr c) (delete group (cadddr c))))
588         (push group groups)))
589     (setf (cadddr cat) (nconc (cadddr cat) groups))
590     (gnus-category-write)))
591
592 (defun gnus-agent-remove-group (arg)
593   "Remove the current group from its agent category, if any."
594   (interactive "P")
595   (let (c)
596     (gnus-group-iterate arg
597       (lambda (group)
598         (when (cadddr (setq c (gnus-group-category group)))
599           (setf (cadddr c) (delete group (cadddr c))))))
600     (gnus-category-write)))
601
602 (defun gnus-agent-synchronize-flags ()
603   "Synchronize unplugged flags with servers."
604   (interactive)
605   (save-excursion
606     (dolist (gnus-command-method gnus-agent-covered-methods)
607       (when (file-exists-p (gnus-agent-lib-file "flags"))
608         (gnus-agent-synchronize-flags-server gnus-command-method)))))
609
610 (defun gnus-agent-possibly-synchronize-flags ()
611   "Synchronize flags according to `gnus-agent-synchronize-flags'."
612   (interactive)
613   (save-excursion
614     (dolist (gnus-command-method gnus-agent-covered-methods)
615       (when (file-exists-p (gnus-agent-lib-file "flags"))
616         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
617
618 (defun gnus-agent-synchronize-flags-server (method)
619   "Synchronize flags set when unplugged for server."
620   (let ((gnus-command-method method))
621     (when (file-exists-p (gnus-agent-lib-file "flags"))
622       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
623       (erase-buffer)
624       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
625       (if (null (gnus-check-server gnus-command-method))
626           (gnus-message 1 "Couldn't open server %s" (nth 1 gnus-command-method))
627         (while (not (eobp))
628           (if (null (eval (read (current-buffer))))
629               (progn (forward-line)
630                      (kill-line -1))
631             (write-file (gnus-agent-lib-file "flags"))
632             (error "Couldn't set flags from file %s"
633                    (gnus-agent-lib-file "flags"))))
634         (delete-file (gnus-agent-lib-file "flags")))
635       (kill-buffer nil))))
636
637 (defun gnus-agent-possibly-synchronize-flags-server (method)
638   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
639   (when (or (and gnus-agent-synchronize-flags
640                  (not (eq gnus-agent-synchronize-flags 'ask)))
641             (and (eq gnus-agent-synchronize-flags 'ask)
642                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
643                                         (cadr method)))))
644     (gnus-agent-synchronize-flags-server method)))
645
646 ;;;
647 ;;; Server mode commands
648 ;;;
649
650 (defun gnus-agent-add-server (server)
651   "Enroll SERVER in the agent program."
652   (interactive (list (gnus-server-server-name)))
653   (unless server
654     (error "No server on the current line"))
655   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
656     (when (gnus-agent-method-p method)
657       (error "Server already in the agent program"))
658     (push method gnus-agent-covered-methods)
659     (gnus-server-update-server server)
660     (gnus-agent-write-servers)
661     (gnus-message 1 "Entered %s into the Agent" server)))
662
663 (defun gnus-agent-remove-server (server)
664   "Remove SERVER from the agent program."
665   (interactive (list (gnus-server-server-name)))
666   (unless server
667     (error "No server on the current line"))
668   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
669     (unless (gnus-agent-method-p method)
670       (error "Server not in the agent program"))
671     (setq gnus-agent-covered-methods
672           (delete method gnus-agent-covered-methods))
673     (gnus-server-update-server server)
674     (gnus-agent-write-servers)
675     (gnus-message 1 "Removed %s from the agent" server)))
676
677 (defun gnus-agent-read-servers ()
678   "Read the alist of covered servers."
679   (mapcar (lambda (m)
680             (let ((method (gnus-server-get-method
681                            nil
682                            (or m "native"))))
683               (if method
684                   (unless (member method gnus-agent-covered-methods)
685                     (push method gnus-agent-covered-methods))
686                 (gnus-message 1 "Ignoring disappeared server `%s'" m)
687                 (sit-for 1))))
688           (gnus-agent-read-file
689            (nnheader-concat gnus-agent-directory "lib/servers"))))
690
691 (defun gnus-agent-write-servers ()
692   "Write the alist of covered servers."
693   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
694   (let ((coding-system-for-write nnheader-file-coding-system)
695         (output-coding-system nnheader-file-coding-system)
696         (file-name-coding-system nnmail-pathname-coding-system)
697         (pathname-coding-system nnmail-pathname-coding-system))
698     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
699       (prin1 (mapcar 'gnus-method-simplify gnus-agent-covered-methods)
700              (current-buffer)))))
701
702 ;;;
703 ;;; Summary commands
704 ;;;
705
706 (defun gnus-agent-mark-article (n &optional unmark)
707   "Mark the next N articles as downloadable.
708 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
709 the mark instead.  The difference between N and the actual number of
710 articles marked is returned."
711   (interactive "p")
712   (let ((backward (< n 0))
713         (n (abs n)))
714     (while (and
715             (> n 0)
716             (progn
717               (gnus-summary-set-agent-mark
718                (gnus-summary-article-number) unmark)
719               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
720       (setq n (1- n)))
721     (when (/= 0 n)
722       (gnus-message 7 "No more articles"))
723     (gnus-summary-recenter)
724     (gnus-summary-position-point)
725     n))
726
727 (defun gnus-agent-unmark-article (n)
728   "Remove the downloadable mark from the next N articles.
729 If N is negative, unmark backward instead.  The difference between N and
730 the actual number of articles unmarked is returned."
731   (interactive "p")
732   (gnus-agent-mark-article n t))
733
734 (defun gnus-agent-toggle-mark (n)
735   "Toggle the downloadable mark from the next N articles.
736 If N is negative, toggle backward instead.  The difference between N and
737 the actual number of articles toggled is returned."
738   (interactive "p")
739   (gnus-agent-mark-article n 'toggle))
740
741 (defun gnus-summary-set-agent-mark (article &optional unmark)
742   "Mark ARTICLE as downloadable.  If UNMARK is nil, article is marked.
743 When UNMARK is t, the article is unmarked.  For any other value, the
744 article's mark is toggled."
745   (let ((unmark (cond ((eq nil unmark)
746                        nil)
747                       ((eq t unmark)
748                        t)
749                       (t
750                        (memq article gnus-newsgroup-downloadable)))))
751     (when (gnus-summary-goto-subject article nil t)
752       (gnus-summary-update-mark
753        (if unmark
754            (progn
755              (setq gnus-newsgroup-downloadable
756                    (delq article gnus-newsgroup-downloadable))
757              (gnus-article-mark article))
758          (progn
759            (setq gnus-newsgroup-downloadable
760                  (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
761            gnus-downloadable-mark)
762          )
763        'unread))))
764
765 (defun gnus-agent-get-undownloaded-list ()
766   "Construct list of articles that have not been downloaded."
767   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
768     (when (set (make-local-variable 'gnus-newsgroup-agentized) (gnus-agent-method-p gnus-command-method))
769       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
770              (headers gnus-newsgroup-headers)
771              (undownloaded (list nil))
772              (tail-undownloaded undownloaded)
773              (unfetched (list nil))
774              (tail-unfetched unfetched))
775         (while (and alist headers)
776           (let ((a (caar alist))
777                 (h (mail-header-number (car headers))))
778             (cond ((< a h)
779                    ;; Ignore IDs in the alist that are not being
780                    ;; displayed in the summary.
781                    (pop alist))
782                   ((> a h)
783                    ;; Headers that are not in the alist should be
784                    ;; fictious (see nnagent-retrieve-headers); they
785                    ;; imply that this article isn't in the agent.
786                    (gnus-agent-append-to-list tail-undownloaded h)
787                    (gnus-agent-append-to-list tail-unfetched    h)
788                    (pop headers)) 
789                   ((cdar alist)
790                    (pop alist)
791                    (pop headers)
792                    nil                  ; ignore already downloaded
793                    )
794                   (t
795                    (pop alist)
796                    (pop headers)
797                    (gnus-agent-append-to-list tail-undownloaded a)))))
798
799         (while headers
800           (let ((num (mail-header-number (pop headers))))
801             (gnus-agent-append-to-list tail-undownloaded num)
802             (gnus-agent-append-to-list tail-unfetched    num)))
803
804         (setq gnus-newsgroup-undownloaded (cdr undownloaded)
805               gnus-newsgroup-unfetched    (cdr unfetched))))))
806
807 (defun gnus-agent-catchup ()
808   "Mark as read all unhandled articles.
809 An article is unhandled if it is neither cached, nor downloaded, nor
810 downloadable."
811   (interactive)
812   (save-excursion
813     (let ((articles gnus-newsgroup-undownloaded))
814       (when (or gnus-newsgroup-downloadable
815                 gnus-newsgroup-cached)
816         (setq articles (gnus-sorted-ndifference
817                         (gnus-sorted-ndifference
818                          (copy-sequence articles)
819                          gnus-newsgroup-downloadable)
820                         gnus-newsgroup-cached)))
821
822       (while articles
823         (gnus-summary-mark-article
824          (pop articles) gnus-catchup-mark)))
825     (gnus-summary-position-point)))
826
827 (defun gnus-agent-summary-fetch-series ()
828   (interactive)
829   (when gnus-newsgroup-processable
830     (setq gnus-newsgroup-downloadable
831           (let* ((dl gnus-newsgroup-downloadable)
832                  (gnus-newsgroup-downloadable
833                   (sort (copy-sequence gnus-newsgroup-processable) '<))
834                  (fetched-articles (gnus-agent-summary-fetch-group)))
835             ;; The preceeding call to (gnus-agent-summary-fetch-group)
836             ;; updated gnus-newsgroup-downloadable to remove each
837             ;; article successfully fetched.
838
839             ;; For each article that I processed, remove its
840             ;; processable mark IF the article is no longer
841             ;; downloadable (i.e. it's already downloaded)
842             (dolist (article gnus-newsgroup-processable)
843               (unless (memq article gnus-newsgroup-downloadable)
844                 (gnus-summary-remove-process-mark article)))
845             (gnus-sorted-ndifference dl fetched-articles)))))
846
847 (defun gnus-agent-summary-fetch-group (&optional all)
848   "Fetch the downloadable articles in the group.
849 Optional arg ALL, if non-nil, means to fetch all articles."
850   (interactive "P")
851   (let ((articles
852          (if all gnus-newsgroup-articles
853            gnus-newsgroup-downloadable))
854         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
855         (state gnus-plugged)
856         fetched-articles)
857     (unwind-protect
858         (progn
859           (unless state
860             (gnus-agent-toggle-plugged t))
861           (unless articles
862             (error "No articles to download"))
863           (gnus-agent-with-fetch
864             (setq gnus-newsgroup-undownloaded
865                   (gnus-sorted-ndifference
866                    gnus-newsgroup-undownloaded
867                    (setq fetched-articles
868                          (gnus-agent-fetch-articles
869                           gnus-newsgroup-name articles)))))
870           (save-excursion
871             (dolist (article articles)
872               (let ((was-marked-downloadable
873                      (memq article gnus-newsgroup-downloadable)))
874                 (when
875                     (cond
876                      (gnus-agent-mark-unread-after-downloaded
877                       (setq gnus-newsgroup-downloadable
878                             (delq article gnus-newsgroup-downloadable))
879
880                       ;; The downloadable mark is implemented as a
881                       ;; type of read mark.  Therefore, marking the
882                       ;; article as unread is sufficient to clear
883                       ;; its downloadable flag.
884                       (gnus-summary-mark-article article gnus-unread-mark)
885                       ;; I just redrew the entire article so
886                       ;; there's no need to update the download
887                       ;; mark below.
888                       nil)
889                      (was-marked-downloadable
890                       (gnus-summary-set-agent-mark article t)
891                       t)
892                      (t t))
893                   (when (gnus-summary-goto-subject article nil t)
894                     (gnus-summary-update-download-mark article)))))))
895       (when (and (not state)
896                  gnus-plugged)
897         (gnus-agent-toggle-plugged nil)))
898     fetched-articles))
899
900 (defun gnus-agent-fetch-selected-article ()
901   "Fetch the current article as it is selected.
902 This can be added to `gnus-select-article-hook' or
903 `gnus-mark-article-hook'."
904   (let ((gnus-command-method gnus-current-select-method))
905     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
906       (when (gnus-agent-fetch-articles
907              gnus-newsgroup-name
908              (list gnus-current-article))
909         (setq gnus-newsgroup-undownloaded
910               (delq gnus-current-article gnus-newsgroup-undownloaded))
911         (gnus-summary-update-article-line
912          gnus-current-article
913          (gnus-summary-article-header gnus-current-article))))))
914
915 ;;;
916 ;;; Internal functions
917 ;;;
918
919 (defun gnus-agent-save-active (method)
920   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
921
922 (defun gnus-agent-save-active-1 (method function)
923   (when (gnus-agent-method-p method)
924     (let* ((gnus-command-method method)
925            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
926            (file (gnus-agent-lib-file "active")))
927       (funcall function nil new)
928       (gnus-agent-write-active file new)
929       (erase-buffer)
930       (nnheader-insert-file-contents file))))
931
932 (defun gnus-agent-write-active (file new)
933   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
934         (file (gnus-agent-lib-file "active"))
935         elem osym)
936     (when (file-exists-p file)
937       (with-temp-buffer
938         (nnheader-insert-file-contents file)
939         (gnus-active-to-gnus-format nil orig))
940       (mapatoms
941        (lambda (sym)
942          (when (and sym (boundp sym))
943            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
944                     (setq elem (symbol-value osym)))
945                (progn
946                  (if (and (integerp (car (symbol-value sym)))
947                           (> (car elem) (car (symbol-value sym))))
948                      (setcar elem (car (symbol-value sym))))
949                  (if (integerp (cdr (symbol-value sym)))
950                      (setcdr elem (cdr (symbol-value sym)))))
951              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
952        new))
953     (gnus-make-directory (file-name-directory file))
954     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
955       ;; The hashtable contains real names of groups,  no more prefix
956       ;; removing, so set `full' to `t'.
957       (gnus-write-active-file file orig t))))
958
959 (defun gnus-agent-save-groups (method)
960   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
961
962 (defun gnus-agent-save-group-info (method group active)
963   (when (gnus-agent-method-p method)
964     (let* ((gnus-command-method method)
965            (coding-system-for-write nnheader-file-coding-system)
966            (output-coding-system nnheader-file-coding-system)
967            (file-name-coding-system nnmail-pathname-coding-system)
968            (pathname-coding-system nnmail-pathname-coding-system)
969            (file (gnus-agent-lib-file "active"))
970            oactive-min)
971       (gnus-make-directory (file-name-directory file))
972       (with-temp-file file
973         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
974         (set-buffer-multibyte nil)
975         (when (file-exists-p file)
976           (nnheader-insert-file-contents file))
977         (goto-char (point-min))
978         (when (re-search-forward
979                (concat "^" (regexp-quote group) " ") nil t)
980           (save-excursion
981             (read (current-buffer))                      ;; max
982             (setq oactive-min (read (current-buffer))))  ;; min
983           (gnus-delete-line))
984         (insert (format "%S %d %d y\n" (intern group)
985                         (cdr active)
986                         (or oactive-min (car active))))
987         (goto-char (point-max))
988         (while (search-backward "\\." nil t)
989           (delete-char 1))))))
990
991 (defun gnus-agent-group-path (group)
992   "Translate GROUP into a file name."
993   (if nnmail-use-long-file-names
994       (gnus-group-real-name group)
995     (nnheader-translate-file-chars
996      (nnheader-replace-chars-in-string
997       (nnheader-replace-duplicate-chars-in-string
998        (nnheader-replace-chars-in-string
999         (gnus-group-real-name group)
1000         ?/ ?_)
1001        ?. ?_)
1002       ?. ?/))))
1003
1004 (defun gnus-agent-get-function (method)
1005   (if (gnus-online method)
1006       (car method)
1007     (require 'nnagent)
1008     'nnagent))
1009
1010 ;;; History functions
1011
1012 (defun gnus-agent-history-buffer ()
1013   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1014
1015 (defun gnus-agent-open-history ()
1016   (save-excursion
1017     (push (cons (gnus-agent-method)
1018                 (set-buffer (gnus-get-buffer-create
1019                              (format " *Gnus agent %s history*"
1020                                      (gnus-agent-method)))))
1021           gnus-agent-history-buffers)
1022     (set-buffer-multibyte nil) ;; everything is binary
1023     (erase-buffer)
1024     (insert "\n")
1025     (let ((file (gnus-agent-lib-file "history")))
1026       (when (file-exists-p file)
1027         (nnheader-insert-file-contents file))
1028       (set (make-local-variable 'gnus-agent-file-name) file))))
1029
1030 (defun gnus-agent-close-history ()
1031   (when (gnus-buffer-live-p gnus-agent-current-history)
1032     (kill-buffer gnus-agent-current-history)
1033     (setq gnus-agent-history-buffers
1034           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1035                 gnus-agent-history-buffers))))
1036
1037 ;;;
1038 ;;; Fetching
1039 ;;;
1040
1041 (defun gnus-agent-fetch-articles (group articles)
1042   "Fetch ARTICLES from GROUP and put them into the Agent."
1043   (when articles
1044     (gnus-agent-load-alist group)
1045     (let* ((alist   gnus-agent-article-alist)
1046            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1047            (selected-sets (list nil))
1048            (current-set-size 0)
1049            article
1050            header-number)
1051       ;; Check each article
1052       (while (setq article (pop articles))
1053         ;; Skip alist entries preceeding this article
1054         (while (> article (or (caar alist) (1+ article)))
1055           (setq alist (cdr alist)))
1056
1057         ;; Prune off articles that we have already fetched.
1058         (unless (and (eq article (caar alist))
1059                      (cdar alist))
1060           ;; Skip headers preceeding this article
1061           (while (> article 
1062                     (setq header-number
1063                           (let* ((header (car headers)))
1064                             (if header
1065                                 (mail-header-number header)
1066                               (1+ article)))))
1067             (setq headers (cdr headers)))
1068
1069           ;; Add this article to the current set
1070           (setcar selected-sets (cons article (car selected-sets)))
1071
1072           ;; Update the set size, when the set is too large start a
1073           ;; new one.  I do this after adding the article as I want at
1074           ;; least one article in each set.
1075           (when (< gnus-agent-max-fetch-size
1076                    (setq current-set-size
1077                          (+ current-set-size
1078                             (if (= header-number article)
1079                                 (mail-header-chars (car headers))
1080                               0))))
1081             (setcar selected-sets (nreverse (car selected-sets)))
1082             (setq selected-sets (cons nil selected-sets)
1083                   current-set-size 0))))
1084
1085       (when (or (cdr selected-sets) (car selected-sets))
1086         (let* ((fetched-articles (list nil))
1087                (tail-fetched-articles fetched-articles)
1088                (dir (concat
1089                      (gnus-agent-directory)
1090                      (gnus-agent-group-path group) "/"))
1091                (date (time-to-days (current-time)))
1092                (case-fold-search t)
1093                pos crosses id)
1094
1095           (setcar selected-sets (nreverse (car selected-sets)))
1096           (setq selected-sets (nreverse selected-sets))
1097
1098           (gnus-make-directory dir)
1099           (gnus-message 7 "Fetching articles for %s..." group)
1100           
1101           (unwind-protect
1102               (while (setq articles (pop selected-sets))
1103                 ;; Fetch the articles from the backend.
1104                 (if (gnus-check-backend-function 'retrieve-articles group)
1105                     (setq pos (gnus-retrieve-articles articles group))
1106                   (with-temp-buffer
1107                     (let (article)
1108                       (while (setq article (pop articles))
1109                         (gnus-message 10 "Fetching article %s for %s..."
1110                                       article group)
1111                         (when (or
1112                                (gnus-backlog-request-article group article
1113                                                              nntp-server-buffer)
1114                                (gnus-request-article article group))
1115                           (goto-char (point-max))
1116                           (push (cons article (point)) pos)
1117                           (insert-buffer-substring nntp-server-buffer)))
1118                       (copy-to-buffer
1119                        nntp-server-buffer (point-min) (point-max))
1120                       (setq pos (nreverse pos)))))
1121                 ;; Then save these articles into the Agent.
1122                 (save-excursion
1123                   (set-buffer nntp-server-buffer)
1124                   (while pos
1125                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1126                     (goto-char (point-min))
1127                     (unless (eobp) ;; Don't save empty articles.
1128                       (when (search-forward "\n\n" nil t)
1129                         (when (search-backward "\nXrefs: " nil t)
1130                           ;; Handle cross posting.
1131                           (goto-char (match-end 0)) ; move to end of header name
1132                           (skip-chars-forward "^ ") ; skip server name
1133                           (skip-chars-forward " ")
1134                           (setq crosses nil)
1135                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1136                             (push (cons (buffer-substring (match-beginning 1)
1137                                                           (match-end 1))
1138                                         (string-to-int
1139                                          (buffer-substring (match-beginning 2)
1140                                                            (match-end 2))))
1141                                   crosses)
1142                             (goto-char (match-end 0)))
1143                           (gnus-agent-crosspost crosses (caar pos) date)))
1144                       (goto-char (point-min))
1145                       (if (not (re-search-forward
1146                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1147                           (setq id "No-Message-ID-in-article")
1148                         (setq id (buffer-substring
1149                                   (match-beginning 1) (match-end 1))))
1150                       (write-region-as-coding-system
1151                        gnus-agent-file-coding-system (point-min) (point-max)
1152                        (concat dir (number-to-string (caar pos))) nil 'silent)
1153
1154                       (gnus-agent-append-to-list
1155                        tail-fetched-articles (caar pos)))
1156                     (widen)
1157                     (pop pos))))
1158
1159             (gnus-agent-save-alist group (cdr fetched-articles) date))
1160           (cdr fetched-articles))))))
1161
1162 (defun gnus-agent-crosspost (crosses article &optional date)
1163   (setq date (or date t))
1164
1165   (let (gnus-agent-article-alist group alist beg end)
1166     (save-excursion
1167       (set-buffer gnus-agent-overview-buffer)
1168       (when (nnheader-find-nov-line article)
1169         (forward-word 1)
1170         (setq beg (point))
1171         (setq end (progn (forward-line 1) (point)))))
1172     (while crosses
1173       (setq group (caar crosses))
1174       (unless (setq alist (assoc group gnus-agent-group-alist))
1175         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1176               gnus-agent-group-alist))
1177       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1178       (save-excursion
1179         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1180                                                     group)))
1181         (when (= (point-max) (point-min))
1182           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1183           (ignore-errors
1184             (nnheader-insert-file-contents
1185              (gnus-agent-article-name ".overview" group))))
1186         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1187         (insert (string-to-number (cdar crosses)))
1188         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1189         (gnus-agent-check-overview-buffer))
1190       (pop crosses))))
1191
1192 (defun gnus-agent-backup-overview-buffer ()
1193   (when gnus-newsgroup-name
1194     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1195           (cnt 0)
1196           name)
1197       (while (file-exists-p
1198               (setq name (concat root "~"
1199                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1200       (write-region (point-min) (point-max) name nil 'no-msg)
1201       (gnus-message 1 "Created backup copy of overview in %s." name)))
1202   t)
1203
1204 (defun gnus-agent-check-overview-buffer (&optional buffer)
1205   "Check the overview file given for sanity.
1206 In particular, checks that the file is sorted by article number
1207 and that there are no duplicates."
1208   (let ((prev-num -1)
1209         (backed-up nil))
1210     (save-excursion
1211       (when buffer
1212         (set-buffer buffer))
1213       (save-restriction
1214         (widen)
1215         (goto-char (point-min))
1216
1217         (while (< (point) (point-max))
1218           (let ((p (point))
1219                 (cur (condition-case nil
1220                          (read (current-buffer))
1221                        (error nil))))
1222             (cond
1223              ((or (not (integerp cur))
1224                   (not (eq (char-after) ?\t)))
1225               (or backed-up
1226                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1227               (gnus-message 1
1228                             "Overview buffer contains garbage '%s'."
1229                             (buffer-substring
1230                              p (gnus-point-at-eol))))
1231              ((= cur prev-num)
1232               (or backed-up
1233                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1234               (gnus-message 1
1235                             "Duplicate overview line for %d" cur)
1236               (delete-region (point) (progn (forward-line 1) (point))))
1237              ((< cur prev-num)
1238               (or backed-up
1239                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1240               (gnus-message 1 "Overview buffer not sorted!")
1241               (sort-numeric-fields 1 (point-min) (point-max))
1242               (goto-char (point-min))
1243               (setq prev-num -1))
1244              (t
1245               (setq prev-num cur)))
1246             (forward-line 1)))))))
1247
1248 (defun gnus-agent-flush-cache ()
1249   (save-excursion
1250     (while gnus-agent-buffer-alist
1251       (set-buffer (cdar gnus-agent-buffer-alist))
1252       (write-region-as-coding-system
1253        gnus-agent-file-coding-system
1254        (point-min) (point-max)
1255        (gnus-agent-article-name ".overview"
1256                                 (caar gnus-agent-buffer-alist))
1257        nil 'silent)
1258       (pop gnus-agent-buffer-alist))
1259     (while gnus-agent-group-alist
1260       (with-temp-file (gnus-agent-article-name
1261                        ".agentview" (caar gnus-agent-group-alist))
1262         (princ (cdar gnus-agent-group-alist))
1263         (insert "\n")
1264         (princ 1 (current-buffer))
1265         (insert "\n"))
1266       (pop gnus-agent-group-alist))))
1267
1268 (defun gnus-agent-fetch-headers (group &optional force)
1269   "Fetch interesting headers into the agent.  The group's overview
1270 file will be updated to include the headers while a list of available
1271 article numbers will be returned."
1272   (let* ((fetch-all (and gnus-agent-consider-all-articles
1273                          ;; Do not fetch all headers if the predicate
1274                          ;; implies that we only consider unread articles.
1275                          (not (gnus-predicate-implies-unread
1276                                (or (gnus-group-find-parameter
1277                                     group 'agent-predicate t)
1278                                    (cadr (gnus-group-category group)))))))
1279          (articles (if fetch-all
1280                        (gnus-uncompress-range (gnus-active group))
1281                      (gnus-list-of-unread-articles group)))
1282          (gnus-decode-encoded-word-function 'identity)
1283          (file (gnus-agent-article-name ".overview" group))
1284          gnus-agent-cache)
1285     ;; Check whether the number of articles is not too large.
1286     (when (and (integerp gnus-agent-large-newsgroup)
1287                (> gnus-agent-large-newsgroup 0))
1288       (setq articles (nthcdr (max (- (length articles)
1289                                      gnus-agent-large-newsgroup)
1290                                   0)
1291                              articles)))
1292     (unless fetch-all
1293       ;; Add articles with marks to the list of article headers we want to
1294       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1295       ;; mark, but do fetch recent or seen articles if they have other, more
1296       ;; interesting marks.  (We have to fetch articles with boring marks
1297       ;; because otherwise the agent will remove their marks.)
1298       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1299         (unless (memq (car arts) '(seen recent killed cache))
1300           (setq articles (gnus-range-add articles (cdr arts)))))
1301       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1302
1303     ;; At this point, I have the list of articles to consider for
1304     ;; fetching.  This is the list that I'll return to my caller. Some
1305     ;; of these articles may have already been fetched.  That's OK as
1306     ;; the fetch article code will filter those out.  Internally, I'll
1307     ;; filter this list to just those articles whose headers need to
1308     ;; be fetched.
1309     (let ((articles articles))
1310       ;; Remove known articles.
1311       (when (gnus-agent-load-alist group)
1312         ;; Remove articles marked as downloaded.
1313         (if fetch-all
1314             ;; I want to fetch all headers in the active range.
1315             ;; Therefore, exclude only those headers that are in the
1316             ;; article alist.
1317             ;; NOTE: This is probably NOT what I want to do after
1318             ;; agent expiration in this group.
1319             (setq articles (gnus-agent-uncached-articles articles group))
1320
1321           ;; I want to only fetch those headers that have never been
1322           ;; fetched.  Therefore, exclude all headers that are, or
1323           ;; WERE, in the article alist.
1324           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1325                 (high (cdr (gnus-active group))))
1326             ;; Low can be greater than High when the same group is
1327             ;; fetched twice in the same session {The first fetch will
1328             ;; fill the article alist such that (last
1329             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1330             ;; group))}.  The addition of one(the 1+ above) then
1331             ;; forces Low to be greater than High.  When this happens,
1332             ;; gnus-list-range-intersection returns nil which
1333             ;; indicates that no headers need to be fetched. -- Kevin
1334             (setq articles (gnus-list-range-intersection
1335                             articles (list (cons low high)))))))
1336
1337       (gnus-message
1338        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1339        (gnus-compress-sequence articles t))
1340
1341       (save-excursion
1342         (set-buffer nntp-server-buffer)
1343
1344         (if articles
1345             (progn
1346               (gnus-message 7 "Fetching headers for %s..." group)
1347
1348               ;; Fetch them.
1349               (gnus-make-directory (nnheader-translate-file-chars
1350                                     (file-name-directory file) t))
1351
1352               (unless (eq 'nov (gnus-retrieve-headers articles group))
1353                 (nnvirtual-convert-headers))
1354               (gnus-agent-check-overview-buffer)
1355               ;; Move these headers to the overview buffer so that
1356               ;; gnus-agent-braid-nov can merge them with the contents
1357               ;; of FILE.
1358               (copy-to-buffer
1359                gnus-agent-overview-buffer (point-min) (point-max))
1360               (when (file-exists-p file)
1361                 (gnus-agent-braid-nov group articles file))
1362               (gnus-agent-check-overview-buffer)
1363               (write-region-as-coding-system
1364                gnus-agent-file-coding-system
1365                (point-min) (point-max) file nil 'silent)
1366               (gnus-agent-save-alist group articles nil)
1367               articles)
1368           (ignore-errors
1369             (erase-buffer)
1370             (nnheader-insert-file-contents file))))
1371       )
1372     articles))
1373
1374 (defsubst gnus-agent-copy-nov-line (article)
1375   (let (art b e)
1376     (set-buffer gnus-agent-overview-buffer)
1377     (while (and (not (eobp))
1378                 (< (setq art (read (current-buffer))) article))
1379       (forward-line 1))
1380     (beginning-of-line)
1381     (if (or (eobp)
1382             (not (eq article art)))
1383         (set-buffer nntp-server-buffer)
1384       (setq b (point))
1385       (setq e (progn (forward-line 1) (point)))
1386       (set-buffer nntp-server-buffer)
1387       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1388
1389 (defun gnus-agent-braid-nov (group articles file)
1390   "Merge agent overview data with given file.
1391 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1392 FILE and places the combined headers into `nntp-server-buffer'."
1393   (let (start last)
1394     (set-buffer gnus-agent-overview-buffer)
1395     (goto-char (point-min))
1396     (set-buffer nntp-server-buffer)
1397     (erase-buffer)
1398     (nnheader-insert-file-contents file)
1399     (goto-char (point-max))
1400     (forward-line -1)
1401     (unless (looking-at "[0-9]+\t")
1402       ;; Remove corrupted lines
1403       (gnus-message
1404        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1405       (goto-char (point-min))
1406       (while (not (eobp))
1407         (if (looking-at "[0-9]+\t")
1408             (forward-line 1)
1409           (delete-region (point) (progn (forward-line 1) (point)))))
1410       (forward-line -1))
1411     (unless (or (= (point-min) (point-max))
1412                 (< (setq last (read (current-buffer))) (car articles)))
1413       ;; We do it the hard way.
1414       (when (nnheader-find-nov-line (car articles))
1415         ;; Replacing existing NOV entry
1416         (delete-region (point) (progn (forward-line 1) (point))))
1417       (gnus-agent-copy-nov-line (pop articles))
1418
1419       (ignore-errors
1420         (while articles
1421           (while (let ((art (read (current-buffer))))
1422                    (cond ((< art (car articles))
1423                           (forward-line 1)
1424                           t)
1425                          ((= art (car articles))
1426                           (beginning-of-line)
1427                           (delete-region
1428                            (point) (progn (forward-line 1) (point)))
1429                           nil)
1430                          (t
1431                           (beginning-of-line)
1432                           nil))))
1433             
1434           (gnus-agent-copy-nov-line (pop articles)))))
1435
1436     ;; Copy the rest lines
1437     (set-buffer nntp-server-buffer)
1438     (goto-char (point-max))
1439     (when articles
1440       (when last
1441         (set-buffer gnus-agent-overview-buffer)
1442         (ignore-errors
1443           (while (<= (read (current-buffer)) last)
1444             (forward-line 1)))
1445         (beginning-of-line)
1446         (setq start (point))
1447         (set-buffer nntp-server-buffer))
1448       (insert-buffer-substring gnus-agent-overview-buffer start))))
1449
1450 ;; Keeps the compiler from warning about the free variable in
1451 ;; gnus-agent-read-agentview.
1452 (eval-when-compile
1453   (defvar gnus-agent-read-agentview))
1454
1455 (defun gnus-agent-load-alist (group)
1456   "Load the article-state alist for GROUP."
1457   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1458   (let ((gnus-agent-read-agentview group))
1459     (setq gnus-agent-article-alist
1460           (gnus-cache-file-contents
1461            (gnus-agent-article-name ".agentview" group)
1462            'gnus-agent-file-loading-cache
1463            'gnus-agent-read-agentview))))
1464
1465 ;; Save format may be either 1 or 2.  Two is the new, compressed
1466 ;; format that is still being tested.  Format 1 is uncompressed but
1467 ;; known to be reliable.
1468 (defconst gnus-agent-article-alist-save-format 2)
1469
1470 (defun gnus-agent-read-agentview (file)
1471   "Load FILE and do a `read' there."
1472   (with-temp-buffer
1473     (ignore-errors
1474       (nnheader-insert-file-contents file)
1475       (goto-char (point-min))
1476       (let ((alist (read (current-buffer)))
1477             (version (condition-case nil (read (current-buffer))
1478                        (end-of-file 0)))
1479             changed-version)
1480
1481         (cond
1482          ((= version 0)
1483           (let ((inhibit-quit t)
1484                 entry)
1485             (gnus-agent-open-history)
1486             (set-buffer (gnus-agent-history-buffer))
1487             (goto-char (point-min))
1488             (while (not (eobp))
1489               (if (and (looking-at
1490                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1491                        (string= (match-string 2)
1492                                 gnus-agent-read-agentview)
1493                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1494                   (setcdr entry (string-to-number (match-string 1))))
1495               (forward-line 1))
1496             (gnus-agent-close-history)
1497             (setq changed-version t)))
1498          ((= version 1)
1499           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1500          ((= version 2)
1501           (let (uncomp)
1502             (mapcar
1503              (lambda (comp-list)
1504                (let ((state (car comp-list))
1505                      (sequence (gnus-uncompress-sequence
1506                                 (cdr comp-list))))
1507                  (mapcar (lambda (article-id)
1508                            (setq uncomp (cons (cons article-id state) uncomp)))
1509                          sequence)))
1510              alist)
1511             (setq alist (sort uncomp
1512                               (lambda (first second)
1513                                 (< (car first) (car second))))))))
1514         (when changed-version
1515           (let ((gnus-agent-article-alist alist))
1516             (gnus-agent-save-alist gnus-agent-read-agentview)))
1517         alist))))
1518
1519 (defun gnus-agent-save-alist (group &optional articles state dir)
1520   "Save the article-state alist for GROUP."
1521   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1522          (pathname-coding-system nnmail-pathname-coding-system)
1523          (prev (cons nil gnus-agent-article-alist))
1524          (all prev)
1525          print-level print-length item article)
1526     (while (setq article (pop articles))
1527       (while (and (cdr prev)
1528                   (< (caadr prev) article))
1529         (setq prev (cdr prev)))
1530       (cond
1531        ((not (cdr prev))
1532         (setcdr prev (list (cons article state))))
1533        ((> (caadr prev) article)
1534         (setcdr prev (cons (cons article state) (cdr prev))))
1535        ((= (caadr prev) article)
1536         (setcdr (cadr prev) state)))
1537       (setq prev (cdr prev)))
1538     (setq gnus-agent-article-alist (cdr all))
1539     (if dir
1540         (gnus-make-directory dir)
1541       (gnus-make-directory (gnus-agent-article-name "" group)))
1542     (with-temp-file (if dir
1543                         (expand-file-name ".agentview" dir)
1544                       (gnus-agent-article-name ".agentview" group))
1545       (cond ((eq gnus-agent-article-alist-save-format 1)
1546              (princ gnus-agent-article-alist (current-buffer)))
1547             ((eq gnus-agent-article-alist-save-format 2)
1548              (let ((compressed nil))
1549                (mapcar (lambda (pair)
1550                          (let* ((article-id (car pair))
1551                                 (day-of-download (cdr pair))
1552                                 (comp-list (assq day-of-download compressed)))
1553                            (if comp-list
1554                                (setcdr comp-list
1555                                        (cons article-id (cdr comp-list)))
1556                              (setq compressed
1557                                    (cons (list day-of-download article-id)
1558                                          compressed)))
1559                            nil)) gnus-agent-article-alist)
1560                (mapcar (lambda (comp-list)
1561                          (setcdr comp-list
1562                                  (gnus-compress-sequence
1563                                   (nreverse (cdr comp-list)))))
1564                        compressed)
1565                (princ compressed (current-buffer)))))
1566       (insert "\n")
1567       (princ gnus-agent-article-alist-save-format (current-buffer))
1568       (insert "\n"))))
1569
1570 (defun gnus-agent-article-name (article group)
1571   (expand-file-name article
1572                     (file-name-as-directory
1573                      (expand-file-name (gnus-agent-group-path group)
1574                                        (gnus-agent-directory)))))
1575
1576 (defun gnus-agent-batch-confirmation (msg)
1577   "Show error message and return t."
1578   (gnus-message 1 msg)
1579   t)
1580
1581 ;;;###autoload
1582 (defun gnus-agent-batch-fetch ()
1583   "Start Gnus and fetch session."
1584   (interactive)
1585   (gnus)
1586   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1587     (gnus-agent-fetch-session))
1588   (gnus-group-exit))
1589
1590 (defun gnus-agent-fetch-session ()
1591   "Fetch all articles and headers that are eligible for fetching."
1592   (interactive)
1593   (unless gnus-agent-covered-methods
1594     (error "No servers are covered by the Gnus agent"))
1595   (unless gnus-plugged
1596     (error "Can't fetch articles while Gnus is unplugged"))
1597   (let ((methods gnus-agent-covered-methods)
1598         groups group gnus-command-method)
1599     (save-excursion
1600       (while methods
1601         (condition-case err
1602             (progn
1603               (setq gnus-command-method (car methods))
1604               (when (and (or (gnus-server-opened gnus-command-method)
1605                              (gnus-open-server gnus-command-method))
1606                          (gnus-online gnus-command-method))
1607                 (setq groups (gnus-groups-from-server (car methods)))
1608                 (gnus-agent-with-fetch
1609                   (while (setq group (pop groups))
1610                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1611                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1612           (error
1613            (unless (funcall gnus-agent-confirmation-function
1614                             (format "Error %s.  Continue? " (cdr err)))
1615              (error "Cannot fetch articles into the Gnus agent")))
1616           (quit
1617            (unless (funcall gnus-agent-confirmation-function
1618                             (format "Quit fetching session %s.  Continue? "
1619                                     (cdr err)))
1620              (signal 'quit "Cannot fetch articles into the Gnus agent"))))
1621         (pop methods))
1622       (run-hooks 'gnus-agent-fetch-hook)
1623       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1624
1625 (defun gnus-agent-fetch-group-1 (group method)
1626   "Fetch GROUP."
1627   (let ((gnus-command-method method)
1628         (gnus-newsgroup-name group)
1629         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1630         (gnus-newsgroup-headers gnus-newsgroup-headers)
1631         (gnus-newsgroup-scored gnus-newsgroup-scored)
1632         (gnus-use-cache gnus-use-cache)
1633         (gnus-summary-expunge-below gnus-summary-expunge-below)
1634         (gnus-summary-mark-below gnus-summary-mark-below)
1635         (gnus-orphan-score gnus-orphan-score)
1636         ;; Maybe some other gnus-summary local variables should also
1637         ;; be put here.
1638
1639         gnus-headers
1640         gnus-score
1641         articles arts
1642         category predicate info marks score-param
1643         )
1644     (unless (gnus-check-group group)
1645       (error "Can't open server for %s" group))
1646
1647     ;; Fetch headers.
1648     (when (or gnus-newsgroup-active
1649               (gnus-active group)
1650               (gnus-activate-group group))
1651       (let ((marked-articles gnus-newsgroup-downloadable))
1652         ;; Identify the articles marked for download
1653         (unless gnus-newsgroup-active
1654           ;; The variable gnus-newsgroup-active was selected as I need
1655           ;; a gnus-summary local variable that is NOT bound to any
1656           ;; value (its global value should default to nil).
1657           (dolist (mark gnus-agent-download-marks)
1658             (let ((arts (cdr (assq mark (gnus-info-marks
1659                                          (setq info (gnus-get-info group)))))))
1660               (when arts
1661                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1662                                              marked-articles))
1663                 ))))
1664         (setq marked-articles (sort marked-articles '<))
1665
1666         ;; Fetch any new articles from the server
1667         (setq articles (gnus-agent-fetch-headers group))
1668
1669         ;; Merge new articles with marked
1670         (setq articles (sort (append marked-articles articles) '<))
1671
1672         (when articles
1673           ;; Parse them and see which articles we want to fetch.
1674           (setq gnus-newsgroup-dependencies
1675                 (or gnus-newsgroup-dependencies
1676                     (make-vector (length articles) 0)))
1677           (setq gnus-newsgroup-headers
1678                 (or gnus-newsgroup-headers
1679                     (gnus-get-newsgroup-headers-xover articles nil nil
1680                                                       group)))
1681           ;; `gnus-agent-overview-buffer' may be killed for
1682           ;; timeout reason.  If so, recreate it.
1683           (gnus-agent-create-buffer)
1684
1685           ;; Figure out how to select articles in this group
1686           (setq category (gnus-group-category group))
1687
1688           (setq predicate
1689                 (gnus-get-predicate
1690                  (or (gnus-group-find-parameter group 'agent-predicate t)
1691                      (cadr category))))
1692
1693           ;; If the selection predicate requires scoring, score each header
1694           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1695             (let ((score-param
1696                    (or (gnus-group-get-parameter group 'agent-score t)
1697                        (caddr category))))
1698               ;; Translate score-param into real one
1699               (cond
1700                ((not score-param))
1701                ((eq score-param 'file)
1702                 (setq score-param (gnus-all-score-files group)))
1703                ((stringp (car score-param)))
1704                (t
1705                 (setq score-param (list (list score-param)))))
1706               (when score-param
1707                 (gnus-score-headers score-param))))
1708
1709           (unless (and (eq predicate 'gnus-agent-false)
1710                        (not marked-articles))
1711             (let ((arts (list nil)))
1712               (let ((arts-tail arts)
1713                     (alist (gnus-agent-load-alist group))
1714                     (marked-articles marked-articles)
1715                     (gnus-newsgroup-headers gnus-newsgroup-headers))
1716                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
1717                   (let ((num (mail-header-number gnus-headers)))
1718                     ;; Determine if this article is already in the cache
1719                     (while (and alist
1720                                 (> num (caar alist)))
1721                       (setq alist (cdr alist)))
1722
1723                     (unless (and (eq num (caar alist))
1724                                  (cdar alist))
1725
1726                       ;; Determine if this article was marked for download.
1727                       (while (and marked-articles
1728                                   (> num (car marked-articles)))
1729                         (setq marked-articles
1730                               (cdr marked-articles)))
1731
1732                       ;; When this article is marked, or selected by the
1733                       ;; predicate, add it to the download list
1734                       (when (or (eq num (car marked-articles))
1735                                 (let ((gnus-score
1736                                        (or (cdr
1737                                             (assq num gnus-newsgroup-scored))
1738                                            gnus-summary-default-score)))
1739                                   (funcall predicate)))
1740                         (gnus-agent-append-to-list arts-tail num))))))
1741
1742               (let (fetched-articles)
1743                 ;; Fetch all selected articles
1744                 (setq gnus-newsgroup-undownloaded
1745                       (gnus-sorted-ndifference
1746                        gnus-newsgroup-undownloaded
1747                        (setq fetched-articles
1748                              (if (cdr arts)
1749                                  (gnus-agent-fetch-articles group (cdr arts))
1750                                nil))))
1751
1752                 (let ((unfetched-articles
1753                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
1754                   (if gnus-newsgroup-active
1755                       ;; Update the summary buffer
1756                       (progn
1757                         (dolist (article marked-articles)
1758                           (when (gnus-summary-goto-subject article nil t)
1759                             (gnus-summary-set-agent-mark article t)))
1760                         (dolist (article fetched-articles)
1761                           (if gnus-agent-mark-unread-after-downloaded
1762                               (gnus-summary-mark-article
1763                                article gnus-unread-mark))
1764                           (when (gnus-summary-goto-subject article nil t)
1765                             (gnus-summary-update-download-mark article)))
1766                         (dolist (article unfetched-articles)
1767                           (gnus-summary-mark-article
1768                            article gnus-canceled-mark)))
1769
1770                     ;; Update the group buffer.
1771
1772                     ;; When some, or all, of the marked articles came
1773                     ;; from the download mark.  Remove that mark.  I
1774                     ;; didn't do this earlier as I only want to remove
1775                     ;; the marks after the fetch is completed.
1776
1777                     (dolist (mark gnus-agent-download-marks)
1778                       (when (eq mark 'download)
1779                         (let ((marked-arts
1780                                (assq mark (gnus-info-marks
1781                                            (setq info (gnus-get-info group))))))
1782                           (when (cdr marked-arts)
1783                             (setq marks
1784                                   (delq marked-arts (gnus-info-marks info)))
1785                             (gnus-info-set-marks info marks)))))
1786                     (let ((read (gnus-info-read
1787                                  (or info (setq info (gnus-get-info group))))))
1788                       (gnus-info-set-read
1789                        info (gnus-add-to-range read unfetched-articles)))
1790
1791                     (gnus-group-update-group group t)
1792                     (sit-for 0)
1793
1794                     (gnus-dribble-enter
1795                      (concat "(gnus-group-set-info '"
1796                              (gnus-prin1-to-string info)
1797                              ")"))))))))))))
1798
1799 ;;;
1800 ;;; Agent Category Mode
1801 ;;;
1802
1803 (defvar gnus-category-mode-hook nil
1804   "Hook run in `gnus-category-mode' buffers.")
1805
1806 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1807   "Format of category lines.
1808
1809 Valid specifiers include:
1810 %c  Topic name (string)
1811 %g  The number of groups in the topic (integer)
1812
1813 General format specifiers can also be used.  See Info node
1814 `(gnus)Formatting Variables'.")
1815
1816 (defvar gnus-category-mode-line-format "Gnus: %%b"
1817   "The format specification for the category mode line.")
1818
1819 (defvar gnus-agent-short-article 100
1820   "Articles that have fewer lines than this are short.")
1821
1822 (defvar gnus-agent-long-article 200
1823   "Articles that have more lines than this are long.")
1824
1825 (defvar gnus-agent-low-score 0
1826   "Articles that have a score lower than this have a low score.")
1827
1828 (defvar gnus-agent-high-score 0
1829   "Articles that have a score higher than this have a high score.")
1830
1831
1832 ;;; Internal variables.
1833
1834 (defvar gnus-category-buffer "*Agent Category*")
1835
1836 (defvar gnus-category-line-format-alist
1837   `((?c gnus-tmp-name ?s)
1838     (?g gnus-tmp-groups ?d)))
1839
1840 (defvar gnus-category-mode-line-format-alist
1841   `((?u user-defined ?s)))
1842
1843 (defvar gnus-category-line-format-spec nil)
1844 (defvar gnus-category-mode-line-format-spec nil)
1845
1846 (defvar gnus-category-mode-map nil)
1847 (put 'gnus-category-mode 'mode-class 'special)
1848
1849 (unless gnus-category-mode-map
1850   (setq gnus-category-mode-map (make-sparse-keymap))
1851   (suppress-keymap gnus-category-mode-map)
1852
1853   (gnus-define-keys gnus-category-mode-map
1854     "q" gnus-category-exit
1855     "k" gnus-category-kill
1856     "c" gnus-category-copy
1857     "a" gnus-category-add
1858     "p" gnus-category-edit-predicate
1859     "g" gnus-category-edit-groups
1860     "s" gnus-category-edit-score
1861     "l" gnus-category-list
1862
1863     "\C-c\C-i" gnus-info-find-node
1864     "\C-c\C-b" gnus-bug))
1865
1866 (defvar gnus-category-menu-hook nil
1867   "*Hook run after the creation of the menu.")
1868
1869 (defun gnus-category-make-menu-bar ()
1870   (gnus-turn-off-edit-menu 'category)
1871   (unless (boundp 'gnus-category-menu)
1872     (easy-menu-define
1873      gnus-category-menu gnus-category-mode-map ""
1874      '("Categories"
1875        ["Add" gnus-category-add t]
1876        ["Kill" gnus-category-kill t]
1877        ["Copy" gnus-category-copy t]
1878        ["Edit predicate" gnus-category-edit-predicate t]
1879        ["Edit score" gnus-category-edit-score t]
1880        ["Edit groups" gnus-category-edit-groups t]
1881        ["Exit" gnus-category-exit t]))
1882
1883     (gnus-run-hooks 'gnus-category-menu-hook)))
1884
1885 (defun gnus-category-mode ()
1886   "Major mode for listing and editing agent categories.
1887
1888 All normal editing commands are switched off.
1889 \\<gnus-category-mode-map>
1890 For more in-depth information on this mode, read the manual
1891 \(`\\[gnus-info-find-node]').
1892
1893 The following commands are available:
1894
1895 \\{gnus-category-mode-map}"
1896   (interactive)
1897   (when (gnus-visual-p 'category-menu 'menu)
1898     (gnus-category-make-menu-bar))
1899   (kill-all-local-variables)
1900   (gnus-simplify-mode-line)
1901   (setq major-mode 'gnus-category-mode)
1902   (setq mode-name "Category")
1903   (gnus-set-default-directory)
1904   (setq mode-line-process nil)
1905   (use-local-map gnus-category-mode-map)
1906   (buffer-disable-undo)
1907   (setq truncate-lines t)
1908   (setq buffer-read-only t)
1909   (gnus-run-hooks 'gnus-category-mode-hook))
1910
1911 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1912
1913 (defun gnus-category-insert-line (category)
1914   (let* ((gnus-tmp-name (format "%s" (car category)))
1915          (gnus-tmp-groups (length (cadddr category))))
1916     (beginning-of-line)
1917     (gnus-add-text-properties
1918      (point)
1919      (prog1 (1+ (point))
1920        ;; Insert the text.
1921        (eval gnus-category-line-format-spec))
1922      (list 'gnus-category gnus-tmp-name))))
1923
1924 (defun gnus-enter-category-buffer ()
1925   "Go to the Category buffer."
1926   (interactive)
1927   (gnus-category-setup-buffer)
1928   (gnus-configure-windows 'category)
1929   (gnus-category-prepare))
1930
1931 (defun gnus-category-setup-buffer ()
1932   (unless (get-buffer gnus-category-buffer)
1933     (save-excursion
1934       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1935       (gnus-category-mode))))
1936
1937 (defun gnus-category-prepare ()
1938   (gnus-set-format 'category-mode)
1939   (gnus-set-format 'category t)
1940   (let ((alist gnus-category-alist)
1941         (buffer-read-only nil))
1942     (erase-buffer)
1943     (while alist
1944       (gnus-category-insert-line (pop alist)))
1945     (goto-char (point-min))
1946     (gnus-category-position-point)))
1947
1948 (defun gnus-category-name ()
1949   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
1950       (error "No category on the current line")))
1951
1952 (defun gnus-category-read ()
1953   "Read the category alist."
1954   (setq gnus-category-alist
1955         (or (gnus-agent-read-file
1956              (nnheader-concat gnus-agent-directory "lib/categories"))
1957             (list (list 'default 'short nil nil)))))
1958
1959 (defun gnus-category-write ()
1960   "Write the category alist."
1961   (setq gnus-category-predicate-cache nil
1962         gnus-category-group-cache nil)
1963   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1964   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1965     (prin1 gnus-category-alist (current-buffer))))
1966
1967 (defun gnus-category-edit-predicate (category)
1968   "Edit the predicate for CATEGORY."
1969   (interactive (list (gnus-category-name)))
1970   (let ((info (assq category gnus-category-alist)))
1971     (gnus-edit-form
1972      (cadr info) (format "Editing the predicate for category %s" category)
1973      `(lambda (predicate)
1974         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1975         (gnus-category-write)
1976         (gnus-category-list)))))
1977
1978 (defun gnus-category-edit-score (category)
1979   "Edit the score expression for CATEGORY."
1980   (interactive (list (gnus-category-name)))
1981   (let ((info (assq category gnus-category-alist)))
1982     (gnus-edit-form
1983      (caddr info)
1984      (format "Editing the score expression for category %s" category)
1985      `(lambda (groups)
1986         (setcar (nthcdr 2 (assq ',category gnus-category-alist)) groups)
1987         (gnus-category-write)
1988         (gnus-category-list)))))
1989
1990 (defun gnus-category-edit-groups (category)
1991   "Edit the group list for CATEGORY."
1992   (interactive (list (gnus-category-name)))
1993   (let ((info (assq category gnus-category-alist)))
1994     (gnus-edit-form
1995      (cadddr info) (format "Editing the group list for category %s" category)
1996      `(lambda (groups)
1997         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1998         (gnus-category-write)
1999         (gnus-category-list)))))
2000
2001 (defun gnus-category-kill (category)
2002   "Kill the current category."
2003   (interactive (list (gnus-category-name)))
2004   (let ((info (assq category gnus-category-alist))
2005         (buffer-read-only nil))
2006     (gnus-delete-line)
2007     (setq gnus-category-alist (delq info gnus-category-alist))
2008     (gnus-category-write)))
2009
2010 (defun gnus-category-copy (category to)
2011   "Copy the current category."
2012   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2013   (let ((info (assq category gnus-category-alist)))
2014     (push (list to (gnus-copy-sequence (cadr info))
2015                 (gnus-copy-sequence (caddr info)) nil)
2016           gnus-category-alist)
2017     (gnus-category-write)
2018     (gnus-category-list)))
2019
2020 (defun gnus-category-add (category)
2021   "Create a new category."
2022   (interactive "SCategory name: ")
2023   (when (assq category gnus-category-alist)
2024     (error "Category %s already exists" category))
2025   (push (list category 'false nil nil)
2026         gnus-category-alist)
2027   (gnus-category-write)
2028   (gnus-category-list))
2029
2030 (defun gnus-category-list ()
2031   "List all categories."
2032   (interactive)
2033   (gnus-category-prepare))
2034
2035 (defun gnus-category-exit ()
2036   "Return to the group buffer."
2037   (interactive)
2038   (kill-buffer (current-buffer))
2039   (gnus-configure-windows 'group t))
2040
2041 ;; To avoid having 8-bit characters in the source file.
2042 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2043
2044 (defvar gnus-category-predicate-alist
2045   '((spam . gnus-agent-spam-p)
2046     (short . gnus-agent-short-p)
2047     (long . gnus-agent-long-p)
2048     (low . gnus-agent-low-scored-p)
2049     (high . gnus-agent-high-scored-p)
2050     (read . gnus-agent-read-p)
2051     (true . gnus-agent-true)
2052     (false . gnus-agent-false))
2053   "Mapping from short score predicate symbols to predicate functions.")
2054
2055 (defun gnus-agent-spam-p ()
2056   "Say whether an article is spam or not."
2057   (unless gnus-agent-spam-hashtb
2058     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2059   (if (not (equal (mail-header-references gnus-headers) ""))
2060       nil
2061     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2062       (prog1
2063           (gnus-gethash string gnus-agent-spam-hashtb)
2064         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2065
2066 (defun gnus-agent-short-p ()
2067   "Say whether an article is short or not."
2068   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2069
2070 (defun gnus-agent-long-p ()
2071   "Say whether an article is long or not."
2072   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2073
2074 (defun gnus-agent-low-scored-p ()
2075   "Say whether an article has a low score or not."
2076   (< gnus-score gnus-agent-low-score))
2077
2078 (defun gnus-agent-high-scored-p ()
2079   "Say whether an article has a high score or not."
2080   (> gnus-score gnus-agent-high-score))
2081
2082 (defun gnus-agent-read-p ()
2083   "Say whether an article is read or not."
2084   (gnus-member-of-range (mail-header-number gnus-headers)
2085                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2086
2087 (defun gnus-category-make-function (cat)
2088   "Make a function from category CAT."
2089   (let ((func (gnus-category-make-function-1 cat)))
2090     (if (and (= (length func) 1)
2091              (symbolp (car func)))
2092         (car func)
2093       (gnus-byte-compile `(lambda () ,func)))))
2094
2095 (defun gnus-agent-true ()
2096   "Return t."
2097   t)
2098
2099 (defun gnus-agent-false ()
2100   "Return nil."
2101   nil)
2102
2103 (defun gnus-category-make-function-1 (cat)
2104   "Make a function from category CAT."
2105   (cond
2106    ;; Functions are just returned as is.
2107    ((or (symbolp cat)
2108         (gnus-functionp cat))
2109     `(,(or (cdr (assq cat gnus-category-predicate-alist))
2110            cat)))
2111    ;; More complex category.
2112    ((consp cat)
2113     `(,(cond
2114         ((memq (car cat) '(& and))
2115          'and)
2116         ((memq (car cat) '(| or))
2117          'or)
2118         ((memq (car cat) gnus-category-not)
2119          'not))
2120       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
2121    (t
2122     (error "Unknown category type: %s" cat))))
2123
2124 (defun gnus-get-predicate (predicate)
2125   "Return the predicate for CATEGORY."
2126   (or (cdr (assoc predicate gnus-category-predicate-cache))
2127       (let ((func (gnus-category-make-function predicate)))
2128         (setq gnus-category-predicate-cache
2129               (nconc gnus-category-predicate-cache
2130                      (list (cons predicate func))))
2131         func)))
2132
2133 (defun gnus-predicate-implies-unread (predicate)
2134   "Say whether PREDICATE implies unread articles only.
2135 It is okay to miss some cases, but there must be no false positives.
2136 That is, if this function returns true, then indeed the predicate must
2137 return only unread articles."
2138   ;; Todo: make this work in more cases.
2139   (equal predicate '(not read)))
2140
2141 (defun gnus-group-category (group)
2142   "Return the category GROUP belongs to."
2143   (unless gnus-category-group-cache
2144     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2145     (let ((cs gnus-category-alist)
2146           groups cat)
2147       (while (setq cat (pop cs))
2148         (setq groups (cadddr cat))
2149         (while groups
2150           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2151   (or (gnus-gethash group gnus-category-group-cache)
2152       (assq 'default gnus-category-alist)))
2153
2154 (defun gnus-agent-expire-2 (expiring-group active articles overview day force
2155                                            dir)
2156   (gnus-agent-load-alist expiring-group)
2157   (gnus-message 5 "Expiring articles in %s" expiring-group)
2158   (let* ((info (gnus-get-info expiring-group))
2159          (alist gnus-agent-article-alist)
2160          (specials (if alist
2161                        (list (caar (last alist)))))
2162          (unreads ;; Articles that are excluded from the expiration process
2163           (cond (gnus-agent-expire-all
2164                  ;; All articles are marked read by global decree
2165                  nil)
2166                 ((eq articles t)
2167                  ;; All articles are marked read by function parameter
2168                  nil)
2169                 ((not articles)
2170                  ;; Unread articles are marked protected from
2171                  ;; expiration Don't call gnus-list-of-unread-articles
2172                  ;; as it returns articles that have not been fetched
2173                  ;; into the agent.
2174                  (ignore-errors (gnus-agent-unread-articles expiring-group)))
2175                 (t
2176                  ;; All articles EXCEPT those named by the caller are
2177                  ;; protected from expiration
2178                  (gnus-sorted-difference
2179                   (gnus-uncompress-range
2180                    (cons (caar alist) (caar (last alist))))
2181                   (sort articles '<)))))
2182          (marked ;; More articles that are exluded from the expiration process
2183           (cond (gnus-agent-expire-all
2184                  ;; All articles are unmarked by global decree
2185                  nil)
2186                 ((eq articles t)
2187                  ;; All articles are unmarked by function parameter
2188                  nil)
2189                 (articles
2190                  ;; All articles may as well be unmarked as the
2191                  ;; unreads list already names the articles we are
2192                  ;; going to keep
2193                  nil)
2194                 (t
2195                  ;; Ticked and/or dormant articles are excluded from expiration
2196                  (nconc
2197                   (gnus-uncompress-range
2198                    (cdr (assq 'tick (gnus-info-marks info))))
2199                   (gnus-uncompress-range
2200                    (cdr (assq 'dormant
2201                               (gnus-info-marks info))))))))
2202          (nov-file (concat dir ".overview"))
2203          (cnt 0)
2204          (completed -1)
2205          dlist
2206          type)
2207
2208     ;; The normal article alist contains
2209     ;; elements that look like (article# .
2210     ;; fetch_date) I need to combine other
2211     ;; information with this list.  For
2212     ;; example, a flag indicating that a
2213     ;; particular article MUST BE KEPT.  To
2214     ;; do this, I'm going to transform the
2215     ;; elements to look like (article#
2216     ;; fetch_date keep_flag
2217     ;; NOV_entry_marker) Later, I'll reverse
2218     ;; the process to generate the expired
2219     ;; article alist.
2220
2221     ;; Convert the alist elements to
2222     ;; (article# fetch_date nil nil).
2223     (setq dlist (mapcar (lambda (e) (list (car e) (cdr e) nil nil)) alist))
2224
2225     ;; Convert the keep lists to elements
2226     ;; that look like (article# nil
2227     ;; keep_flag nil) then append it to the
2228     ;; expanded dlist These statements are
2229     ;; sorted by ascending precidence of the
2230     ;; keep_flag.
2231     (setq dlist (nconc dlist (mapcar (lambda (e)
2232                                        (list e nil 'unread  nil)) unreads)))
2233     (setq dlist (nconc dlist (mapcar (lambda (e)
2234                                        (list e nil 'marked  nil)) marked)))
2235     (setq dlist (nconc dlist (mapcar (lambda (e)
2236                                        (list e nil 'special nil)) specials)))
2237
2238     (set-buffer overview)
2239     (erase-buffer)
2240     (when (file-exists-p nov-file)
2241       (gnus-message 7 "gnus-agent-expire: Loading overview...")
2242       (nnheader-insert-file-contents nov-file)
2243       (goto-char (point-min))
2244
2245       (let (p)
2246         (while (< (setq p (point)) (point-max))
2247           (condition-case nil
2248               ;; If I successfully read an
2249               ;; integer (the plus zero
2250               ;; ensures a numeric type),
2251               ;; prepend a marker entry to
2252               ;; the list
2253               (push (list (+ 0 (read (current-buffer))) nil nil
2254                           (set-marker (make-marker) p)) dlist)
2255             (error
2256              (gnus-message 1 (concat "gnus-agent-expire: read error occurred "
2257                                      "when reading expression at %s in %s.  "
2258                                      "Skipping to next line.")
2259                            (point) nov-file)))
2260           ;; Whether I succeeded, or failed,
2261           ;; it doesn't matter.  Move to the
2262           ;; next line then try again.
2263           (forward-line 1)))
2264       (gnus-message 7 "gnus-agent-expire: Loading overview... Done"))
2265     (set-buffer-modified-p nil)
2266
2267     ;; At this point, all of the information
2268     ;; is in dlist.  The only problem is
2269     ;; that much of it is spread across
2270     ;; multiple entries.  Sort then MERGE!!
2271     (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
2272     ;; If two entries have the same
2273     ;; article-number then sort by ascending
2274     ;; keep_flag.
2275     (let ((special 0)
2276           (marked 1)
2277           (unread 2))
2278       (setq dlist
2279             (sort dlist
2280                   (lambda (a b)
2281                     (cond ((< (nth 0 a) (nth 0 b))
2282                            t)
2283                           ((> (nth 0 a) (nth 0 b))
2284                            nil)
2285                           (t
2286                            (let ((a (or (symbol-value (nth 2 a)) 3))
2287                                  (b (or (symbol-value (nth 2 b)) 3)))
2288                              (<= a b))))))))
2289     (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
2290     (gnus-message 7 "gnus-agent-expire: Merging entries... ")
2291     (let ((dlist dlist))
2292       (while (cdr dlist) ; I'm not at the end-of-list
2293         (if (eq (caar dlist) (caadr dlist))
2294             (let ((first (cdr (car dlist)))
2295                   (secnd (cdr (cadr dlist))))
2296               (setcar first (or (car first) (car secnd))) ; fetch_date
2297               (setq first (cdr first)
2298                     secnd (cdr secnd))
2299               (setcar first (or (car first) (car secnd))) ; Keep_flag
2300               (setq first (cdr first)
2301                     secnd (cdr secnd))
2302               (setcar first (or (car first) (car secnd))) ; NOV_entry_marker
2303
2304               (setcdr dlist (cddr dlist)))
2305           (setq dlist (cdr dlist)))))
2306     (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
2307
2308     (let* ((len (float (length dlist)))
2309            (alist (list nil))
2310            (tail-alist alist))
2311       (while dlist
2312         (let ((new-completed (truncate (* 100.0 (/ (setq cnt (1+ cnt)) len)))))
2313           (when (> new-completed completed)
2314             (setq completed new-completed)
2315             (gnus-message 9 "%3d%% completed..."  completed)))
2316         (let* ((entry          (car dlist))
2317                (article-number (nth 0 entry))
2318                (fetch-date     (nth 1 entry))
2319                (keep           (nth 2 entry))
2320                (marker         (nth 3 entry)))
2321
2322           (cond
2323            ;; Kept articles are unread, marked, or special.
2324            (keep
2325             (when fetch-date
2326               (unless (file-exists-p (concat dir (number-to-string
2327                                                   article-number)))
2328                 (setf (nth 1 entry) nil)
2329                 (gnus-message 3 (concat "gnus-agent-expire cleared download "
2330                                         "flag on article %d as the cached "
2331                                         "article file is missing.")
2332                                         (caar dlist)))
2333               (unless marker
2334                 (gnus-message 1 (concat "gnus-agent-expire detected a "
2335                                         "missing NOV entry.  Run "
2336                                         "gnus-agent-regenerate-group to "
2337                                         "restore it."))))
2338             (gnus-agent-append-to-list tail-alist (cons article-number fetch-date)))
2339
2340            ;; The following articles are READ, UNMARKED, and ORDINARY.
2341            ;; See if they can be EXPIRED!!!
2342            ((setq type
2343                   (cond
2344                    ((not (integerp fetch-date))
2345                     'read) ;; never fetched article (may expire right now)
2346                    ((not (file-exists-p (concat dir (number-to-string
2347                                                      article-number))))
2348                     (setf (nth 1 entry) nil)
2349                     'externally-expired) ;; Can't find the cached
2350                                          ;; article.  Handle case as
2351                                          ;; though this article was
2352                                          ;; never fetched.
2353
2354                    ;; We now have the arrival day, so we see
2355                    ;; whether it's old enough to be expired.
2356                    ((< fetch-date day)
2357                     'expired)
2358                    (force
2359                     'forced)))
2360
2361             ;; I found some reason to expire this entry.
2362
2363             (let ((actions nil))
2364               (when (memq type '(forced expired))
2365                 (ignore-errors ; Just being paranoid.
2366                   (delete-file (concat dir (number-to-string article-number)))
2367                   (push "expired cached article" actions))
2368                 (setf (nth 1 entry) nil))
2369
2370               (when marker
2371                 (push "NOV entry removed" actions)
2372                 (goto-char marker)
2373                 (gnus-delete-line))
2374
2375               ;; If considering all articles is set, I can only expire
2376               ;; article IDs that are no longer in the active range.
2377               (if (and gnus-agent-consider-all-articles
2378                        (>= article-number (car active)))
2379                   ;; I have to keep this ID in the alist
2380                   (gnus-agent-append-to-list tail-alist
2381                                              (cons article-number fetch-date))
2382                 (push (format "Removed %s article number from article alist"
2383                               type) actions))
2384
2385               (gnus-message 7 "gnus-agent-expire: Article %d: %s"
2386                             article-number (mapconcat 'identity
2387                                                       actions ", "))))
2388            (t
2389             (gnus-agent-append-to-list tail-alist (cons article-number fetch-date)))
2390            )
2391
2392           ;; Clean up markers as I want to recycle this buffer over
2393           ;; several groups.
2394           (when marker
2395             (set-marker marker nil))
2396
2397           (setq dlist (cdr dlist))))
2398
2399       (setq alist (cdr alist))
2400
2401       (let ((inhibit-quit t))
2402         (unless (equal alist gnus-agent-article-alist)
2403           (setq gnus-agent-article-alist alist)
2404           (gnus-agent-save-alist expiring-group))
2405
2406         (when (buffer-modified-p)
2407           (gnus-make-directory dir)
2408           (write-region-as-coding-system gnus-agent-file-coding-system
2409                                          (point-min) (point-max) nov-file
2410                                          nil 'silent)
2411           ;; clear the modified flag as that I'm not confused by its
2412           ;; status on the next pass through this routine.
2413           (set-buffer-modified-p nil))
2414
2415         (when (eq articles t)
2416           (gnus-summary-update-info))))))
2417
2418 (defun gnus-agent-expire-1 (&optional articles group force)
2419   "Expire all old agent cached articles unconditionally.
2420 See `gnus-agent-expire'."
2421   (let ((methods (if group
2422                      (list (gnus-find-method-for-group group))
2423                    gnus-agent-covered-methods))
2424         (day (if (numberp gnus-agent-expire-days)
2425                  (- (time-to-days (current-time)) gnus-agent-expire-days)
2426                nil))
2427         gnus-command-method sym arts pos
2428         history overview file histories elem art nov-file low info
2429         unreads marked article orig lowest highest found days)
2430     (save-excursion
2431       (setq overview (gnus-get-buffer-create " *expire overview*"))
2432       (unwind-protect
2433           (while (setq gnus-command-method (pop methods))
2434             (when (file-exists-p (gnus-agent-lib-file "active"))
2435               (with-temp-buffer
2436                 (nnheader-insert-file-contents
2437                  (gnus-agent-lib-file "active"))
2438                 (gnus-active-to-gnus-format
2439                  gnus-command-method
2440                  (setq orig (gnus-make-hashtable
2441                              (count-lines (point-min) (point-max))))))
2442               (dolist (expiring-group (gnus-groups-from-server
2443                                        gnus-command-method))
2444                 (if (or (not group)
2445                         (equal group expiring-group))
2446                     (let* ((dir (concat
2447                                  (gnus-agent-directory)
2448                                  (gnus-agent-group-path expiring-group)
2449                                  "/"))
2450                            (active
2451                             (gnus-gethash-safe expiring-group orig))
2452                            (day (if (numberp day)
2453                                     day
2454                                   (let (found
2455                                         (days gnus-agent-expire-days))
2456                                     (catch 'found
2457                                       (while (and (not found) days)
2458                                         (when (eq 0 (string-match
2459                                                      (caar days)
2460                                                      expiring-group))
2461                                           (throw 'found (- (time-to-days
2462                                                             (current-time))
2463                                                            (cadar days))))
2464                                         (pop days))
2465                                       ;; No regexp matched so set
2466                                       ;; a limit that will block
2467                                       ;; expiration in this group.
2468                                       0)))))
2469
2470                       (when active
2471                         (gnus-agent-expire-2 expiring-group active
2472                                              articles overview day force
2473                                              dir)))))))
2474         (kill-buffer overview)))))
2475
2476 (defun gnus-agent-expire (&optional articles group force)
2477   "Expire all old agent cached articles.
2478 If you want to force expiring of certain articles, this function can
2479 take ARTICLES, GROUP and FORCE parameters as well.
2480
2481 The articles on which the expiration process runs are selected as follows:
2482   if ARTICLES is null, all read and unmarked articles.
2483   if ARTICLES is t, all articles.
2484   if ARTICLES is a list, just those articles.
2485 Setting GROUP will limit expiration to that group.
2486 FORCE is equivalent to setting gnus-agent-expire-days to zero(0)."
2487   (interactive)
2488   (if (or (not (eq articles t))
2489           (yes-or-no-p (concat "Are you sure that you want to expire all "
2490                                "articles in " (if group group
2491                                                 "every agentized group")
2492                                ".")))
2493       (gnus-agent-expire-1 articles group force))
2494   (gnus-message 4 "Expiry...done"))
2495
2496 ;;;###autoload
2497 (defun gnus-agent-batch ()
2498   "Start Gnus, send queue and fetch session."
2499   (interactive)
2500   (let ((init-file-user "")
2501         (gnus-always-read-dribble-file t))
2502     (gnus))
2503   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2504     (gnus-group-send-queue)
2505     (gnus-agent-fetch-session)))
2506
2507 (defun gnus-agent-unread-articles (group)
2508   (let* ((read (gnus-info-read (gnus-get-info group)))
2509          (known (gnus-agent-load-alist group))
2510          (unread (list nil))
2511          (tail-unread unread))
2512     (while (and known read)
2513       (let ((candidate (car (pop known))))
2514         (while (let* ((range (car read))
2515                       (min   (if (numberp range) range (car range)))
2516                       (max   (if (numberp range) range (cdr range))))
2517                  (cond ((or (not min)
2518                             (< candidate min))
2519                         (gnus-agent-append-to-list tail-unread candidate)
2520                         nil)
2521                        ((> candidate max)
2522                         (pop read)))))))
2523     (while known
2524       (gnus-agent-append-to-list tail-unread (car (pop known))))
2525     (cdr unread)))
2526
2527 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
2528   "Restrict ARTICLES to numbers already fetched.
2529 Returns a sublist of ARTICLES that excludes thos article ids in GROUP
2530 that have already been fetched.
2531 If CACHED-HEADER is nil, articles are only excluded if the article itself
2532 has been fetched."
2533
2534   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
2535   ;; 'car gnus-agent-article-alist))
2536
2537   ;; Functionally, I don't need to construct a temp list using mapcar.
2538
2539   (if (gnus-agent-load-alist group)
2540     (let* ((ref gnus-agent-article-alist)
2541            (arts articles)
2542            (uncached (list nil))
2543            (tail-uncached uncached))
2544       (while (and ref arts)
2545         (let ((v1 (car arts))
2546               (v2 (caar ref)))
2547           (cond ((< v1 v2) ; the article (v1) does not appear in the reference list
2548                  (gnus-agent-append-to-list tail-uncached v1)
2549                  (pop arts))
2550                 ((= v1 v2)
2551                  (unless (or cached-header (cdar ref)) ; the article (v1) is already cached
2552                    (gnus-agent-append-to-list tail-uncached v1))
2553                  (pop arts)
2554                  (pop ref))
2555                 (t ; the reference article (v2) preceeds the list being filtered
2556                  (pop ref)))))
2557       (while arts
2558         (gnus-agent-append-to-list tail-uncached (pop arts)))
2559       (cdr uncached))
2560     ;; if gnus-agent-load-alist fails, no articles are cached.
2561     articles))
2562
2563 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
2564   (save-excursion
2565     (gnus-agent-create-buffer)
2566     (let ((gnus-decode-encoded-word-function 'identity)
2567           (file (gnus-agent-article-name ".overview" group))
2568           cached-articles uncached-articles)
2569       (gnus-make-directory (nnheader-translate-file-chars
2570                             (file-name-directory file) t))
2571
2572       ;; Populate temp buffer with known headers
2573       (when (file-exists-p file)
2574         (with-current-buffer gnus-agent-overview-buffer
2575           (erase-buffer)
2576           (let ((nnheader-file-coding-system
2577                  gnus-agent-file-coding-system))
2578             (nnheader-insert-nov-file file (car articles)))))
2579
2580       (if (setq uncached-articles (gnus-agent-uncached-articles articles group t))
2581           (progn
2582             ;; Populate nntp-server-buffer with uncached headers
2583             (set-buffer nntp-server-buffer)
2584             (erase-buffer)
2585             (let (gnus-agent-cache)     ; Turn off agent cache
2586               (cond ((not (eq 'nov (gnus-retrieve-headers
2587                                     uncached-articles group fetch-old)))
2588                      (nnvirtual-convert-headers))
2589                     ((eq 'nntp (car gnus-current-select-method))
2590                      ;; The author of gnus-get-newsgroup-headers-xover
2591                      ;; reports that the XOVER command is commonly
2592                      ;; unreliable. The problem is that recently
2593                      ;; posted articles may not be entered into the
2594                      ;; NOV database in time to respond to my XOVER
2595                      ;; query.
2596                      ;;
2597                      ;; I'm going to use his assumption that the NOV
2598                      ;; database is updated in order of ascending
2599                      ;; article ID.  Therefore, a response containing
2600                      ;; article ID N implies that all articles from 1
2601                      ;; to N-1 are up-to-date.  Therefore, missing
2602                      ;; articles in that range have expired.
2603                      
2604                      (set-buffer nntp-server-buffer)
2605                      (let* ((fetched-articles (list nil))
2606                             (tail-fetched-articles fetched-articles)
2607                             (min (cond ((numberp fetch-old)
2608                                         (max 1 (- (car articles) fetch-old)))
2609                                        (fetch-old
2610                                         1)
2611                                        (t
2612                                         (car articles))))
2613                             (max (car (last articles))))
2614                        
2615                        ;; Get the list of articles that were fetched
2616                        (goto-char (point-min))
2617                        (let ((pm (point-max)))
2618                          (while (< (point) pm)
2619                            (when (looking-at "[0-9]+\t")
2620                              (gnus-agent-append-to-list tail-fetched-articles (read (current-buffer))))
2621                            (forward-line 1)))
2622                        
2623                        ;; Clip this list to the headers that will
2624                        ;; actually be returned
2625                        (setq fetched-articles (gnus-list-range-intersection
2626                                                (cdr fetched-articles)
2627                                                (cons min max)))
2628
2629                        ;; Clip the uncached articles list to exclude
2630                        ;; IDs after the last FETCHED header.  The
2631                        ;; excluded IDs may be fetchable using HEAD.
2632                        (if (car tail-fetched-articles)
2633                            (setq uncached-articles (gnus-list-range-intersection 
2634                                                     uncached-articles 
2635                                                     (cons (car uncached-articles) (car tail-fetched-articles)))))
2636
2637                        ;; Create the list of articles that were
2638                        ;; "successfully" fetched.  Success, in this
2639                        ;; case, means that the ID should not be
2640                        ;; fetched again.  In the case of an expired
2641                        ;; article, the header will not be fetched.
2642                        (setq uncached-articles (gnus-sorted-nunion fetched-articles uncached-articles))
2643                        ))))
2644
2645             ;; Erase the temp buffer
2646             (set-buffer gnus-agent-overview-buffer)
2647             (erase-buffer)
2648
2649             ;; Copy the nntp-server-buffer to the temp buffer
2650             (set-buffer nntp-server-buffer)
2651             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
2652
2653             ;; Merge the temp buffer with the known headers (found on
2654             ;; disk in FILE) into the nntp-server-buffer
2655             (when (and uncached-articles (file-exists-p file))
2656               (gnus-agent-braid-nov group uncached-articles file))
2657
2658             ;; Save the new set of known headers to FILE
2659             (set-buffer nntp-server-buffer)
2660             (gnus-agent-check-overview-buffer)
2661             (write-region-as-coding-system
2662              gnus-agent-file-coding-system
2663              (point-min) (point-max) file nil 'silent)
2664             
2665             ;; Update the group's article alist to include the newly
2666             ;; fetched articles.
2667             (gnus-agent-load-alist group)
2668             (gnus-agent-save-alist group uncached-articles nil)
2669             )
2670         
2671         ;; Copy the temp buffer to the nntp-server-buffer
2672         (set-buffer nntp-server-buffer)
2673         (erase-buffer)
2674         (insert-buffer-substring gnus-agent-overview-buffer)))
2675
2676     (if (and fetch-old
2677              (not (numberp fetch-old)))
2678         t                               ; Don't remove anything.
2679       (nnheader-nov-delete-outside-range
2680        (if fetch-old (max 1 (- (car articles) fetch-old))
2681          (car articles))
2682        (car (last articles)))
2683       t)
2684
2685     'nov))
2686
2687 (defun gnus-agent-request-article (article group)
2688   "Retrieve ARTICLE in GROUP from the agent cache."
2689   (let* ((gnus-command-method (gnus-find-method-for-group group))
2690          (file (concat
2691                   (gnus-agent-directory)
2692                   (gnus-agent-group-path group) "/"
2693                   (number-to-string article)))
2694          (buffer-read-only nil))
2695     (when (and (file-exists-p file)
2696                (> (nth 7 (file-attributes file)) 0))
2697       (erase-buffer)
2698       (gnus-kill-all-overlays)
2699       (insert-file-contents-as-coding-system gnus-cache-coding-system file)
2700       t)))
2701
2702 (defun gnus-agent-regenerate-group (group &optional reread)
2703   "Regenerate GROUP.
2704 If REREAD is t, all articles in the .overview are marked as unread.
2705 If REREAD is not nil, downloaded articles are marked as unread."
2706   (interactive (list (let ((def (or (gnus-group-group-name)
2707                                     gnus-newsgroup-name)))
2708                        (let ((select (read-string (if def (concat "Group Name (" def "): ")
2709                                           "Group Name: "))))
2710                          (if (and (equal "" select)
2711                                   def)
2712                              def
2713                            select)))
2714                      (intern-soft (read-string "Reread (nil)? (t=>all, nil=>none, some=>all downloaded): "))))
2715   (gnus-message 5 "Regenerating in %s" group)
2716   (let* ((gnus-command-method (or gnus-command-method
2717                                   (gnus-find-method-for-group group)))
2718          (file (gnus-agent-article-name ".overview" group))
2719          (dir (file-name-directory file))
2720          point
2721          (downloaded (if (file-exists-p dir)
2722                          (sort (mapcar (lambda (name) (string-to-int name))
2723                                        (directory-files dir nil "^[0-9]+$" t))
2724                                '>)
2725                        (progn (gnus-make-directory dir) nil)))
2726          dl nov-arts
2727          alist header
2728          regenerated)
2729
2730     (mm-with-unibyte-buffer
2731      (if (file-exists-p file)
2732          (let ((nnheader-file-coding-system
2733                 gnus-agent-file-coding-system))
2734            (nnheader-insert-file-contents file)))
2735      (set-buffer-modified-p nil)
2736
2737      ;; Load the article IDs found in the overview file.  As a
2738      ;; side-effect, validate the file contents.
2739      (let ((load t))
2740        (while load
2741          (setq load nil)
2742          (goto-char (point-min))
2743          (while (< (point) (point-max))
2744            (cond ((and (looking-at "[0-9]+\t")
2745                        (<= (- (match-end 0) (match-beginning 0)) 9))
2746                   (push (read (current-buffer)) nov-arts)
2747                   (forward-line 1)
2748                   (let ((l1 (car nov-arts))
2749                         (l2 (cadr nov-arts)))
2750                     (cond ((not l2)
2751                            nil)
2752                           ((< l1 l2)
2753                            (gnus-message 3 "gnus-agent-regenerate-group: NOV entries are NOT in ascending order.")
2754                            ;; Don't sort now as I haven't verified
2755                            ;; that every line begins with a number
2756                            (setq load t))
2757                           ((= l1 l2)
2758                            (forward-line -1)
2759                            (gnus-message 4 "gnus-agent-regenerate-group: NOV entries contained duplicate of article %s.  Duplicate deleted." l1)
2760                            (gnus-delete-line)
2761                            (pop nov-arts)))))
2762                  (t
2763                   (gnus-message 1 "gnus-agent-regenerate-group: NOV entries contained line that did not begin with an article number.  Deleted line.")
2764                   (gnus-delete-line))))
2765          (if load
2766              (progn
2767                (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV entries into ascending order.")
2768                (sort-numeric-fields 1 (point-min) (point-max))
2769                     (setq nov-arts nil)))))
2770      (gnus-agent-check-overview-buffer)
2771
2772      ;; Construct a new article alist whose nodes match every header
2773      ;; in the .overview file.  As a side-effect, missing headers are
2774      ;; reconstructed from the downloaded article file.
2775      (while (or downloaded nov-arts)
2776        (cond ((and downloaded 
2777                    (or (not nov-arts)
2778                        (> (car downloaded) (car nov-arts))))
2779               ;; This entry is missing from the overview file
2780               (gnus-message 3 "Regenerating NOV %s %d..." group (car downloaded))
2781               (let ((file (concat dir (number-to-string (car downloaded)))))
2782                 (mm-with-unibyte-buffer
2783                  (nnheader-insert-file-contents file)
2784                  (nnheader-remove-body)
2785                  (setq header (nnheader-parse-naked-head)))
2786                 (mail-header-set-number header (car downloaded))
2787                 (if nov-arts
2788                     (let ((key (concat "^" (int-to-string (car nov-arts)) "\t")))
2789                       (or (re-search-backward key nil t)
2790                           (re-search-forward key))
2791                       (forward-line 1))
2792                   (goto-char (point-min)))
2793                 (nnheader-insert-nov header))
2794               (setq nov-arts (cons (car downloaded) nov-arts)))
2795              ((eq (car downloaded) (car nov-arts))
2796               ;; This entry in the overview has been downloaded
2797               (push (cons (car downloaded) (time-to-days (nth 5 (file-attributes (concat dir (number-to-string (car downloaded))))))) alist)
2798               (pop downloaded)
2799               (pop nov-arts))
2800              (t
2801               ;; This entry in the overview has not been downloaded
2802               (push (cons (car nov-arts) nil) alist)
2803               (pop nov-arts))))
2804
2805      ;; When gnus-agent-consider-all-articles is set,
2806      ;; gnus-agent-regenerate-group should NOT remove article IDs from
2807      ;; the alist.  Those IDs serve as markers to indicate that an
2808      ;; attempt has been made to fetch that article's header.
2809
2810      ;; When gnus-agent-consider-all-articles is NOT set,
2811      ;; gnus-agent-regenerate-group can remove the article ID of every
2812      ;; article (with the exception of the last ID in the list - it's
2813      ;; special) that no longer appears in the overview.  In this
2814      ;; situtation, the last article ID in the list implies that it,
2815      ;; and every article ID preceeding it, have been fetched from the
2816      ;; server.
2817      (if gnus-agent-consider-all-articles
2818          ;; Restore all article IDs that were not found in the overview file.
2819          (let* ((n (cons nil alist))
2820                 (merged n)
2821                 (o (gnus-agent-load-alist group)))
2822            (while o
2823              (let ((nID (caadr n))
2824                    (oID (caar o)))
2825                (cond ((not nID)
2826                       (setq n (setcdr n (list (list oID))))
2827                       (pop o))
2828                      ((< oID nID)
2829                       (setcdr n (cons (list oID) (cdr n)))
2830                       (pop o))
2831                      ((= oID nID)
2832                       (pop o)
2833                       (pop n))
2834                      (t
2835                       (pop n)))))
2836            (setq alist (cdr merged)))
2837        ;; Restore the last article ID if it is not already in the new alist
2838        (let ((n (last alist))
2839              (o (last (gnus-agent-load-alist group))))
2840          (cond ((not o)
2841                 nil)
2842                ((not n)
2843                 (push (cons (caar o) nil) alist))
2844                ((< (caar n) (caar o))
2845                 (setcdr n (list (car o)))))))
2846                      
2847      (let ((inhibit-quit t))
2848      (if (setq regenerated (buffer-modified-p))
2849          (write-region-as-coding-system
2850           gnus-agent-file-coding-system
2851           (point-min) (point-max) file nil 'silent))
2852
2853     (setq regenerated (or regenerated
2854                           (and reread gnus-agent-article-alist)
2855                           (not (equal alist gnus-agent-article-alist)))
2856           )
2857
2858     (setq gnus-agent-article-alist alist)
2859  
2860     (when regenerated
2861          (gnus-agent-save-alist group)))
2862      )
2863
2864     (when (and reread gnus-agent-article-alist)
2865       (gnus-make-ascending-articles-unread
2866        group
2867        (delq nil (mapcar (function (lambda (c)
2868                                      (cond ((eq reread t)
2869                                             (car c))
2870                                            ((cdr c)
2871                                             (car c)))))
2872                          gnus-agent-article-alist)))
2873
2874       (when (gnus-buffer-live-p gnus-group-buffer)
2875         (gnus-group-update-group group t)
2876         (sit-for 0))
2877       )
2878
2879     regenerated))
2880
2881 ;;;###autoload
2882 (defun gnus-agent-regenerate (&optional clean reread)
2883   "Regenerate all agent covered files.
2884 If CLEAN, don't read existing active files."
2885   (interactive "P")
2886   (let (regenerated)
2887     (gnus-message 4 "Regenerating Gnus agent files...")
2888     (dolist (gnus-command-method gnus-agent-covered-methods)
2889       (let ((active-file (gnus-agent-lib-file "active"))
2890             active-hashtb active-changed
2891             point)
2892         (gnus-make-directory (file-name-directory active-file))
2893         (if clean
2894             (setq active-hashtb (gnus-make-hashtable 1000))
2895           (mm-with-unibyte-buffer
2896            (if (file-exists-p active-file)
2897                (let ((nnheader-file-coding-system
2898                       gnus-agent-file-coding-system))
2899                  (nnheader-insert-file-contents active-file))
2900              (setq active-changed t))
2901            (gnus-active-to-gnus-format
2902             nil (setq active-hashtb
2903                       (gnus-make-hashtable
2904                        (count-lines (point-min) (point-max)))))))
2905         (dolist (group (gnus-groups-from-server gnus-command-method))
2906           (setq regenerated (or (gnus-agent-regenerate-group group reread)
2907                                 regenerated))
2908           (let ((min (or (caar gnus-agent-article-alist) 1))
2909                 (max (or (caar (last gnus-agent-article-alist)) 0))
2910                 (active (gnus-gethash-safe (gnus-group-real-name group)
2911                                            active-hashtb))
2912                 (read (gnus-info-read (gnus-get-info group))))
2913             (if (not active)
2914                 (progn
2915                   (setq active (cons min max)
2916                         active-changed t)
2917                   (gnus-sethash group active active-hashtb))
2918               (when (> (car active) min)
2919                 (setcar active min)
2920                 (setq active-changed t))
2921               (when (< (cdr active) max)
2922                 (setcdr active max)
2923                 (setq active-changed t)))))
2924         (when active-changed
2925           (setq regenerated t)
2926           (gnus-message 4 "Regenerate %s" active-file)
2927           (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
2928             (gnus-write-active-file active-file active-hashtb)))))
2929     (gnus-message 4 "Regenerating Gnus agent files...done")
2930     regenerated))
2931
2932 (defun gnus-agent-go-online (&optional force)
2933   "Switch servers into online status."
2934   (interactive (list t))
2935   (dolist (server gnus-opened-servers)
2936     (when (eq (nth 1 server) 'offline)
2937       (if (if (eq force 'ask)
2938               (gnus-y-or-n-p
2939                (format "Switch %s:%s into online status? "
2940                        (caar server) (cadar server)))
2941             force)
2942           (setcar (nthcdr 1 server) 'close)))))
2943
2944 (defun gnus-agent-toggle-group-plugged (group)
2945   "Toggle the status of the server of the current group."
2946   (interactive (list (gnus-group-group-name)))
2947   (let* ((method (gnus-find-method-for-group group))
2948          (status (cadr (assoc method gnus-opened-servers))))
2949     (if (eq status 'offline)
2950         (gnus-server-set-status method 'closed)
2951       (gnus-close-server method)
2952       (gnus-server-set-status method 'offline))
2953     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
2954              (if (eq status 'offline) 'offline 'online)
2955              (if (eq status 'offline) 'online 'offline))))
2956
2957 (defun gnus-agent-group-covered-p (group)
2958   (member (gnus-group-method group)
2959           gnus-agent-covered-methods))
2960
2961 (provide 'gnus-agent)
2962
2963 ;;; gnus-agent.el ends here