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