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