Import Gnus v5.10.2.
[elisp/gnus.git-] / 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 The normal usage of this command is to put the following as the
588 last form in your `.gnus.el' file:
589
590 \(gnus-agentize)
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                 (sit-for 1))))
831           (gnus-agent-read-file
832            (nnheader-concat gnus-agent-directory "lib/servers"))))
833
834 (defun gnus-agent-write-servers ()
835   "Write the alist of covered servers."
836   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
837   (let ((coding-system-for-write nnheader-file-coding-system)
838         (file-name-coding-system nnmail-pathname-coding-system))
839     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
840       (prin1 (mapcar 'gnus-method-simplify gnus-agent-covered-methods)
841              (current-buffer)))))
842
843 ;;;
844 ;;; Summary commands
845 ;;;
846
847 (defun gnus-agent-mark-article (n &optional unmark)
848   "Mark the next N articles as downloadable.
849 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
850 the mark instead.  The difference between N and the actual number of
851 articles marked is returned."
852   (interactive "p")
853   (let ((backward (< n 0))
854         (n (abs n)))
855     (while (and
856             (> n 0)
857             (progn
858               (gnus-summary-set-agent-mark
859                (gnus-summary-article-number) unmark)
860               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
861       (setq n (1- n)))
862     (when (/= 0 n)
863       (gnus-message 7 "No more articles"))
864     (gnus-summary-recenter)
865     (gnus-summary-position-point)
866     n))
867
868 (defun gnus-agent-unmark-article (n)
869   "Remove the downloadable mark from the next N articles.
870 If N is negative, unmark backward instead.  The difference between N and
871 the actual number of articles unmarked is returned."
872   (interactive "p")
873   (gnus-agent-mark-article n t))
874
875 (defun gnus-agent-toggle-mark (n)
876   "Toggle the downloadable mark from the next N articles.
877 If N is negative, toggle backward instead.  The difference between N and
878 the actual number of articles toggled is returned."
879   (interactive "p")
880   (gnus-agent-mark-article n 'toggle))
881
882 (defun gnus-summary-set-agent-mark (article &optional unmark)
883   "Mark ARTICLE as downloadable.  If UNMARK is nil, article is marked.
884 When UNMARK is t, the article is unmarked.  For any other value, the
885 article's mark is toggled."
886   (let ((unmark (cond ((eq nil unmark)
887                        nil)
888                       ((eq t unmark)
889                        t)
890                       (t
891                        (memq article gnus-newsgroup-downloadable)))))
892     (when (gnus-summary-goto-subject article nil t)
893       (gnus-summary-update-mark
894        (if unmark
895            (progn
896              (setq gnus-newsgroup-downloadable
897                    (delq article gnus-newsgroup-downloadable))
898              (gnus-article-mark article))
899          (progn
900            (setq gnus-newsgroup-downloadable
901                  (gnus-add-to-sorted-list gnus-newsgroup-downloadable article))
902            gnus-downloadable-mark)
903          )
904        'unread))))
905
906 (defun gnus-agent-get-undownloaded-list ()
907   "Construct list of articles that have not been downloaded."
908   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
909     (when (set (make-local-variable 'gnus-newsgroup-agentized)
910                (gnus-agent-method-p gnus-command-method))
911       (let* ((alist (gnus-agent-load-alist gnus-newsgroup-name))
912              (headers (sort (mapcar (lambda (h)
913                                       (mail-header-number h))
914                                     gnus-newsgroup-headers) '<))
915              (cached (and gnus-use-cache gnus-newsgroup-cached))
916              (undownloaded (list nil))
917              (tail-undownloaded undownloaded)
918              (unfetched (list nil))
919              (tail-unfetched unfetched))
920         (while (and alist headers)
921           (let ((a (caar alist))
922                 (h (car headers)))
923             (cond ((< a h)
924                    ;; Ignore IDs in the alist that are not being
925                    ;; displayed in the summary.
926                    (setq alist (cdr alist)))
927                   ((> a h)
928                    ;; Headers that are not in the alist should be
929                    ;; fictious (see nnagent-retrieve-headers); they
930                    ;; imply that this article isn't in the agent.
931                    (gnus-agent-append-to-list tail-undownloaded h)
932                    (gnus-agent-append-to-list tail-unfetched    h)
933                    (setq headers (cdr headers))) 
934                   ((cdar alist)
935                    (setq alist (cdr alist))
936                    (setq headers (cdr headers))
937                    nil                  ; ignore already downloaded
938                    )
939                   (t
940                    (setq alist (cdr alist))
941                    (setq headers (cdr headers))
942                    
943                    ;; This article isn't in the agent.  Check to see
944                    ;; if it is in the cache.  If it is, it's been
945                    ;; downloaded.
946                    (while (and cached (< (car cached) a))
947                      (setq cached (cdr cached)))
948                    (unless (equal a (car cached))
949                      (gnus-agent-append-to-list tail-undownloaded a))))))
950
951         (while headers
952           (let ((num (pop headers)))
953             (gnus-agent-append-to-list tail-undownloaded num)
954             (gnus-agent-append-to-list tail-unfetched    num)))
955
956         (setq gnus-newsgroup-undownloaded (cdr undownloaded)
957               gnus-newsgroup-unfetched    (cdr unfetched))))))
958
959 (defun gnus-agent-catchup ()
960   "Mark as read all unhandled articles.
961 An article is unhandled if it is neither cached, nor downloaded, nor
962 downloadable."
963   (interactive)
964   (save-excursion
965     (let ((articles gnus-newsgroup-undownloaded))
966       (when (or gnus-newsgroup-downloadable
967                 gnus-newsgroup-cached)
968         (setq articles (gnus-sorted-ndifference
969                         (gnus-sorted-ndifference
970                          (gnus-copy-sequence articles)
971                          gnus-newsgroup-downloadable)
972                         gnus-newsgroup-cached)))
973
974       (while articles
975         (gnus-summary-mark-article
976          (pop articles) gnus-catchup-mark)))
977     (gnus-summary-position-point)))
978
979 (defun gnus-agent-summary-fetch-series ()
980   (interactive)
981   (when gnus-newsgroup-processable
982     (setq gnus-newsgroup-downloadable
983           (let* ((dl gnus-newsgroup-downloadable)
984                  (gnus-newsgroup-downloadable
985                   (sort (gnus-copy-sequence gnus-newsgroup-processable) '<))
986                  (fetched-articles (gnus-agent-summary-fetch-group)))
987             ;; The preceeding call to (gnus-agent-summary-fetch-group)
988             ;; updated gnus-newsgroup-downloadable to remove each
989             ;; article successfully fetched.
990
991             ;; For each article that I processed, remove its
992             ;; processable mark IF the article is no longer
993             ;; downloadable (i.e. it's already downloaded)
994             (dolist (article gnus-newsgroup-processable)
995               (unless (memq article gnus-newsgroup-downloadable)
996                 (gnus-summary-remove-process-mark article)))
997             (gnus-sorted-ndifference dl fetched-articles)))))
998
999 (defun gnus-agent-summary-fetch-group (&optional all)
1000   "Fetch the downloadable articles in the group.
1001 Optional arg ALL, if non-nil, means to fetch all articles."
1002   (interactive "P")
1003   (let ((articles
1004          (if all gnus-newsgroup-articles
1005            gnus-newsgroup-downloadable))
1006         (gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name))
1007         fetched-articles)
1008     (gnus-agent-while-plugged
1009       (unless articles
1010         (error "No articles to download"))
1011       (gnus-agent-with-fetch
1012         (setq gnus-newsgroup-undownloaded
1013               (gnus-sorted-ndifference
1014                gnus-newsgroup-undownloaded
1015                (setq fetched-articles
1016                      (gnus-agent-fetch-articles
1017                       gnus-newsgroup-name articles)))))
1018       (save-excursion
1019         (dolist (article articles)
1020           (let ((was-marked-downloadable 
1021                  (memq article gnus-newsgroup-downloadable)))
1022             (cond (gnus-agent-mark-unread-after-downloaded
1023                    (setq gnus-newsgroup-downloadable
1024                          (delq article gnus-newsgroup-downloadable))
1025
1026                    ;; The downloadable mark is implemented as a
1027                    ;; type of read mark.  Therefore, marking the
1028                    ;; article as unread is sufficient to clear
1029                    ;; its downloadable flag.  
1030                    (gnus-summary-mark-article article gnus-unread-mark))
1031                   (was-marked-downloadable
1032                    (gnus-summary-set-agent-mark article t)))
1033             (when (gnus-summary-goto-subject article nil t)
1034               (gnus-summary-update-download-mark article))))))
1035     fetched-articles))
1036
1037 (defun gnus-agent-fetch-selected-article ()
1038   "Fetch the current article as it is selected.
1039 This can be added to `gnus-select-article-hook' or
1040 `gnus-mark-article-hook'."
1041   (let ((gnus-command-method gnus-current-select-method))
1042     (when (and gnus-plugged (gnus-agent-method-p gnus-command-method))
1043       (when (gnus-agent-fetch-articles
1044              gnus-newsgroup-name
1045              (list gnus-current-article))
1046         (setq gnus-newsgroup-undownloaded
1047               (delq gnus-current-article gnus-newsgroup-undownloaded))
1048         (gnus-summary-update-download-mark gnus-current-article)))))
1049
1050 ;;;
1051 ;;; Internal functions
1052 ;;;
1053
1054 ;;; NOTES:
1055 ;;; The agent's active range is defined as follows:
1056 ;;;  If the agent has no record of the group, use the actual active
1057 ;;;    range.
1058 ;;;  If the agent has a record, set the agent's active range to
1059 ;;;    include the max limit of the actual active range.
1060 ;;;  When expiring, update the min limit to match the smallest of the
1061 ;;;    min article not expired or the min actual active range.
1062
1063 (defun gnus-agent-save-active (method)
1064   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
1065
1066 (defun gnus-agent-save-active-1 (method function)
1067   (when (gnus-agent-method-p method)
1068     (let* ((gnus-command-method method)
1069            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
1070            (file (gnus-agent-lib-file "active")))
1071       (funcall function nil new)
1072       (gnus-agent-write-active file new)
1073       (erase-buffer)
1074       (nnheader-insert-file-contents file))))
1075
1076 (defun gnus-agent-write-active (file new &optional literal-replacement)
1077   (let ((old new))
1078     (when (and (not literal-replacement)
1079                (file-exists-p file))
1080       (setq old (gnus-make-hashtable (count-lines (point-min) (point-max))))
1081       (with-temp-buffer
1082         (nnheader-insert-file-contents file)
1083         (gnus-active-to-gnus-format nil old))
1084       ;; Iterate over the current active groups, the current active
1085       ;; range may expand, but NOT CONTRACT, the agent's active range.
1086       (mapatoms
1087        (lambda (nsym)
1088          (let ((new-active (and nsym (boundp nsym) (symbol-value nsym))))
1089            (when new-active
1090              (let* ((osym       (intern (symbol-name nsym) old))
1091                     (old-active (and (boundp osym) (symbol-value osym))))
1092                (if old-active
1093                    (let ((new-min (car new-active))
1094                          (old-min (car old-active))
1095                          (new-max (cdr new-active))
1096                          (old-max (cdr old-active)))
1097                      (if (and (integerp new-min)
1098                               (< new-min old-min))
1099                          (setcar old-active new-min))
1100                      (if (and (integerp new-max)
1101                               (> new-max old-max))
1102                          (setcdr old-active new-max)))
1103                  (set osym new-active))))))
1104        new))
1105     (gnus-make-directory (file-name-directory file))
1106     (let ((nnmail-active-file-coding-system gnus-agent-file-coding-system))
1107       ;; The hashtable contains real names of groups.  However, do NOT
1108       ;; add the foreign server prefix as gnus-active-to-gnus-format
1109       ;; will add it while reading the file.
1110       (gnus-write-active-file file old nil))))
1111
1112 (defun gnus-agent-save-groups (method)
1113   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
1114
1115 (defun gnus-agent-save-group-info (method group active)
1116   (when (gnus-agent-method-p method)
1117     (let* ((gnus-command-method method)
1118            (coding-system-for-write nnheader-file-coding-system)
1119            (file-name-coding-system nnmail-pathname-coding-system)
1120            (file (gnus-agent-lib-file "active"))
1121            oactive-min oactive-max)
1122       (gnus-make-directory (file-name-directory file))
1123       (with-temp-file file
1124         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
1125         (mm-disable-multibyte)
1126         (when (file-exists-p file)
1127           (nnheader-insert-file-contents file)
1128
1129           (goto-char (point-min))
1130           (when (re-search-forward
1131                  (concat "^" (regexp-quote group) " ") nil t)
1132             (save-excursion
1133               (setq oactive-max (read (current-buffer)) ;; max
1134                     oactive-min (read (current-buffer)))) ;; min
1135             (gnus-delete-line)))
1136         (insert (format "%S %d %d y\n" (intern group)
1137                         (max (or oactive-max (cdr active)) (cdr active))
1138                         (min (or oactive-min (car active)) (car active))))
1139         (goto-char (point-max))
1140         (while (search-backward "\\." nil t)
1141           (delete-char 1))))))
1142
1143 (defun gnus-agent-group-path (group)
1144   "Translate GROUP into a file name."
1145
1146   ;; NOTE: This is what nnmail-group-pathname does as of Apr 2003.
1147   ;; The two methods must be kept synchronized, which is why
1148   ;; gnus-agent-group-pathname was added.
1149
1150   (setq group
1151         (nnheader-translate-file-chars
1152          (nnheader-replace-duplicate-chars-in-string
1153           (nnheader-replace-chars-in-string 
1154            (gnus-group-real-name group)
1155            ?/ ?_)
1156           ?. ?_)))
1157   (if (or nnmail-use-long-file-names
1158           (file-directory-p (expand-file-name group (gnus-agent-directory))))
1159       group
1160     (mm-encode-coding-string
1161      (nnheader-replace-chars-in-string group ?. ?/)
1162      nnmail-pathname-coding-system)))
1163
1164 (defun gnus-agent-group-pathname (group)
1165   "Translate GROUP into a file name."
1166   ;; nnagent uses nnmail-group-pathname to read articles while
1167   ;; unplugged.  The agent must, therefore, use the same directory
1168   ;; while plugged.
1169   (let ((gnus-command-method (or gnus-command-method
1170                                  (gnus-find-method-for-group group))))
1171     (nnmail-group-pathname (gnus-group-real-name group) (gnus-agent-directory))))
1172
1173 (defun gnus-agent-get-function (method)
1174   (if (gnus-online method)
1175       (car method)
1176     (require 'nnagent)
1177     'nnagent))
1178
1179 ;;; History functions
1180
1181 (defun gnus-agent-history-buffer ()
1182   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
1183
1184 (defun gnus-agent-open-history ()
1185   (save-excursion
1186     (push (cons (gnus-agent-method)
1187                 (set-buffer (gnus-get-buffer-create
1188                              (format " *Gnus agent %s history*"
1189                                      (gnus-agent-method)))))
1190           gnus-agent-history-buffers)
1191     (mm-disable-multibyte) ;; everything is binary
1192     (erase-buffer)
1193     (insert "\n")
1194     (let ((file (gnus-agent-lib-file "history")))
1195       (when (file-exists-p file)
1196         (nnheader-insert-file-contents file))
1197       (set (make-local-variable 'gnus-agent-file-name) file))))
1198
1199 (defun gnus-agent-close-history ()
1200   (when (gnus-buffer-live-p gnus-agent-current-history)
1201     (kill-buffer gnus-agent-current-history)
1202     (setq gnus-agent-history-buffers
1203           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
1204                 gnus-agent-history-buffers))))
1205
1206 ;;;
1207 ;;; Fetching
1208 ;;;
1209
1210 (defun gnus-agent-fetch-articles (group articles)
1211   "Fetch ARTICLES from GROUP and put them into the Agent."
1212   (when articles
1213     (gnus-agent-load-alist group)
1214     (let* ((alist   gnus-agent-article-alist)
1215            (headers (if (< (length articles) 2) nil gnus-newsgroup-headers))
1216            (selected-sets (list nil))
1217            (current-set-size 0)
1218            article
1219            header-number)
1220       ;; Check each article
1221       (while (setq article (pop articles))
1222         ;; Skip alist entries preceeding this article
1223         (while (> article (or (caar alist) (1+ article)))
1224           (setq alist (cdr alist)))
1225
1226         ;; Prune off articles that we have already fetched.
1227         (unless (and (eq article (caar alist))
1228                      (cdar alist))
1229           ;; Skip headers preceeding this article
1230           (while (> article 
1231                     (setq header-number
1232                           (let* ((header (car headers)))
1233                             (if header
1234                                 (mail-header-number header)
1235                               (1+ article)))))
1236             (setq headers (cdr headers)))
1237
1238           ;; Add this article to the current set
1239           (setcar selected-sets (cons article (car selected-sets)))
1240
1241           ;; Update the set size, when the set is too large start a
1242           ;; new one.  I do this after adding the article as I want at
1243           ;; least one article in each set.
1244           (when (< gnus-agent-max-fetch-size
1245                    (setq current-set-size
1246                          (+ current-set-size
1247                             (if (= header-number article)
1248                                 (let ((char-size (mail-header-chars
1249                                                   (car headers))))
1250                                   (if (<= char-size 0)
1251                                       ;; The char size was missing/invalid,
1252                                       ;; assume a worst-case situation of
1253                                       ;; 65 char/line.  If the line count
1254                                       ;; is missing, arbitrarily assume a
1255                                       ;; size of 1000 characters.
1256                                     (max (* 65 (mail-header-lines
1257                                                 (car headers)))
1258                                          1000)
1259                                     char-size))
1260                               0))))
1261             (setcar selected-sets (nreverse (car selected-sets)))
1262             (setq selected-sets (cons nil selected-sets)
1263                   current-set-size 0))))
1264
1265       (when (or (cdr selected-sets) (car selected-sets))
1266         (let* ((fetched-articles (list nil))
1267                (tail-fetched-articles fetched-articles)
1268                (dir (gnus-agent-group-pathname group))
1269                (date (time-to-days (current-time)))
1270                (case-fold-search t)
1271                pos crosses id)
1272
1273           (setcar selected-sets (nreverse (car selected-sets)))
1274           (setq selected-sets (nreverse selected-sets))
1275
1276           (gnus-make-directory dir)
1277           (gnus-message 7 "Fetching articles for %s..." group)
1278
1279           (unwind-protect
1280               (while (setq articles (pop selected-sets))
1281                 ;; Fetch the articles from the backend.
1282                 (if (gnus-check-backend-function 'retrieve-articles group)
1283                     (setq pos (gnus-retrieve-articles articles group))
1284                   (with-temp-buffer
1285                     (let (article)
1286                       (while (setq article (pop articles))
1287                         (gnus-message 10 "Fetching article %s for %s..."
1288                                       article group)
1289                         (when (or
1290                                (gnus-backlog-request-article group article
1291                                                              nntp-server-buffer)
1292                                (gnus-request-article article group))
1293                           (goto-char (point-max))
1294                           (push (cons article (point)) pos)
1295                           (insert-buffer-substring nntp-server-buffer)))
1296                       (copy-to-buffer
1297                        nntp-server-buffer (point-min) (point-max))
1298                       (setq pos (nreverse pos)))))
1299                 ;; Then save these articles into the Agent.
1300                 (save-excursion
1301                   (set-buffer nntp-server-buffer)
1302                   (while pos
1303                     (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
1304                     (goto-char (point-min))
1305                     (unless (eobp) ;; Don't save empty articles.
1306                       (when (search-forward "\n\n" nil t)
1307                         (when (search-backward "\nXrefs: " nil t)
1308                           ;; Handle cross posting.
1309                           (goto-char (match-end 0)) ; move to end of header name
1310                           (skip-chars-forward "^ ") ; skip server name
1311                           (skip-chars-forward " ")
1312                           (setq crosses nil)
1313                           (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) *")
1314                             (push (cons (buffer-substring (match-beginning 1)
1315                                                           (match-end 1))
1316                                         (string-to-int
1317                                          (buffer-substring (match-beginning 2)
1318                                                            (match-end 2))))
1319                                   crosses)
1320                             (goto-char (match-end 0)))
1321                           (gnus-agent-crosspost crosses (caar pos) date)))
1322                       (goto-char (point-min))
1323                       (if (not (re-search-forward
1324                                 "^Message-ID: *<\\([^>\n]+\\)>" nil t))
1325                           (setq id "No-Message-ID-in-article")
1326                         (setq id (buffer-substring
1327                                   (match-beginning 1) (match-end 1))))
1328                       (let ((coding-system-for-write
1329                              gnus-agent-file-coding-system))
1330                         (write-region (point-min) (point-max)
1331                                       (concat dir (number-to-string (caar pos)))
1332                                       nil 'silent))
1333
1334                       (gnus-agent-append-to-list
1335                        tail-fetched-articles (caar pos)))
1336                     (widen)
1337                     (setq pos (cdr pos)))))
1338
1339             (gnus-agent-save-alist group (cdr fetched-articles) date)
1340             (gnus-message 7 ""))
1341           (cdr fetched-articles))))))
1342
1343 (defun gnus-agent-crosspost (crosses article &optional date)
1344   (setq date (or date t))
1345
1346   (let (gnus-agent-article-alist group alist beg end)
1347     (save-excursion
1348       (set-buffer gnus-agent-overview-buffer)
1349       (when (nnheader-find-nov-line article)
1350         (forward-word 1)
1351         (setq beg (point))
1352         (setq end (progn (forward-line 1) (point)))))
1353     (while crosses
1354       (setq group (caar crosses))
1355       (unless (setq alist (assoc group gnus-agent-group-alist))
1356         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
1357               gnus-agent-group-alist))
1358       (setcdr alist (cons (cons (cdar crosses) date) (cdr alist)))
1359       (save-excursion
1360         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
1361                                                     group)))
1362         (when (= (point-max) (point-min))
1363           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
1364           (ignore-errors
1365             (nnheader-insert-file-contents
1366              (gnus-agent-article-name ".overview" group))))
1367         (nnheader-find-nov-line (string-to-number (cdar crosses)))
1368         (insert (string-to-number (cdar crosses)))
1369         (insert-buffer-substring gnus-agent-overview-buffer beg end)
1370         (gnus-agent-check-overview-buffer))
1371       (setq crosses (cdr crosses)))))
1372
1373 (defun gnus-agent-backup-overview-buffer ()
1374   (when gnus-newsgroup-name
1375     (let ((root (gnus-agent-article-name ".overview" gnus-newsgroup-name))
1376           (cnt 0)
1377           name)
1378       (while (file-exists-p
1379               (setq name (concat root "~"
1380                                  (int-to-string (setq cnt (1+ cnt))) "~"))))
1381       (write-region (point-min) (point-max) name nil 'no-msg)
1382       (gnus-message 1 "Created backup copy of overview in %s." name)))
1383   t)
1384
1385 (defun gnus-agent-check-overview-buffer (&optional buffer)
1386   "Check the overview file given for sanity.
1387 In particular, checks that the file is sorted by article number
1388 and that there are no duplicates."
1389   (let ((prev-num -1)
1390         (backed-up nil))
1391     (save-excursion
1392       (when buffer
1393         (set-buffer buffer))
1394       (save-restriction
1395         (widen)
1396         (goto-char (point-min))
1397
1398         (while (< (point) (point-max))
1399           (let ((p (point))
1400                 (cur (condition-case nil
1401                          (read (current-buffer))
1402                        (error nil))))
1403             (cond
1404              ((or (not (integerp cur))
1405                   (not (eq (char-after) ?\t)))
1406               (or backed-up
1407                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1408               (gnus-message 1
1409                             "Overview buffer contains garbage '%s'."
1410                             (buffer-substring
1411                              p (gnus-point-at-eol))))
1412              ((= cur prev-num)
1413               (or backed-up
1414                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1415               (gnus-message 1
1416                             "Duplicate overview line for %d" cur)
1417               (delete-region (point) (progn (forward-line 1) (point))))
1418              ((< cur prev-num)
1419               (or backed-up
1420                   (setq backed-up (gnus-agent-backup-overview-buffer)))
1421               (gnus-message 1 "Overview buffer not sorted!")
1422               (sort-numeric-fields 1 (point-min) (point-max))
1423               (goto-char (point-min))
1424               (setq prev-num -1))
1425              (t
1426               (setq prev-num cur)))
1427             (forward-line 1)))))))
1428
1429 (defun gnus-agent-flush-cache ()
1430   (save-excursion
1431     (while gnus-agent-buffer-alist
1432       (set-buffer (cdar gnus-agent-buffer-alist))
1433       (let ((coding-system-for-write
1434              gnus-agent-file-coding-system))
1435         (write-region (point-min) (point-max)
1436                       (gnus-agent-article-name ".overview"
1437                                                (caar gnus-agent-buffer-alist))
1438                       nil 'silent))
1439       (setq gnus-agent-buffer-alist (cdr gnus-agent-buffer-alist)))
1440     (while gnus-agent-group-alist
1441       (with-temp-file (gnus-agent-article-name
1442                        ".agentview" (caar gnus-agent-group-alist))
1443         (princ (cdar gnus-agent-group-alist))
1444         (insert "\n")
1445         (princ 1 (current-buffer))
1446         (insert "\n"))
1447       (setq gnus-agent-group-alist (cdr gnus-agent-group-alist)))))
1448
1449 (defun gnus-agent-find-parameter (group symbol)
1450   "Search for GROUPs SYMBOL in the group's parameters, the group's
1451 topic parameters, the group's category, or the customizable
1452 variables.  Returns the first non-nil value found."
1453   (or (gnus-group-find-parameter group symbol t)
1454       (gnus-group-parameter-value (cdr (gnus-group-category group)) symbol t)
1455       (symbol-value
1456        (cdr
1457         (assq symbol
1458               '((agent-short-article . gnus-agent-short-article)
1459                 (agent-long-article . gnus-agent-long-article)
1460                 (agent-low-score . gnus-agent-low-score)
1461                 (agent-high-score . gnus-agent-high-score)
1462                 (agent-days-until-old . gnus-agent-expire-days)
1463                 (agent-enable-expiration
1464                  . gnus-agent-enable-expiration)
1465                 (agent-predicate . gnus-agent-predicate)))))))
1466
1467 (defun gnus-agent-fetch-headers (group &optional force)
1468   "Fetch interesting headers into the agent.  The group's overview
1469 file will be updated to include the headers while a list of available
1470 article numbers will be returned."
1471   (let* ((fetch-all (and gnus-agent-consider-all-articles
1472                          ;; Do not fetch all headers if the predicate
1473                          ;; implies that we only consider unread articles.
1474                          (not (gnus-predicate-implies-unread
1475                                (gnus-agent-find-parameter group
1476                                                           'agent-predicate)))))
1477          (articles (if fetch-all
1478                        (gnus-uncompress-range (gnus-active group))
1479                      (gnus-list-of-unread-articles group)))
1480          (gnus-decode-encoded-word-function 'identity)
1481          (file (gnus-agent-article-name ".overview" group)))
1482
1483     (unless fetch-all
1484       ;; Add articles with marks to the list of article headers we want to
1485       ;; fetch.  Don't fetch articles solely on the basis of a recent or seen
1486       ;; mark, but do fetch recent or seen articles if they have other, more
1487       ;; interesting marks.  (We have to fetch articles with boring marks
1488       ;; because otherwise the agent will remove their marks.)
1489       (dolist (arts (gnus-info-marks (gnus-get-info group)))
1490         (unless (memq (car arts) '(seen recent killed cache))
1491           (setq articles (gnus-range-add articles (cdr arts)))))
1492       (setq articles (sort (gnus-uncompress-sequence articles) '<)))
1493
1494     ;; At this point, I have the list of articles to consider for
1495     ;; fetching.  This is the list that I'll return to my caller. Some
1496     ;; of these articles may have already been fetched.  That's OK as
1497     ;; the fetch article code will filter those out.  Internally, I'll
1498     ;; filter this list to just those articles whose headers need to
1499     ;; be fetched.
1500     (let ((articles articles))
1501       ;; Remove known articles.
1502       (when (and (or gnus-agent-cache
1503                      (not gnus-plugged))
1504                  (gnus-agent-load-alist group))
1505         ;; Remove articles marked as downloaded.
1506         (if fetch-all
1507             ;; I want to fetch all headers in the active range.
1508             ;; Therefore, exclude only those headers that are in the
1509             ;; article alist.
1510             ;; NOTE: This is probably NOT what I want to do after
1511             ;; agent expiration in this group.
1512             (setq articles (gnus-agent-uncached-articles articles group))
1513
1514           ;; I want to only fetch those headers that have never been
1515           ;; fetched.  Therefore, exclude all headers that are, or
1516           ;; WERE, in the article alist.
1517           (let ((low (1+ (caar (last gnus-agent-article-alist))))
1518                 (high (cdr (gnus-active group))))
1519             ;; Low can be greater than High when the same group is
1520             ;; fetched twice in the same session {The first fetch will
1521             ;; fill the article alist such that (last
1522             ;; gnus-agent-article-alist) equals (cdr (gnus-active
1523             ;; group))}.  The addition of one(the 1+ above) then
1524             ;; forces Low to be greater than High.  When this happens,
1525             ;; gnus-list-range-intersection returns nil which
1526             ;; indicates that no headers need to be fetched. -- Kevin
1527             (setq articles (gnus-list-range-intersection
1528                             articles (list (cons low high)))))))
1529
1530       (gnus-message
1531        10 "gnus-agent-fetch-headers: undownloaded articles are '%s'"
1532        (gnus-compress-sequence articles t))
1533
1534       (save-excursion
1535         (set-buffer nntp-server-buffer)
1536
1537         (if articles
1538             (progn
1539               (gnus-message 7 "Fetching headers for %s..." group)
1540
1541               ;; Fetch them.
1542               (gnus-make-directory (nnheader-translate-file-chars
1543                                     (file-name-directory file) t))
1544
1545               (unless (eq 'nov (gnus-retrieve-headers articles group))
1546                 (nnvirtual-convert-headers))
1547               (gnus-agent-check-overview-buffer)
1548               ;; Move these headers to the overview buffer so that
1549               ;; gnus-agent-braid-nov can merge them with the contents
1550               ;; of FILE.
1551               (copy-to-buffer
1552                gnus-agent-overview-buffer (point-min) (point-max))
1553               (when (file-exists-p file)
1554                 (gnus-agent-braid-nov group articles file))
1555               (let ((coding-system-for-write
1556                      gnus-agent-file-coding-system))
1557                 (gnus-agent-check-overview-buffer)
1558                 (write-region (point-min) (point-max) file nil 'silent))
1559               (gnus-agent-save-alist group articles nil)
1560               articles)
1561           (ignore-errors
1562             (erase-buffer)
1563             (nnheader-insert-file-contents file)))))
1564     articles))
1565
1566 (defsubst gnus-agent-copy-nov-line (article)
1567   (let (art b e)
1568     (set-buffer gnus-agent-overview-buffer)
1569     (while (and (not (eobp))
1570                 (< (setq art (read (current-buffer))) article))
1571       (forward-line 1))
1572     (beginning-of-line)
1573     (if (or (eobp)
1574             (not (eq article art)))
1575         (set-buffer nntp-server-buffer)
1576       (setq b (point))
1577       (setq e (progn (forward-line 1) (point)))
1578       (set-buffer nntp-server-buffer)
1579       (insert-buffer-substring gnus-agent-overview-buffer b e))))
1580
1581 (defun gnus-agent-braid-nov (group articles file)
1582   "Merge agent overview data with given file.
1583 Takes headers for ARTICLES from `gnus-agent-overview-buffer' and the given
1584 FILE and places the combined headers into `nntp-server-buffer'."
1585   (let (start last)
1586     (set-buffer gnus-agent-overview-buffer)
1587     (goto-char (point-min))
1588     (set-buffer nntp-server-buffer)
1589     (erase-buffer)
1590     (nnheader-insert-file-contents file)
1591     (goto-char (point-max))
1592     (forward-line -1)
1593     (unless (looking-at "[0-9]+\t")
1594       ;; Remove corrupted lines
1595       (gnus-message
1596        1 "Overview %s is corrupted. Removing corrupted lines..." file)
1597       (goto-char (point-min))
1598       (while (not (eobp))
1599         (if (looking-at "[0-9]+\t")
1600             (forward-line 1)
1601           (delete-region (point) (progn (forward-line 1) (point)))))
1602       (forward-line -1))
1603     (unless (or (= (point-min) (point-max))
1604                 (< (setq last (read (current-buffer))) (car articles)))
1605       ;; We do it the hard way.
1606       (when (nnheader-find-nov-line (car articles))
1607         ;; Replacing existing NOV entry
1608         (delete-region (point) (progn (forward-line 1) (point))))
1609       (gnus-agent-copy-nov-line (pop articles))
1610
1611       (ignore-errors
1612         (while articles
1613           (while (let ((art (read (current-buffer))))
1614                    (cond ((< art (car articles))
1615                           (forward-line 1)
1616                           t)
1617                          ((= art (car articles))
1618                           (beginning-of-line)
1619                           (delete-region
1620                            (point) (progn (forward-line 1) (point)))
1621                           nil)
1622                          (t
1623                           (beginning-of-line)
1624                           nil))))
1625
1626           (gnus-agent-copy-nov-line (pop articles)))))
1627
1628     ;; Copy the rest lines
1629     (set-buffer nntp-server-buffer)
1630     (goto-char (point-max))
1631     (when articles
1632       (when last
1633         (set-buffer gnus-agent-overview-buffer)
1634         (ignore-errors
1635           (while (<= (read (current-buffer)) last)
1636             (forward-line 1)))
1637         (beginning-of-line)
1638         (setq start (point))
1639         (set-buffer nntp-server-buffer))
1640       (insert-buffer-substring gnus-agent-overview-buffer start))))
1641
1642 ;; Keeps the compiler from warning about the free variable in
1643 ;; gnus-agent-read-agentview.
1644 (eval-when-compile
1645   (defvar gnus-agent-read-agentview))
1646
1647 (defun gnus-agent-load-alist (group)
1648   "Load the article-state alist for GROUP."
1649   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
1650   (let ((gnus-agent-read-agentview group))
1651     (setq gnus-agent-article-alist
1652           (gnus-cache-file-contents
1653            (gnus-agent-article-name ".agentview" group)
1654            'gnus-agent-file-loading-cache
1655            'gnus-agent-read-agentview))))
1656
1657 ;; Save format may be either 1 or 2.  Two is the new, compressed
1658 ;; format that is still being tested.  Format 1 is uncompressed but
1659 ;; known to be reliable.
1660 (defconst gnus-agent-article-alist-save-format 2)
1661
1662 (defun gnus-agent-read-agentview (file)
1663   "Load FILE and do a `read' there."
1664   (with-temp-buffer
1665     (ignore-errors
1666       (nnheader-insert-file-contents file)
1667       (goto-char (point-min))
1668       (let ((alist (read (current-buffer)))
1669             (version (condition-case nil (read (current-buffer))
1670                        (end-of-file 0)))
1671             changed-version)
1672
1673         (cond
1674          ((= version 0)
1675           (let ((inhibit-quit t)
1676                 entry)
1677             (gnus-agent-open-history)
1678             (set-buffer (gnus-agent-history-buffer))
1679             (goto-char (point-min))
1680             (while (not (eobp))
1681               (if (and (looking-at
1682                         "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
1683                        (string= (match-string 2)
1684                                 gnus-agent-read-agentview)
1685                        (setq entry (assoc (string-to-number (match-string 3)) alist)))
1686                   (setcdr entry (string-to-number (match-string 1))))
1687               (forward-line 1))
1688             (gnus-agent-close-history)
1689             (setq changed-version t)))
1690          ((= version 1)
1691           (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
1692          ((= version 2)
1693           (let (uncomp)
1694             (mapcar
1695              (lambda (comp-list)
1696                (let ((state (car comp-list))
1697                      (sequence (gnus-uncompress-sequence
1698                                 (cdr comp-list))))
1699                  (mapcar (lambda (article-id)
1700                            (setq uncomp (cons (cons article-id state) uncomp)))
1701                          sequence)))
1702              alist)
1703             (setq alist (sort uncomp
1704                               (lambda (first second)
1705                                 (< (car first) (car second))))))))
1706         (when changed-version
1707           (let ((gnus-agent-article-alist alist))
1708             (gnus-agent-save-alist gnus-agent-read-agentview)))
1709         alist))))
1710
1711 (defun gnus-agent-save-alist (group &optional articles state dir)
1712   "Save the article-state alist for GROUP."
1713   (let* ((file-name-coding-system nnmail-pathname-coding-system)
1714          (prev (cons nil gnus-agent-article-alist))
1715          (all prev)
1716          print-level print-length item article)
1717     (while (setq article (pop articles))
1718       (while (and (cdr prev)
1719                   (< (caadr prev) article))
1720         (setq prev (cdr prev)))
1721       (cond
1722        ((not (cdr prev))
1723         (setcdr prev (list (cons article state))))
1724        ((> (caadr prev) article)
1725         (setcdr prev (cons (cons article state) (cdr prev))))
1726        ((= (caadr prev) article)
1727         (setcdr (cadr prev) state)))
1728       (setq prev (cdr prev)))
1729     (setq gnus-agent-article-alist (cdr all))
1730     (if dir
1731         (gnus-make-directory dir)
1732       (gnus-make-directory (gnus-agent-article-name "" group)))
1733     (with-temp-file (if dir
1734                         (expand-file-name ".agentview" dir)
1735                       (gnus-agent-article-name ".agentview" group))
1736       (cond ((eq gnus-agent-article-alist-save-format 1)
1737              (princ gnus-agent-article-alist (current-buffer)))
1738             ((eq gnus-agent-article-alist-save-format 2)
1739              (let ((compressed nil))
1740                (mapcar (lambda (pair)
1741                          (let* ((article-id (car pair))
1742                                 (day-of-download (cdr pair))
1743                                 (comp-list (assq day-of-download compressed)))
1744                            (if comp-list
1745                                (setcdr comp-list
1746                                        (cons article-id (cdr comp-list)))
1747                              (setq compressed
1748                                    (cons (list day-of-download article-id)
1749                                          compressed)))
1750                            nil)) gnus-agent-article-alist)
1751                (mapcar (lambda (comp-list)
1752                          (setcdr comp-list
1753                                  (gnus-compress-sequence
1754                                   (nreverse (cdr comp-list)))))
1755                        compressed)
1756                (princ compressed (current-buffer)))))
1757       (insert "\n")
1758       (princ gnus-agent-article-alist-save-format (current-buffer))
1759       (insert "\n"))))
1760
1761 (defun gnus-agent-article-name (article group)
1762   (expand-file-name article
1763                     (file-name-as-directory
1764                      (gnus-agent-group-pathname group))))
1765
1766 (defun gnus-agent-batch-confirmation (msg)
1767   "Show error message and return t."
1768   (gnus-message 1 msg)
1769   t)
1770
1771 ;;;###autoload
1772 (defun gnus-agent-batch-fetch ()
1773   "Start Gnus and fetch session."
1774   (interactive)
1775   (gnus)
1776   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1777     (gnus-agent-fetch-session))
1778   (gnus-group-exit))
1779
1780 (defun gnus-agent-fetch-session ()
1781   "Fetch all articles and headers that are eligible for fetching."
1782   (interactive)
1783   (unless gnus-agent-covered-methods
1784     (error "No servers are covered by the Gnus agent"))
1785   (unless gnus-plugged
1786     (error "Can't fetch articles while Gnus is unplugged"))
1787   (let ((methods gnus-agent-covered-methods)
1788         groups group gnus-command-method)
1789     (save-excursion
1790       (while methods
1791         (setq gnus-command-method (car methods))
1792         (when (and (or (gnus-server-opened gnus-command-method)
1793                        (gnus-open-server gnus-command-method))
1794                    (gnus-online gnus-command-method))
1795           (setq groups (gnus-groups-from-server (car methods)))
1796           (gnus-agent-with-fetch
1797             (while (setq group (pop groups))
1798               (when (<= (gnus-group-level group)
1799                         gnus-agent-handle-level)
1800                 (if (or debug-on-error debug-on-quit)
1801                     (gnus-agent-fetch-group-1
1802                      group gnus-command-method)
1803                   (condition-case err
1804                       (gnus-agent-fetch-group-1
1805                        group gnus-command-method)
1806                     (error
1807                      (unless (funcall gnus-agent-confirmation-function
1808                                       (format "Error %s.  Continue? "
1809                                               (error-message-string err)))
1810                        (error "Cannot fetch articles into the Gnus agent")))
1811                     (quit
1812                      (unless (funcall gnus-agent-confirmation-function
1813                                       (format
1814                                        "Quit fetching session %s.  Continue? "
1815                                        (error-message-string err)))
1816                        (signal 'quit
1817                                "Cannot fetch articles into the Gnus agent")))))))))
1818         (setq methods (cdr methods)))
1819       (gnus-run-hooks 'gnus-agent-fetched-hook)
1820       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1821
1822 (defun gnus-agent-fetch-group-1 (group method)
1823   "Fetch GROUP."
1824   (let ((gnus-command-method method)
1825         (gnus-newsgroup-name group)
1826         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
1827         (gnus-newsgroup-headers gnus-newsgroup-headers)
1828         (gnus-newsgroup-scored gnus-newsgroup-scored)
1829         (gnus-use-cache gnus-use-cache)
1830         (gnus-summary-expunge-below gnus-summary-expunge-below)
1831         (gnus-summary-mark-below gnus-summary-mark-below)
1832         (gnus-orphan-score gnus-orphan-score)
1833         ;; Maybe some other gnus-summary local variables should also
1834         ;; be put here.
1835
1836         gnus-headers
1837         gnus-score
1838         articles arts
1839         category predicate info marks score-param
1840         )
1841     (unless (gnus-check-group group)
1842       (error "Can't open server for %s" group))
1843
1844     ;; Fetch headers.
1845     (when (or gnus-newsgroup-active
1846               (gnus-active group)
1847               (gnus-activate-group group))
1848       (let ((marked-articles gnus-newsgroup-downloadable))
1849         ;; Identify the articles marked for download
1850         (unless gnus-newsgroup-active
1851           ;; The variable gnus-newsgroup-active was selected as I need
1852           ;; a gnus-summary local variable that is NOT bound to any
1853           ;; value (its global value should default to nil).
1854           (dolist (mark gnus-agent-download-marks)
1855             (let ((arts (cdr (assq mark (gnus-info-marks
1856                                          (setq info (gnus-get-info group)))))))
1857               (when arts
1858                 (setq marked-articles (nconc (gnus-uncompress-range arts)
1859                                              marked-articles))
1860                 ))))
1861         (setq marked-articles (sort marked-articles '<))
1862
1863         ;; Fetch any new articles from the server
1864         (setq articles (gnus-agent-fetch-headers group))
1865
1866         ;; Merge new articles with marked
1867         (setq articles (sort (append marked-articles articles) '<))
1868
1869         (when articles
1870           ;; Parse them and see which articles we want to fetch.
1871           (setq gnus-newsgroup-dependencies
1872                 (or gnus-newsgroup-dependencies
1873                     (make-vector (length articles) 0)))
1874           (setq gnus-newsgroup-headers
1875                 (or gnus-newsgroup-headers
1876                     (gnus-get-newsgroup-headers-xover articles nil nil
1877                                                       group)))
1878           ;; `gnus-agent-overview-buffer' may be killed for
1879           ;; timeout reason.  If so, recreate it.
1880           (gnus-agent-create-buffer)
1881
1882           ;; Figure out how to select articles in this group
1883           (setq category (gnus-group-category group))
1884
1885           (setq predicate
1886                 (gnus-get-predicate
1887                  (gnus-agent-find-parameter group 'agent-predicate)))
1888
1889           ;; If the selection predicate requires scoring, score each header
1890           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
1891             (let ((score-param
1892                    (gnus-agent-find-parameter group 'agent-score-file)))
1893               ;; Translate score-param into real one
1894               (cond
1895                ((not score-param))
1896                ((eq score-param 'file)
1897                 (setq score-param (gnus-all-score-files group)))
1898                ((stringp (car score-param)))
1899                (t
1900                 (setq score-param (list (list score-param)))))
1901               (when score-param
1902                 (gnus-score-headers score-param))))
1903
1904           (unless (and (eq predicate 'gnus-agent-false)
1905                        (not marked-articles))
1906             (let ((arts (list nil)))
1907               (let ((arts-tail arts)
1908                     (alist (gnus-agent-load-alist group))
1909                     (marked-articles marked-articles)
1910                     (gnus-newsgroup-headers gnus-newsgroup-headers))
1911                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
1912                   (let ((num (mail-header-number gnus-headers)))
1913                     ;; Determine if this article is already in the cache
1914                     (while (and alist
1915                                 (> num (caar alist)))
1916                       (setq alist (cdr alist)))
1917
1918                     (unless (and (eq num (caar alist))
1919                                  (cdar alist))
1920
1921                       ;; Determine if this article was marked for download.
1922                       (while (and marked-articles
1923                                   (> num (car marked-articles)))
1924                         (setq marked-articles
1925                               (cdr marked-articles)))
1926
1927                       ;; When this article is marked, or selected by the
1928                       ;; predicate, add it to the download list
1929                       (when (or (eq num (car marked-articles))
1930                                 (let ((gnus-score
1931                                        (or (cdr
1932                                             (assq num gnus-newsgroup-scored))
1933                                            gnus-summary-default-score))
1934                                       (gnus-agent-long-article
1935                                        (gnus-agent-find-parameter
1936                                         group 'agent-long-article))
1937                                       (gnus-agent-short-article
1938                                        (gnus-agent-find-parameter
1939                                         group 'agent-short-article))
1940                                       (gnus-agent-low-score
1941                                        (gnus-agent-find-parameter
1942                                         group 'agent-low-score))
1943                                       (gnus-agent-high-score
1944                                        (gnus-agent-find-parameter
1945                                         group 'agent-high-score))
1946                                       (gnus-agent-expire-days
1947                                        (gnus-agent-find-parameter
1948                                         group 'agent-days-until-old)))
1949                                   (funcall predicate)))
1950                         (gnus-agent-append-to-list arts-tail num))))))
1951
1952               (let (fetched-articles)
1953                 ;; Fetch all selected articles
1954                 (setq gnus-newsgroup-undownloaded
1955                       (gnus-sorted-ndifference
1956                        gnus-newsgroup-undownloaded
1957                        (setq fetched-articles
1958                              (if (cdr arts)
1959                                  (gnus-agent-fetch-articles group (cdr arts))
1960                                nil))))
1961
1962                 (let ((unfetched-articles
1963                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
1964                   (if gnus-newsgroup-active
1965                       ;; Update the summary buffer
1966                       (progn
1967                         (dolist (article marked-articles)
1968                           (gnus-summary-set-agent-mark article t))
1969                         (dolist (article fetched-articles)
1970                           (if gnus-agent-mark-unread-after-downloaded
1971                               (gnus-summary-mark-article
1972                                article gnus-unread-mark))
1973                           (when (gnus-summary-goto-subject article nil t)
1974                             (gnus-summary-update-download-mark article)))
1975                         (dolist (article unfetched-articles)
1976                           (gnus-summary-mark-article
1977                            article gnus-canceled-mark)))
1978
1979                     ;; Update the group buffer.
1980
1981                     ;; When some, or all, of the marked articles came
1982                     ;; from the download mark.  Remove that mark.  I
1983                     ;; didn't do this earlier as I only want to remove
1984                     ;; the marks after the fetch is completed.
1985
1986                     (dolist (mark gnus-agent-download-marks)
1987                       (when (eq mark 'download)
1988                         (let ((marked-arts
1989                                (assq mark (gnus-info-marks
1990                                            (setq info (gnus-get-info group))))))
1991                           (when (cdr marked-arts)
1992                             (setq marks
1993                                   (delq marked-arts (gnus-info-marks info)))
1994                             (gnus-info-set-marks info marks)))))
1995                     (let ((read (gnus-info-read
1996                                  (or info (setq info (gnus-get-info group))))))
1997                       (gnus-info-set-read
1998                        info (gnus-add-to-range read unfetched-articles)))
1999
2000                     (gnus-group-update-group group t)
2001                     (sit-for 0)
2002
2003                     (gnus-dribble-enter
2004                      (concat "(gnus-group-set-info '"
2005                              (gnus-prin1-to-string info)
2006                              ")"))))))))))))
2007
2008 ;;;
2009 ;;; Agent Category Mode
2010 ;;;
2011
2012 (defvar gnus-category-mode-hook nil
2013   "Hook run in `gnus-category-mode' buffers.")
2014
2015 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2016   "Format of category lines.
2017
2018 Valid specifiers include:
2019 %c  Topic name (string)
2020 %g  The number of groups in the topic (integer)
2021
2022 General format specifiers can also be used.  See Info node
2023 `(gnus)Formatting Variables'.")
2024
2025 (defvar gnus-category-mode-line-format "Gnus: %%b"
2026   "The format specification for the category mode line.")
2027
2028 (defvar gnus-agent-predicate 'false
2029   "The selection predicate used when no other source is available.")
2030
2031 (defvar gnus-agent-short-article 100
2032   "Articles that have fewer lines than this are short.")
2033
2034 (defvar gnus-agent-long-article 200
2035   "Articles that have more lines than this are long.")
2036
2037 (defvar gnus-agent-low-score 0
2038   "Articles that have a score lower than this have a low score.")
2039
2040 (defvar gnus-agent-high-score 0
2041   "Articles that have a score higher than this have a high score.")
2042
2043
2044 ;;; Internal variables.
2045
2046 (defvar gnus-category-buffer "*Agent Category*")
2047
2048 (defvar gnus-category-line-format-alist
2049   `((?c gnus-tmp-name ?s)
2050     (?g gnus-tmp-groups ?d)))
2051
2052 (defvar gnus-category-mode-line-format-alist
2053   `((?u user-defined ?s)))
2054
2055 (defvar gnus-category-line-format-spec nil)
2056 (defvar gnus-category-mode-line-format-spec nil)
2057
2058 (defvar gnus-category-mode-map nil)
2059 (put 'gnus-category-mode 'mode-class 'special)
2060
2061 (unless gnus-category-mode-map
2062   (setq gnus-category-mode-map (make-sparse-keymap))
2063   (suppress-keymap gnus-category-mode-map)
2064
2065   (gnus-define-keys gnus-category-mode-map
2066     "q" gnus-category-exit
2067     "k" gnus-category-kill
2068     "c" gnus-category-copy
2069     "a" gnus-category-add
2070     "e" gnus-agent-customize-category
2071     "p" gnus-category-edit-predicate
2072     "g" gnus-category-edit-groups
2073     "s" gnus-category-edit-score
2074     "l" gnus-category-list
2075
2076     "\C-c\C-i" gnus-info-find-node
2077     "\C-c\C-b" gnus-bug))
2078
2079 (defvar gnus-category-menu-hook nil
2080   "*Hook run after the creation of the menu.")
2081
2082 (defun gnus-category-make-menu-bar ()
2083   (gnus-turn-off-edit-menu 'category)
2084   (unless (boundp 'gnus-category-menu)
2085     (easy-menu-define
2086      gnus-category-menu gnus-category-mode-map ""
2087      '("Categories"
2088        ["Add" gnus-category-add t]
2089        ["Kill" gnus-category-kill t]
2090        ["Copy" gnus-category-copy t]
2091        ["Edit category" gnus-agent-customize-category t]
2092        ["Edit predicate" gnus-category-edit-predicate t]
2093        ["Edit score" gnus-category-edit-score t]
2094        ["Edit groups" gnus-category-edit-groups t]
2095        ["Exit" gnus-category-exit t]))
2096
2097     (gnus-run-hooks 'gnus-category-menu-hook)))
2098
2099 (defun gnus-category-mode ()
2100   "Major mode for listing and editing agent categories.
2101
2102 All normal editing commands are switched off.
2103 \\<gnus-category-mode-map>
2104 For more in-depth information on this mode, read the manual
2105 \(`\\[gnus-info-find-node]').
2106
2107 The following commands are available:
2108
2109 \\{gnus-category-mode-map}"
2110   (interactive)
2111   (when (gnus-visual-p 'category-menu 'menu)
2112     (gnus-category-make-menu-bar))
2113   (kill-all-local-variables)
2114   (gnus-simplify-mode-line)
2115   (setq major-mode 'gnus-category-mode)
2116   (setq mode-name "Category")
2117   (gnus-set-default-directory)
2118   (setq mode-line-process nil)
2119   (use-local-map gnus-category-mode-map)
2120   (buffer-disable-undo)
2121   (setq truncate-lines t)
2122   (setq buffer-read-only t)
2123   (gnus-run-hooks 'gnus-category-mode-hook))
2124
2125 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2126
2127 (defun gnus-category-insert-line (category)
2128   (let* ((gnus-tmp-name (format "%s" (car category)))
2129          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2130     (beginning-of-line)
2131     (gnus-add-text-properties
2132      (point)
2133      (prog1 (1+ (point))
2134        ;; Insert the text.
2135        (eval gnus-category-line-format-spec))
2136      (list 'gnus-category gnus-tmp-name))))
2137
2138 (defun gnus-enter-category-buffer ()
2139   "Go to the Category buffer."
2140   (interactive)
2141   (gnus-category-setup-buffer)
2142   (gnus-configure-windows 'category)
2143   (gnus-category-prepare))
2144
2145 (defun gnus-category-setup-buffer ()
2146   (unless (get-buffer gnus-category-buffer)
2147     (save-excursion
2148       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2149       (gnus-category-mode))))
2150
2151 (defun gnus-category-prepare ()
2152   (gnus-set-format 'category-mode)
2153   (gnus-set-format 'category t)
2154   (let ((alist gnus-category-alist)
2155         (buffer-read-only nil))
2156     (erase-buffer)
2157     (while alist
2158       (gnus-category-insert-line (pop alist)))
2159     (goto-char (point-min))
2160     (gnus-category-position-point)))
2161
2162 (defun gnus-category-name ()
2163   (or (intern (get-text-property (gnus-point-at-bol) 'gnus-category))
2164       (error "No category on the current line")))
2165
2166 (defun gnus-category-read ()
2167   "Read the category alist."
2168   (setq gnus-category-alist
2169         (or
2170          (with-temp-buffer
2171            (ignore-errors
2172             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2173             (goto-char (point-min))
2174             ;; This code isn't temp, it will be needed so long as
2175             ;; anyone may be migrating from an older version.
2176
2177             ;; Once we're certain that people will not revert to an
2178             ;; earlier version, we can take out the old-list code in
2179             ;; gnus-category-write.
2180             (let* ((old-list (read (current-buffer)))
2181                    (new-list (ignore-errors (read (current-buffer)))))
2182               (if new-list
2183                   new-list
2184                 ;; Convert from a positional list to an alist.
2185                 (mapcar
2186                  (lambda (c)
2187                    (setcdr c
2188                            (delq nil
2189                                  (gnus-mapcar
2190                                   (lambda (valu symb)
2191                                     (if valu
2192                                         (cons symb valu)))
2193                                   (cdr c)
2194                                   '(agent-predicate agent-score-file agent-groups))))
2195                    c)
2196                  old-list)))))
2197          (list (gnus-agent-cat-make 'default 'short)))))
2198
2199 (defun gnus-category-write ()
2200   "Write the category alist."
2201   (setq gnus-category-predicate-cache nil
2202         gnus-category-group-cache nil)
2203   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2204   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2205     ;; This prin1 is temporary.  It exists so that people can revert
2206     ;; to an earlier version of gnus-agent.
2207     (prin1 (mapcar (lambda (c)
2208               (list (car c)
2209                     (cdr (assoc 'agent-predicate c))
2210                     (cdr (assoc 'agent-score-file c))
2211                     (cdr (assoc 'agent-groups c))))
2212                    gnus-category-alist)
2213            (current-buffer))
2214     (newline)
2215     (prin1 gnus-category-alist (current-buffer))))
2216
2217 (defun gnus-category-edit-predicate (category)
2218   "Edit the predicate for CATEGORY."
2219   (interactive (list (gnus-category-name)))
2220   (let ((info (assq category gnus-category-alist)))
2221     (gnus-edit-form
2222      (gnus-agent-cat-predicate info)
2223      (format "Editing the select predicate for category %s" category)
2224      `(lambda (predicate)
2225         ;; Avoid run-time execution of setf form
2226         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2227         ;;       predicate)
2228         ;; use its expansion instead:
2229         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2230                                      'agent-predicate predicate)
2231
2232         (gnus-category-write)
2233         (gnus-category-list)))))
2234
2235 (defun gnus-category-edit-score (category)
2236   "Edit the score expression for CATEGORY."
2237   (interactive (list (gnus-category-name)))
2238   (let ((info (assq category gnus-category-alist)))
2239     (gnus-edit-form
2240      (gnus-agent-cat-score-file info)
2241      (format "Editing the score expression for category %s" category)
2242      `(lambda (score-file)
2243         ;; Avoid run-time execution of setf form
2244         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2245         ;;       score-file)
2246         ;; use its expansion instead:
2247         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2248                                      'agent-score-file score-file)
2249
2250         (gnus-category-write)
2251         (gnus-category-list)))))
2252
2253 (defun gnus-category-edit-groups (category)
2254   "Edit the group list for CATEGORY."
2255   (interactive (list (gnus-category-name)))
2256   (let ((info (assq category gnus-category-alist)))
2257     (gnus-edit-form
2258      (gnus-agent-cat-groups info)
2259      (format "Editing the group list for category %s" category)
2260      `(lambda (groups)
2261         ;; Avoid run-time execution of setf form
2262         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2263         ;;       groups)
2264         ;; use its expansion instead:
2265         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2266                                    groups)
2267
2268         (gnus-category-write)
2269         (gnus-category-list)))))
2270
2271 (defun gnus-category-kill (category)
2272   "Kill the current category."
2273   (interactive (list (gnus-category-name)))
2274   (let ((info (assq category gnus-category-alist))
2275         (buffer-read-only nil))
2276     (gnus-delete-line)
2277     (setq gnus-category-alist (delq info gnus-category-alist))
2278     (gnus-category-write)))
2279
2280 (defun gnus-category-copy (category to)
2281   "Copy the current category."
2282   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2283   (let ((info (assq category gnus-category-alist)))
2284     (push (let ((newcat (gnus-copy-sequence info)))
2285             (setf (gnus-agent-cat-name newcat) to)
2286             (setf (gnus-agent-cat-groups newcat) nil)
2287             newcat)
2288           gnus-category-alist)
2289     (gnus-category-write)
2290     (gnus-category-list)))
2291
2292 (defun gnus-category-add (category)
2293   "Create a new category."
2294   (interactive "SCategory name: ")
2295   (when (assq category gnus-category-alist)
2296     (error "Category %s already exists" category))
2297   (push (gnus-agent-cat-make category)
2298         gnus-category-alist)
2299   (gnus-category-write)
2300   (gnus-category-list))
2301
2302 (defun gnus-category-list ()
2303   "List all categories."
2304   (interactive)
2305   (gnus-category-prepare))
2306
2307 (defun gnus-category-exit ()
2308   "Return to the group buffer."
2309   (interactive)
2310   (kill-buffer (current-buffer))
2311   (gnus-configure-windows 'group t))
2312
2313 ;; To avoid having 8-bit characters in the source file.
2314 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2315
2316 (defvar gnus-category-predicate-alist
2317   '((spam . gnus-agent-spam-p)
2318     (short . gnus-agent-short-p)
2319     (long . gnus-agent-long-p)
2320     (low . gnus-agent-low-scored-p)
2321     (high . gnus-agent-high-scored-p)
2322     (read . gnus-agent-read-p)
2323     (true . gnus-agent-true)
2324     (false . gnus-agent-false))
2325   "Mapping from short score predicate symbols to predicate functions.")
2326
2327 (defun gnus-agent-spam-p ()
2328   "Say whether an article is spam or not."
2329   (unless gnus-agent-spam-hashtb
2330     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2331   (if (not (equal (mail-header-references gnus-headers) ""))
2332       nil
2333     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2334       (prog1
2335           (gnus-gethash string gnus-agent-spam-hashtb)
2336         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2337
2338 (defun gnus-agent-short-p ()
2339   "Say whether an article is short or not."
2340   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2341
2342 (defun gnus-agent-long-p ()
2343   "Say whether an article is long or not."
2344   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2345
2346 (defun gnus-agent-low-scored-p ()
2347   "Say whether an article has a low score or not."
2348   (< gnus-score gnus-agent-low-score))
2349
2350 (defun gnus-agent-high-scored-p ()
2351   "Say whether an article has a high score or not."
2352   (> gnus-score gnus-agent-high-score))
2353
2354 (defun gnus-agent-read-p ()
2355   "Say whether an article is read or not."
2356   (gnus-member-of-range (mail-header-number gnus-headers)
2357                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2358
2359 (defun gnus-category-make-function (predicate)
2360   "Make a function from PREDICATE."
2361   (let ((func (gnus-category-make-function-1 predicate)))
2362     (if (and (= (length func) 1)
2363              (symbolp (car func)))
2364         (car func)
2365       (gnus-byte-compile `(lambda () ,func)))))
2366
2367 (defun gnus-agent-true ()
2368   "Return t."
2369   t)
2370
2371 (defun gnus-agent-false ()
2372   "Return nil."
2373   nil)
2374
2375 (defun gnus-category-make-function-1 (predicate)
2376   "Make a function from PREDICATE."
2377   (cond
2378    ;; Functions are just returned as is.
2379    ((or (symbolp predicate)
2380         (functionp predicate))
2381     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2382            predicate)))
2383    ;; More complex predicate.
2384    ((consp predicate)
2385     `(,(cond
2386         ((memq (car predicate) '(& and))
2387          'and)
2388         ((memq (car predicate) '(| or))
2389          'or)
2390         ((memq (car predicate) gnus-category-not)
2391          'not))
2392       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2393    (t
2394     (error "Unknown predicate type: %s" predicate))))
2395
2396 (defun gnus-get-predicate (predicate)
2397   "Return the function implementing PREDICATE."
2398   (or (cdr (assoc predicate gnus-category-predicate-cache))
2399       (let ((func (gnus-category-make-function predicate)))
2400         (setq gnus-category-predicate-cache
2401               (nconc gnus-category-predicate-cache
2402                      (list (cons predicate func))))
2403         func)))
2404
2405 (defun gnus-predicate-implies-unread (predicate)
2406   "Say whether PREDICATE implies unread articles only.
2407 It is okay to miss some cases, but there must be no false positives.
2408 That is, if this function returns true, then indeed the predicate must
2409 return only unread articles."
2410   (gnus-function-implies-unread-1 (gnus-category-make-function predicate)))
2411
2412 (defun gnus-function-implies-unread-1 (function)
2413   (cond ((eq function (symbol-function 'gnus-agent-read-p))
2414          nil)
2415         ((not function)
2416          nil)
2417         ((functionp function)
2418          'ignore)
2419         ((memq (car function) '(or and not))
2420          (apply (car function)
2421                 (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2422         (t
2423          (error "Unknown function: %s" function))))
2424
2425 (defun gnus-group-category (group)
2426   "Return the category GROUP belongs to."
2427   (unless gnus-category-group-cache
2428     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2429     (let ((cs gnus-category-alist)
2430           groups cat)
2431       (while (setq cat (pop cs))
2432         (setq groups (gnus-agent-cat-groups cat))
2433         (while groups
2434           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2435   (or (gnus-gethash group gnus-category-group-cache)
2436       (assq 'default gnus-category-alist)))
2437
2438 (defun gnus-agent-expire-group (group &optional articles force)
2439   "Expire all old articles in GROUP.
2440 If you want to force expiring of certain articles, this function can
2441 take ARTICLES, and FORCE parameters as well.
2442
2443 The articles on which the expiration process runs are selected as follows:
2444   if ARTICLES is null, all read and unmarked articles.
2445   if ARTICLES is t, all articles.
2446   if ARTICLES is a list, just those articles.
2447 FORCE is equivalent to setting the expiration predicates to true."
2448   (interactive
2449    (list (let ((def (or (gnus-group-group-name)
2450                         gnus-newsgroup-name)))
2451            (let ((select (read-string (if def
2452                                           (concat "Group Name ("
2453                                                   def "): ")
2454                                         "Group Name: "))))
2455              (if (and (equal "" select)
2456                       def)
2457                  def
2458                select)))))
2459
2460   (if (not group)
2461       (gnus-agent-expire articles group force)
2462     (if (or (not (eq articles t))
2463             (yes-or-no-p
2464              (concat "Are you sure that you want to "
2465                      "expire all articles in " group ".")))
2466         (let ((gnus-command-method (gnus-find-method-for-group group))
2467               (overview (gnus-get-buffer-create " *expire overview*"))
2468               orig)
2469           (unwind-protect
2470               (let ((active-file (gnus-agent-lib-file "active")))
2471                 (when (file-exists-p active-file)
2472                   (with-temp-buffer
2473                     (nnheader-insert-file-contents active-file)
2474                     (gnus-active-to-gnus-format
2475                      gnus-command-method
2476                      (setq orig (gnus-make-hashtable
2477                                  (count-lines (point-min) (point-max))))))
2478                   (save-excursion
2479                     (gnus-agent-expire-group-1
2480                      group overview (gnus-gethash-safe group orig)
2481                      articles force))
2482                   (gnus-agent-write-active active-file orig t)))
2483             (kill-buffer overview))))
2484     (gnus-message 4 "Expiry...done")))
2485
2486 (defun gnus-agent-expire-group-1 (group overview active articles force)
2487   ;; Internal function - requires caller to have set
2488   ;; gnus-command-method, initialized overview buffer, and to have
2489   ;; provided a non-nil active
2490
2491   (let ((dir (gnus-agent-group-pathname group)))
2492     (when (boundp 'gnus-agent-expire-current-dirs)
2493       (set 'gnus-agent-expire-current-dirs 
2494            (cons dir 
2495                  (symbol-value 'gnus-agent-expire-current-dirs))))
2496
2497     (if (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