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