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