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