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