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