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