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