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