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