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