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