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