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