Synch to No Gnus 200511122247.
[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                  (not (eq (gnus-server-status gnus-command-method) 'offline)))
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 unfortunite 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       (let (sort art)
1975         (while (not (eobp))
1976           (setq art (gnus-agent-read-article-number))
1977           (cond ((not art)
1978                  ;; Bad art num - delete this line
1979                  (beginning-of-line)
1980                  (delete-region (point) (progn (forward-line 1) (point))))
1981                 ((< art last)
1982                  ;; Art num out of order - enable sort
1983                  (setq sort t)
1984                  (forward-line 1))
1985                 (t
1986                  ;; Good art num
1987                  (setq last art)
1988                  (forward-line 1))))
1989         (when sort
1990           (sort-numeric-fields 1 (point-min) (point-max)))))))
1991
1992 ;; Keeps the compiler from warning about the free variable in
1993 ;; gnus-agent-read-agentview.
1994 (eval-when-compile
1995   (defvar gnus-agent-read-agentview))
1996
1997 (defun gnus-agent-load-alist (group)
1998   "Load the article-state alist for GROUP."
1999   ;; Bind free variable that's used in `gnus-agent-read-agentview'.
2000   (let ((gnus-agent-read-agentview group))
2001     (setq gnus-agent-article-alist
2002           (gnus-cache-file-contents
2003            (gnus-agent-article-name ".agentview" group)
2004            'gnus-agent-file-loading-cache
2005            'gnus-agent-read-agentview))))
2006
2007 (defun gnus-agent-read-agentview (file)
2008   "Load FILE and do a `read' there."
2009   (with-temp-buffer
2010     (condition-case nil
2011         (progn
2012           (nnheader-insert-file-contents file)
2013           (goto-char (point-min))
2014           (let ((alist (read (current-buffer)))
2015                 (version (condition-case nil (read (current-buffer))
2016                            (end-of-file 0)))
2017                 changed-version)
2018
2019             (cond
2020              ((= version 0)
2021               (let ((inhibit-quit t)
2022                     entry)
2023                 (gnus-agent-open-history)
2024                 (set-buffer (gnus-agent-history-buffer))
2025                 (goto-char (point-min))
2026                 (while (not (eobp))
2027                   (if (and (looking-at
2028                             "[^\t\n]+\t\\([0-9]+\\)\t\\([^ \n]+\\) \\([0-9]+\\)")
2029                            (string= (match-string 2)
2030                                     gnus-agent-read-agentview)
2031                            (setq entry (assoc (string-to-number (match-string 3)) alist)))
2032                       (setcdr entry (string-to-number (match-string 1))))
2033                   (forward-line 1))
2034                 (gnus-agent-close-history)
2035                 (setq changed-version t)))
2036              ((= version 1)
2037               (setq changed-version (not (= 1 gnus-agent-article-alist-save-format))))
2038              ((= version 2)
2039               (let (uncomp)
2040                 (mapcar
2041                  (lambda (comp-list)
2042                    (let ((state (car comp-list))
2043                          (sequence (inline
2044                                      (gnus-uncompress-range
2045                                       (cdr comp-list)))))
2046                      (mapcar (lambda (article-id)
2047                                (setq uncomp (cons (cons article-id state) uncomp)))
2048                              sequence)))
2049                  alist)
2050                 (setq alist (sort uncomp 'car-less-than-car)))
2051               (setq changed-version (not (= 2 gnus-agent-article-alist-save-format)))))
2052             (when changed-version
2053               (let ((gnus-agent-article-alist alist))
2054                 (gnus-agent-save-alist gnus-agent-read-agentview)))
2055             alist))
2056       (file-error nil))))
2057
2058 (defun gnus-agent-save-alist (group &optional articles state)
2059   "Save the article-state alist for GROUP."
2060   (let* ((file-name-coding-system nnmail-pathname-coding-system)
2061          (prev (cons nil gnus-agent-article-alist))
2062          (all prev)
2063          print-level print-length item article)
2064     (while (setq article (pop articles))
2065       (while (and (cdr prev)
2066                   (< (caadr prev) article))
2067         (setq prev (cdr prev)))
2068       (cond
2069        ((not (cdr prev))
2070         (setcdr prev (list (cons article state))))
2071        ((> (caadr prev) article)
2072         (setcdr prev (cons (cons article state) (cdr prev))))
2073        ((= (caadr prev) article)
2074         (setcdr (cadr prev) state)))
2075       (setq prev (cdr prev)))
2076     (setq gnus-agent-article-alist (cdr all))
2077
2078     (gnus-agent-set-local group
2079                           (caar gnus-agent-article-alist)
2080                           (caar (last gnus-agent-article-alist)))
2081
2082     (gnus-make-directory (gnus-agent-article-name "" group))
2083     (with-temp-file (gnus-agent-article-name ".agentview" group)
2084       (cond ((eq gnus-agent-article-alist-save-format 1)
2085              (princ gnus-agent-article-alist (current-buffer)))
2086             ((eq gnus-agent-article-alist-save-format 2)
2087              (let ((compressed nil))
2088                (mapcar (lambda (pair)
2089                          (let* ((article-id (car pair))
2090                                 (day-of-download (cdr pair))
2091                                 (comp-list (assq day-of-download compressed)))
2092                            (if comp-list
2093                                (setcdr comp-list
2094                                        (cons article-id (cdr comp-list)))
2095                              (setq compressed
2096                                    (cons (list day-of-download article-id)
2097                                          compressed)))
2098                            nil)) gnus-agent-article-alist)
2099                (mapcar (lambda (comp-list)
2100                          (setcdr comp-list
2101                                  (gnus-compress-sequence
2102                                   (nreverse (cdr comp-list)))))
2103                        compressed)
2104                (princ compressed (current-buffer)))))
2105       (insert "\n")
2106       (princ gnus-agent-article-alist-save-format (current-buffer))
2107       (insert "\n"))
2108
2109     (gnus-agent-update-view-total-fetched-for group nil)))
2110
2111 (defvar gnus-agent-article-local nil)
2112 (defvar gnus-agent-file-loading-local nil)
2113
2114 (defun gnus-agent-load-local (&optional method)
2115   "Load the METHOD'S local file.  The local file contains min/max
2116 article counts for each of the method's subscribed groups."
2117   (let ((gnus-command-method (or method gnus-command-method)))
2118     (setq gnus-agent-article-local
2119           (gnus-cache-file-contents
2120            (gnus-agent-lib-file "local")
2121            'gnus-agent-file-loading-local
2122            'gnus-agent-read-and-cache-local))))
2123
2124 (defun gnus-agent-read-and-cache-local (file)
2125   "Load and read FILE then bind its contents to
2126 gnus-agent-article-local.  If that variable had `dirty' (also known as
2127 modified) original contents, they are first saved to their own file."
2128
2129   (if (and gnus-agent-article-local
2130            (symbol-value (intern "+dirty" gnus-agent-article-local)))
2131       (gnus-agent-save-local))
2132   (gnus-agent-read-local file))
2133
2134 (defun gnus-agent-read-local (file)
2135   "Load FILE and do a `read' there."
2136   (let ((my-obarray (gnus-make-hashtable (count-lines (point-min)
2137                                                       (point-max))))
2138         (line 1))
2139     (with-temp-buffer
2140       (condition-case nil
2141           (let ((nnheader-file-coding-system gnus-agent-file-coding-system))
2142             (nnheader-insert-file-contents file))
2143         (file-error))
2144
2145       (goto-char (point-min))
2146       ;; Skip any comments at the beginning of the file (the only place where they may appear)
2147       (while (= (following-char) ?\;)
2148         (forward-line 1)
2149         (setq line (1+ line)))
2150
2151       (while (not (eobp))
2152         (condition-case err
2153             (let (group
2154                   min
2155                   max
2156                   (cur (current-buffer)))
2157               (setq group (read cur)
2158                     min (read cur)
2159                     max (read cur))
2160
2161               (when (stringp group)
2162                 (setq group (intern group my-obarray)))
2163
2164               ;; NOTE: The '+ 0' ensure that min and max are both numerics.
2165               (set group (cons (+ 0 min) (+ 0 max))))
2166           (error
2167            (gnus-message 3 "Warning - invalid agent local: %s on line %d: "
2168                          file line (error-message-string err))))
2169         (forward-line 1)
2170         (setq line (1+ line))))
2171
2172     (set (intern "+dirty" my-obarray) nil)
2173     (set (intern "+method" my-obarray) gnus-command-method)
2174     my-obarray))
2175
2176 (defun gnus-agent-save-local (&optional force)
2177   "Save gnus-agent-article-local under it method's agent.lib directory."
2178   (let ((my-obarray gnus-agent-article-local))
2179     (when (and my-obarray
2180                (or force (symbol-value (intern "+dirty" my-obarray))))
2181       (let* ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2182              ;; NOTE: gnus-command-method is used within gnus-agent-lib-file.
2183              (dest (gnus-agent-lib-file "local")))
2184         (gnus-make-directory (gnus-agent-lib-file ""))
2185
2186         (let ((buffer-file-coding-system gnus-agent-file-coding-system))
2187           (with-temp-file dest
2188             (let ((gnus-command-method (symbol-value (intern "+method" my-obarray)))
2189                   (file-name-coding-system nnmail-pathname-coding-system)
2190                   print-level print-length item article
2191                   (standard-output (current-buffer)))
2192               (mapatoms (lambda (symbol)
2193                           (cond ((not (boundp symbol))
2194                                  nil)
2195                                 ((member (symbol-name symbol) '("+dirty" "+method"))
2196                                  nil)
2197                                 (t
2198                                  (prin1 symbol)
2199                                  (let ((range (symbol-value symbol)))
2200                                    (princ " ")
2201                                    (princ (car range))
2202                                    (princ " ")
2203                                    (princ (cdr range))
2204                                    (princ "\n")))))
2205                         my-obarray))))))))
2206
2207 (defun gnus-agent-get-local (group &optional gmane method)
2208   (let* ((gmane (or gmane (gnus-group-real-name group)))
2209          (gnus-command-method (or method (gnus-find-method-for-group group)))
2210          (local (gnus-agent-load-local))
2211          (symb (intern gmane local))
2212          (minmax (and (boundp symb) (symbol-value symb))))
2213     (unless minmax
2214       ;; Bind these so that gnus-agent-load-alist doesn't change the
2215       ;; current alist (i.e. gnus-agent-article-alist)
2216       (let* ((gnus-agent-article-alist gnus-agent-article-alist)
2217              (gnus-agent-file-loading-cache gnus-agent-file-loading-cache)
2218              (alist (gnus-agent-load-alist group)))
2219         (when alist
2220           (setq minmax
2221                 (cons (caar alist)
2222                       (caar (last alist))))
2223           (gnus-agent-set-local group (car minmax) (cdr minmax)
2224                                 gmane gnus-command-method local))))
2225     minmax))
2226
2227 (defun gnus-agent-set-local (group min max &optional gmane method local)
2228   (let* ((gmane (or gmane (gnus-group-real-name group)))
2229          (gnus-command-method (or method (gnus-find-method-for-group group)))
2230          (local (or local (gnus-agent-load-local)))
2231          (symb (intern gmane local))
2232          (minmax (and (boundp symb) (symbol-value symb))))
2233
2234     (if (cond ((and minmax
2235                     (or (not (eq min (car minmax)))
2236                         (not (eq max (cdr minmax)))))
2237                (setcar minmax min)
2238                (setcdr minmax max)
2239                t)
2240               (minmax
2241                nil)
2242               ((and min max)
2243                (set symb (cons min max))
2244                t)
2245               (t
2246                (unintern symb local)))
2247         (set (intern "+dirty" local) t))))
2248
2249 (defun gnus-agent-article-name (article group)
2250   (expand-file-name article
2251                     (file-name-as-directory
2252                      (gnus-agent-group-pathname group))))
2253
2254 (defun gnus-agent-batch-confirmation (msg)
2255   "Show error message and return t."
2256   (gnus-message 1 msg)
2257   t)
2258
2259 ;;;###autoload
2260 (defun gnus-agent-batch-fetch ()
2261   "Start Gnus and fetch session."
2262   (interactive)
2263   (gnus)
2264   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
2265     (gnus-agent-fetch-session))
2266   (gnus-group-exit))
2267
2268 (defun gnus-agent-fetch-session ()
2269   "Fetch all articles and headers that are eligible for fetching."
2270   (interactive)
2271   (unless gnus-agent-covered-methods
2272     (error "No servers are covered by the Gnus agent"))
2273   (unless gnus-plugged
2274     (error "Can't fetch articles while Gnus is unplugged"))
2275   (let ((methods (gnus-agent-covered-methods))
2276         groups group gnus-command-method)
2277     (save-excursion
2278       (while methods
2279         (setq gnus-command-method (car methods))
2280         (when (and (or (gnus-server-opened gnus-command-method)
2281                        (gnus-open-server gnus-command-method))
2282                    (gnus-online gnus-command-method))
2283           (setq groups (gnus-groups-from-server (car methods)))
2284           (gnus-agent-with-fetch
2285             (while (setq group (pop groups))
2286               (when (<= (gnus-group-level group)
2287                         gnus-agent-handle-level)
2288                 (if (or debug-on-error debug-on-quit)
2289                     (gnus-agent-fetch-group-1
2290                      group gnus-command-method)
2291                   (condition-case err
2292                       (gnus-agent-fetch-group-1
2293                        group gnus-command-method)
2294                     (error
2295                      (unless (funcall gnus-agent-confirmation-function
2296                                       (format "Error %s while fetching session.  Should gnus continue? "
2297                                               (error-message-string err)))
2298                        (error "Cannot fetch articles into the Gnus agent")))
2299                     (quit
2300                      (gnus-agent-regenerate-group group)
2301                      (unless (funcall gnus-agent-confirmation-function
2302                                       (format
2303                                        "%s while fetching session.  Should gnus continue? "
2304                                        (error-message-string err)))
2305                        (signal 'quit
2306                                "Cannot fetch articles into the Gnus agent")))))))))
2307         (setq methods (cdr methods)))
2308       (gnus-run-hooks 'gnus-agent-fetched-hook)
2309       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
2310
2311 (defun gnus-agent-fetch-group-1 (group method)
2312   "Fetch GROUP."
2313   (let ((gnus-command-method method)
2314         (gnus-newsgroup-name group)
2315         (gnus-newsgroup-dependencies gnus-newsgroup-dependencies)
2316         (gnus-newsgroup-headers gnus-newsgroup-headers)
2317         (gnus-newsgroup-scored gnus-newsgroup-scored)
2318         (gnus-use-cache gnus-use-cache)
2319         (gnus-summary-expunge-below gnus-summary-expunge-below)
2320         (gnus-summary-mark-below gnus-summary-mark-below)
2321         (gnus-orphan-score gnus-orphan-score)
2322         ;; Maybe some other gnus-summary local variables should also
2323         ;; be put here.
2324
2325         gnus-headers
2326         gnus-score
2327         articles arts
2328         category predicate info marks score-param
2329         )
2330     (unless (gnus-check-group group)
2331       (error "Can't open server for %s" group))
2332
2333     ;; Fetch headers.
2334     (when (or gnus-newsgroup-active
2335               (gnus-active group)
2336               (gnus-activate-group group))
2337       (let ((marked-articles gnus-newsgroup-downloadable))
2338         ;; Identify the articles marked for download
2339         (unless gnus-newsgroup-active
2340           ;; The variable gnus-newsgroup-active was selected as I need
2341           ;; a gnus-summary local variable that is NOT bound to any
2342           ;; value (its global value should default to nil).
2343           (dolist (mark gnus-agent-download-marks)
2344             (let ((arts (cdr (assq mark (gnus-info-marks
2345                                          (setq info (gnus-get-info group)))))))
2346               (when arts
2347                 (setq marked-articles (nconc (gnus-uncompress-range arts)
2348                                              marked-articles))
2349                 ))))
2350         (setq marked-articles (sort marked-articles '<))
2351
2352         ;; Fetch any new articles from the server
2353         (setq articles (gnus-agent-fetch-headers group))
2354
2355         ;; Merge new articles with marked
2356         (setq articles (sort (append marked-articles articles) '<))
2357
2358         (when articles
2359           ;; Parse them and see which articles we want to fetch.
2360           (setq gnus-newsgroup-dependencies
2361                 (or gnus-newsgroup-dependencies
2362                     (make-vector (length articles) 0)))
2363           (setq gnus-newsgroup-headers
2364                 (or gnus-newsgroup-headers
2365                     (gnus-get-newsgroup-headers-xover articles nil nil
2366                                                       group)))
2367           ;; `gnus-agent-overview-buffer' may be killed for
2368           ;; timeout reason.  If so, recreate it.
2369           (gnus-agent-create-buffer)
2370
2371           ;; Figure out how to select articles in this group
2372           (setq category (gnus-group-category group))
2373
2374           (setq predicate
2375                 (gnus-get-predicate
2376                  (gnus-agent-find-parameter group 'agent-predicate)))
2377
2378           ;; If the selection predicate requires scoring, score each header
2379           (unless (memq predicate '(gnus-agent-true gnus-agent-false))
2380             (let ((score-param
2381                    (gnus-agent-find-parameter group 'agent-score-file)))
2382               ;; Translate score-param into real one
2383               (cond
2384                ((not score-param))
2385                ((eq score-param 'file)
2386                 (setq score-param (gnus-all-score-files group)))
2387                ((stringp (car score-param)))
2388                (t
2389                 (setq score-param (list (list score-param)))))
2390               (when score-param
2391                 (gnus-score-headers score-param))))
2392
2393           (unless (and (eq predicate 'gnus-agent-false)
2394                        (not marked-articles))
2395             (let ((arts (list nil)))
2396               (let ((arts-tail arts)
2397                     (alist (gnus-agent-load-alist group))
2398                     (marked-articles marked-articles)
2399                     (gnus-newsgroup-headers gnus-newsgroup-headers))
2400                 (while (setq gnus-headers (pop gnus-newsgroup-headers))
2401                   (let ((num (mail-header-number gnus-headers)))
2402                     ;; Determine if this article is already in the cache
2403                     (while (and alist
2404                                 (> num (caar alist)))
2405                       (setq alist (cdr alist)))
2406
2407                     (unless (and (eq num (caar alist))
2408                                  (cdar alist))
2409
2410                       ;; Determine if this article was marked for download.
2411                       (while (and marked-articles
2412                                   (> num (car marked-articles)))
2413                         (setq marked-articles
2414                               (cdr marked-articles)))
2415
2416                       ;; When this article is marked, or selected by the
2417                       ;; predicate, add it to the download list
2418                       (when (or (eq num (car marked-articles))
2419                                 (let ((gnus-score
2420                                        (or (cdr
2421                                             (assq num gnus-newsgroup-scored))
2422                                            gnus-summary-default-score))
2423                                       (gnus-agent-long-article
2424                                        (gnus-agent-find-parameter
2425                                         group 'agent-long-article))
2426                                       (gnus-agent-short-article
2427                                        (gnus-agent-find-parameter
2428                                         group 'agent-short-article))
2429                                       (gnus-agent-low-score
2430                                        (gnus-agent-find-parameter
2431                                         group 'agent-low-score))
2432                                       (gnus-agent-high-score
2433                                        (gnus-agent-find-parameter
2434                                         group 'agent-high-score))
2435                                       (gnus-agent-expire-days
2436                                        (gnus-agent-find-parameter
2437                                         group 'agent-days-until-old)))
2438                                   (funcall predicate)))
2439                         (gnus-agent-append-to-list arts-tail num))))))
2440
2441               (let (fetched-articles)
2442                 ;; Fetch all selected articles
2443                 (setq gnus-newsgroup-undownloaded
2444                       (gnus-sorted-ndifference
2445                        gnus-newsgroup-undownloaded
2446                        (setq fetched-articles
2447                              (if (cdr arts)
2448                                  (gnus-agent-fetch-articles group (cdr arts))
2449                                nil))))
2450
2451                 (let ((unfetched-articles
2452                        (gnus-sorted-ndifference (cdr arts) fetched-articles)))
2453                   (if gnus-newsgroup-active
2454                       ;; Update the summary buffer
2455                       (progn
2456                         (dolist (article marked-articles)
2457                           (gnus-summary-set-agent-mark article t))
2458                         (dolist (article fetched-articles)
2459                           (when gnus-agent-mark-unread-after-downloaded
2460                             (setq gnus-newsgroup-downloadable
2461                                   (delq article gnus-newsgroup-downloadable))
2462                             (gnus-summary-mark-article
2463                              article gnus-unread-mark))
2464                           (when (gnus-summary-goto-subject article nil t)
2465                             (gnus-summary-update-download-mark article)))
2466                         (dolist (article unfetched-articles)
2467                           (gnus-summary-mark-article
2468                            article gnus-canceled-mark)))
2469
2470                     ;; Update the group buffer.
2471
2472                     ;; When some, or all, of the marked articles came
2473                     ;; from the download mark.  Remove that mark.  I
2474                     ;; didn't do this earlier as I only want to remove
2475                     ;; the marks after the fetch is completed.
2476
2477                     (dolist (mark gnus-agent-download-marks)
2478                       (when (eq mark 'download)
2479                         (let ((marked-arts
2480                                (assq mark (gnus-info-marks
2481                                            (setq info (gnus-get-info group))))))
2482                           (when (cdr marked-arts)
2483                             (setq marks
2484                                   (delq marked-arts (gnus-info-marks info)))
2485                             (gnus-info-set-marks info marks)))))
2486                     (let ((read (gnus-info-read
2487                                  (or info (setq info (gnus-get-info group))))))
2488                       (gnus-info-set-read
2489                        info (gnus-add-to-range read unfetched-articles)))
2490
2491                     (gnus-group-update-group group t)
2492                     (sit-for 0)
2493
2494                     (gnus-dribble-enter
2495                      (concat "(gnus-group-set-info '"
2496                              (gnus-prin1-to-string info)
2497                              ")"))))))))))))
2498
2499 ;;;
2500 ;;; Agent Category Mode
2501 ;;;
2502
2503 (defvar gnus-category-mode-hook nil
2504   "Hook run in `gnus-category-mode' buffers.")
2505
2506 (defvar gnus-category-line-format "     %(%20c%): %g\n"
2507   "Format of category lines.
2508
2509 Valid specifiers include:
2510 %c  Topic name (string)
2511 %g  The number of groups in the topic (integer)
2512
2513 General format specifiers can also be used.  See Info node
2514 `(gnus)Formatting Variables'.")
2515
2516 (defvar gnus-category-mode-line-format "Gnus: %%b"
2517   "The format specification for the category mode line.")
2518
2519 (defvar gnus-agent-predicate 'false
2520   "The selection predicate used when no other source is available.")
2521
2522 (defvar gnus-agent-short-article 100
2523   "Articles that have fewer lines than this are short.")
2524
2525 (defvar gnus-agent-long-article 200
2526   "Articles that have more lines than this are long.")
2527
2528 (defvar gnus-agent-low-score 0
2529   "Articles that have a score lower than this have a low score.")
2530
2531 (defvar gnus-agent-high-score 0
2532   "Articles that have a score higher than this have a high score.")
2533
2534
2535 ;;; Internal variables.
2536
2537 (defvar gnus-category-buffer "*Agent Category*")
2538
2539 (defvar gnus-category-line-format-alist
2540   `((?c gnus-tmp-name ?s)
2541     (?g gnus-tmp-groups ?d)))
2542
2543 (defvar gnus-category-mode-line-format-alist
2544   `((?u user-defined ?s)))
2545
2546 (defvar gnus-category-line-format-spec nil)
2547 (defvar gnus-category-mode-line-format-spec nil)
2548
2549 (defvar gnus-category-mode-map nil)
2550 (put 'gnus-category-mode 'mode-class 'special)
2551
2552 (unless gnus-category-mode-map
2553   (setq gnus-category-mode-map (make-sparse-keymap))
2554   (suppress-keymap gnus-category-mode-map)
2555
2556   (gnus-define-keys gnus-category-mode-map
2557     "q" gnus-category-exit
2558     "k" gnus-category-kill
2559     "c" gnus-category-copy
2560     "a" gnus-category-add
2561     "e" gnus-agent-customize-category
2562     "p" gnus-category-edit-predicate
2563     "g" gnus-category-edit-groups
2564     "s" gnus-category-edit-score
2565     "l" gnus-category-list
2566
2567     "\C-c\C-i" gnus-info-find-node
2568     "\C-c\C-b" gnus-bug))
2569
2570 (defvar gnus-category-menu-hook nil
2571   "*Hook run after the creation of the menu.")
2572
2573 (defun gnus-category-make-menu-bar ()
2574   (gnus-turn-off-edit-menu 'category)
2575   (unless (boundp 'gnus-category-menu)
2576     (easy-menu-define
2577      gnus-category-menu gnus-category-mode-map ""
2578      '("Categories"
2579        ["Add" gnus-category-add t]
2580        ["Kill" gnus-category-kill t]
2581        ["Copy" gnus-category-copy t]
2582        ["Edit category" gnus-agent-customize-category t]
2583        ["Edit predicate" gnus-category-edit-predicate t]
2584        ["Edit score" gnus-category-edit-score t]
2585        ["Edit groups" gnus-category-edit-groups t]
2586        ["Exit" gnus-category-exit t]))
2587
2588     (gnus-run-hooks 'gnus-category-menu-hook)))
2589
2590 (defun gnus-category-mode ()
2591   "Major mode for listing and editing agent categories.
2592
2593 All normal editing commands are switched off.
2594 \\<gnus-category-mode-map>
2595 For more in-depth information on this mode, read the manual
2596 \(`\\[gnus-info-find-node]').
2597
2598 The following commands are available:
2599
2600 \\{gnus-category-mode-map}"
2601   (interactive)
2602   (when (gnus-visual-p 'category-menu 'menu)
2603     (gnus-category-make-menu-bar))
2604   (kill-all-local-variables)
2605   (gnus-simplify-mode-line)
2606   (setq major-mode 'gnus-category-mode)
2607   (setq mode-name "Category")
2608   (gnus-set-default-directory)
2609   (setq mode-line-process nil)
2610   (use-local-map gnus-category-mode-map)
2611   (buffer-disable-undo)
2612   (setq truncate-lines t)
2613   (setq buffer-read-only t)
2614   (gnus-run-mode-hooks 'gnus-category-mode-hook))
2615
2616 (defalias 'gnus-category-position-point 'gnus-goto-colon)
2617
2618 (defun gnus-category-insert-line (category)
2619   (let* ((gnus-tmp-name (format "%s" (car category)))
2620          (gnus-tmp-groups (length (gnus-agent-cat-groups category))))
2621     (beginning-of-line)
2622     (gnus-add-text-properties
2623      (point)
2624      (prog1 (1+ (point))
2625        ;; Insert the text.
2626        (eval gnus-category-line-format-spec))
2627      (list 'gnus-category gnus-tmp-name))))
2628
2629 (defun gnus-enter-category-buffer ()
2630   "Go to the Category buffer."
2631   (interactive)
2632   (gnus-category-setup-buffer)
2633   (gnus-configure-windows 'category)
2634   (gnus-category-prepare))
2635
2636 (defun gnus-category-setup-buffer ()
2637   (unless (get-buffer gnus-category-buffer)
2638     (save-excursion
2639       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
2640       (gnus-category-mode))))
2641
2642 (defun gnus-category-prepare ()
2643   (gnus-set-format 'category-mode)
2644   (gnus-set-format 'category t)
2645   (let ((alist gnus-category-alist)
2646         (buffer-read-only nil))
2647     (erase-buffer)
2648     (while alist
2649       (gnus-category-insert-line (pop alist)))
2650     (goto-char (point-min))
2651     (gnus-category-position-point)))
2652
2653 (defun gnus-category-name ()
2654   (or (intern (get-text-property (point-at-bol) 'gnus-category))
2655       (error "No category on the current line")))
2656
2657 (defun gnus-category-read ()
2658   "Read the category alist."
2659   (setq gnus-category-alist
2660         (or
2661          (with-temp-buffer
2662            (ignore-errors
2663             (nnheader-insert-file-contents (nnheader-concat gnus-agent-directory "lib/categories"))
2664             (goto-char (point-min))
2665             ;; This code isn't temp, it will be needed so long as
2666             ;; anyone may be migrating from an older version.
2667
2668             ;; Once we're certain that people will not revert to an
2669             ;; earlier version, we can take out the old-list code in
2670             ;; gnus-category-write.
2671             (let* ((old-list (read (current-buffer)))
2672                    (new-list (ignore-errors (read (current-buffer)))))
2673               (if new-list
2674                   new-list
2675                 ;; Convert from a positional list to an alist.
2676                 (mapcar
2677                  (lambda (c)
2678                    (setcdr c
2679                            (delq nil
2680                                  (gnus-mapcar
2681                                   (lambda (valu symb)
2682                                     (if valu
2683                                         (cons symb valu)))
2684                                   (cdr c)
2685                                   '(agent-predicate agent-score-file agent-groups))))
2686                    c)
2687                  old-list)))))
2688          (list (gnus-agent-cat-make 'default 'short)))))
2689
2690 (defun gnus-category-write ()
2691   "Write the category alist."
2692   (setq gnus-category-predicate-cache nil
2693         gnus-category-group-cache nil)
2694   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
2695   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
2696     ;; This prin1 is temporary.  It exists so that people can revert
2697     ;; to an earlier version of gnus-agent.
2698     (prin1 (mapcar (lambda (c)
2699               (list (car c)
2700                     (cdr (assoc 'agent-predicate c))
2701                     (cdr (assoc 'agent-score-file c))
2702                     (cdr (assoc 'agent-groups c))))
2703                    gnus-category-alist)
2704            (current-buffer))
2705     (newline)
2706     (prin1 gnus-category-alist (current-buffer))))
2707
2708 (defun gnus-category-edit-predicate (category)
2709   "Edit the predicate for CATEGORY."
2710   (interactive (list (gnus-category-name)))
2711   (let ((info (assq category gnus-category-alist)))
2712     (gnus-edit-form
2713      (gnus-agent-cat-predicate info)
2714      (format "Editing the select predicate for category %s" category)
2715      `(lambda (predicate)
2716         ;; Avoid run-time execution of setf form
2717         ;; (setf (gnus-agent-cat-predicate (assq ',category gnus-category-alist))
2718         ;;       predicate)
2719         ;; use its expansion instead:
2720         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2721                                      'agent-predicate predicate)
2722
2723         (gnus-category-write)
2724         (gnus-category-list)))))
2725
2726 (defun gnus-category-edit-score (category)
2727   "Edit the score expression for CATEGORY."
2728   (interactive (list (gnus-category-name)))
2729   (let ((info (assq category gnus-category-alist)))
2730     (gnus-edit-form
2731      (gnus-agent-cat-score-file info)
2732      (format "Editing the score expression for category %s" category)
2733      `(lambda (score-file)
2734         ;; Avoid run-time execution of setf form
2735         ;; (setf (gnus-agent-cat-score-file (assq ',category gnus-category-alist))
2736         ;;       score-file)
2737         ;; use its expansion instead:
2738         (gnus-agent-cat-set-property (assq ',category gnus-category-alist)
2739                                      'agent-score-file score-file)
2740
2741         (gnus-category-write)
2742         (gnus-category-list)))))
2743
2744 (defun gnus-category-edit-groups (category)
2745   "Edit the group list for CATEGORY."
2746   (interactive (list (gnus-category-name)))
2747   (let ((info (assq category gnus-category-alist)))
2748     (gnus-edit-form
2749      (gnus-agent-cat-groups info)
2750      (format "Editing the group list for category %s" category)
2751      `(lambda (groups)
2752         ;; Avoid run-time execution of setf form
2753         ;; (setf (gnus-agent-cat-groups (assq ',category gnus-category-alist))
2754         ;;       groups)
2755         ;; use its expansion instead:
2756         (gnus-agent-set-cat-groups (assq ',category gnus-category-alist)
2757                                    groups)
2758
2759         (gnus-category-write)
2760         (gnus-category-list)))))
2761
2762 (defun gnus-category-kill (category)
2763   "Kill the current category."
2764   (interactive (list (gnus-category-name)))
2765   (let ((info (assq category gnus-category-alist))
2766         (buffer-read-only nil))
2767     (gnus-delete-line)
2768     (setq gnus-category-alist (delq info gnus-category-alist))
2769     (gnus-category-write)))
2770
2771 (defun gnus-category-copy (category to)
2772   "Copy the current category."
2773   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
2774   (let ((info (assq category gnus-category-alist)))
2775     (push (let ((newcat (gnus-copy-sequence info)))
2776             (setf (gnus-agent-cat-name newcat) to)
2777             (setf (gnus-agent-cat-groups newcat) nil)
2778             newcat)
2779           gnus-category-alist)
2780     (gnus-category-write)
2781     (gnus-category-list)))
2782
2783 (defun gnus-category-add (category)
2784   "Create a new category."
2785   (interactive "SCategory name: ")
2786   (when (assq category gnus-category-alist)
2787     (error "Category %s already exists" category))
2788   (push (gnus-agent-cat-make category)
2789         gnus-category-alist)
2790   (gnus-category-write)
2791   (gnus-category-list))
2792
2793 (defun gnus-category-list ()
2794   "List all categories."
2795   (interactive)
2796   (gnus-category-prepare))
2797
2798 (defun gnus-category-exit ()
2799   "Return to the group buffer."
2800   (interactive)
2801   (kill-buffer (current-buffer))
2802   (gnus-configure-windows 'group t))
2803
2804 ;; To avoid having 8-bit characters in the source file.
2805 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
2806
2807 (defvar gnus-category-predicate-alist
2808   '((spam . gnus-agent-spam-p)
2809     (short . gnus-agent-short-p)
2810     (long . gnus-agent-long-p)
2811     (low . gnus-agent-low-scored-p)
2812     (high . gnus-agent-high-scored-p)
2813     (read . gnus-agent-read-p)
2814     (true . gnus-agent-true)
2815     (false . gnus-agent-false))
2816   "Mapping from short score predicate symbols to predicate functions.")
2817
2818 (defun gnus-agent-spam-p ()
2819   "Say whether an article is spam or not."
2820   (unless gnus-agent-spam-hashtb
2821     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
2822   (if (not (equal (mail-header-references gnus-headers) ""))
2823       nil
2824     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
2825       (prog1
2826           (gnus-gethash string gnus-agent-spam-hashtb)
2827         (gnus-sethash string t gnus-agent-spam-hashtb)))))
2828
2829 (defun gnus-agent-short-p ()
2830   "Say whether an article is short or not."
2831   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
2832
2833 (defun gnus-agent-long-p ()
2834   "Say whether an article is long or not."
2835   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
2836
2837 (defun gnus-agent-low-scored-p ()
2838   "Say whether an article has a low score or not."
2839   (< gnus-score gnus-agent-low-score))
2840
2841 (defun gnus-agent-high-scored-p ()
2842   "Say whether an article has a high score or not."
2843   (> gnus-score gnus-agent-high-score))
2844
2845 (defun gnus-agent-read-p ()
2846   "Say whether an article is read or not."
2847   (gnus-member-of-range (mail-header-number gnus-headers)
2848                         (gnus-info-read (gnus-get-info gnus-newsgroup-name))))
2849
2850 (defun gnus-category-make-function (predicate)
2851   "Make a function from PREDICATE."
2852   (let ((func (gnus-category-make-function-1 predicate)))
2853     (if (and (= (length func) 1)
2854              (symbolp (car func)))
2855         (car func)
2856       (gnus-byte-compile `(lambda () ,func)))))
2857
2858 (defun gnus-agent-true ()
2859   "Return t."
2860   t)
2861
2862 (defun gnus-agent-false ()
2863   "Return nil."
2864   nil)
2865
2866 (defun gnus-category-make-function-1 (predicate)
2867   "Make a function from PREDICATE."
2868   (cond
2869    ;; Functions are just returned as is.
2870    ((or (symbolp predicate)
2871         (functionp predicate))
2872     `(,(or (cdr (assq predicate gnus-category-predicate-alist))
2873            predicate)))
2874    ;; More complex predicate.
2875    ((consp predicate)
2876     `(,(cond
2877         ((memq (car predicate) '(& and))
2878          'and)
2879         ((memq (car predicate) '(| or))
2880          'or)
2881         ((memq (car predicate) gnus-category-not)
2882          'not))
2883       ,@(mapcar 'gnus-category-make-function-1 (cdr predicate))))
2884    (t
2885     (error "Unknown predicate type: %s" predicate))))
2886
2887 (defun gnus-get-predicate (predicate)
2888   "Return the function implementing PREDICATE."
2889   (or (cdr (assoc predicate gnus-category-predicate-cache))
2890       (let ((func (gnus-category-make-function predicate)))
2891         (setq gnus-category-predicate-cache
2892               (nconc gnus-category-predicate-cache
2893                      (list (cons predicate func))))
2894         func)))
2895
2896 (defun gnus-predicate-implies-unread (predicate)
2897   "Say whether PREDICATE implies unread articles only.
2898 It is okay to miss some cases, but there must be no false positives.
2899 That is, if this predicate returns true, then indeed the predicate must
2900 return only unread articles."
2901   (eq t (gnus-function-implies-unread-1
2902          (gnus-category-make-function-1 predicate))))
2903
2904 (defun gnus-function-implies-unread-1 (function)
2905   "Recursively evaluate a predicate function to determine whether it can select
2906 any read articles.  Returns t if the function is known to never
2907 return read articles, nil when it is known to always return read
2908 articles, and t_nil when the function may return both read and unread
2909 articles."
2910   (let ((func (car function))
2911         (args (mapcar 'gnus-function-implies-unread-1 (cdr function))))
2912     (cond ((eq func 'and)
2913            (cond ((memq t args) ; if any argument returns only unread articles
2914                   ;; then that argument constrains the result to only unread articles.
2915                   t)
2916                  ((memq 't_nil args) ; if any argument is indeterminate
2917                   ;; then the result is indeterminate
2918                   't_nil)))
2919           ((eq func 'or)
2920            (cond ((memq nil args) ; if any argument returns read articles
2921                   ;; then that argument ensures that the results includes read articles.
2922                   nil)
2923                  ((memq 't_nil args) ; if any argument is indeterminate
2924                   ;; then that argument ensures that the results are indeterminate
2925                   't_nil)
2926                  (t ; if all arguments return only unread articles
2927                   ;; then the result returns only unread articles
2928                   t)))
2929           ((eq func 'not)
2930            (cond ((eq (car args) 't_nil) ; if the argument is indeterminate
2931                   ; then the result is indeterminate
2932                   (car args))
2933                  (t ; otherwise
2934                   ; toggle the result to be the opposite of the argument
2935                   (not (car args)))))
2936           ((eq func 'gnus-agent-read-p)
2937            nil) ; The read predicate NEVER returns unread articles
2938           ((eq func 'gnus-agent-false)
2939            t) ; The false predicate returns t as the empty set excludes all read articles
2940           ((eq func 'gnus-agent-true)
2941            nil) ; The true predicate ALWAYS returns read articles
2942           ((catch 'found-match
2943              (let ((alist gnus-category-predicate-alist))
2944                (while alist
2945                  (if (eq func (cdar alist))
2946                      (throw 'found-match t)
2947                    (setq alist (cdr alist))))))
2948            't_nil) ; All other predicates return read and unread articles
2949           (t
2950            (error "Unknown predicate function: %s" function)))))
2951
2952 (defun gnus-group-category (group)
2953   "Return the category GROUP belongs to."
2954   (unless gnus-category-group-cache
2955     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
2956     (let ((cs gnus-category-alist)
2957           groups cat)
2958       (while (setq cat (pop cs))
2959         (setq groups (gnus-agent-cat-groups cat))
2960         (while groups
2961           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
2962   (or (gnus-gethash group gnus-category-group-cache)
2963       (assq 'default gnus-category-alist)))
2964
2965 (defun gnus-agent-expire-group (group &optional articles force)
2966   "Expire all old articles in GROUP.
2967 If you want to force expiring of certain articles, this function can
2968 take ARTICLES, and FORCE parameters as well.
2969
2970 The articles on which the expiration process runs are selected as follows:
2971   if ARTICLES is null, all read and unmarked articles.
2972   if ARTICLES is t, all articles.
2973   if ARTICLES is a list, just those articles.
2974 FORCE is equivalent to setting the expiration predicates to true."
2975   (interactive
2976    (list (let ((def (or (gnus-group-group-name)
2977                         gnus-newsgroup-name)))
2978            (let ((select (read-string (if def
2979                                           (concat "Group Name ("
2980                                                   def "): ")
2981                                         "Group Name: "))))
2982              (if (and (equal "" select)
2983                       def)
2984                  def
2985                select)))))
2986
2987   (if (not group)
2988       (gnus-agent-expire articles group force)
2989     (let ( ;; Bind gnus-agent-expire-stats to enable tracking of
2990           ;; expiration statistics of this single group
2991           (gnus-agent-expire-stats (list 0 0 0.0)))
2992       (if (or (not (eq articles t))
2993               (yes-or-no-p
2994                (concat "Are you sure that you want to "
2995                        "expire all articles in " group "? ")))
2996           (let ((gnus-command-method (gnus-find-method-for-group group))
2997                 (overview (gnus-get-buffer-create " *expire overview*"))
2998                 orig)
2999             (unwind-protect
3000                 (let ((active-file (gnus-agent-lib-file "active")))
3001                   (when (file-exists-p active-file)
3002                     (with-temp-buffer
3003                       (nnheader-insert-file-contents active-file)
3004                       (gnus-active-to-gnus-format
3005                        gnus-command-method
3006                        (setq orig (gnus-make-hashtable
3007                                    (count-lines (point-min) (point-max))))))
3008                     (save-excursion
3009                       (gnus-agent-expire-group-1
3010                        group overview (gnus-gethash-safe group orig)
3011                        articles force))))
3012               (kill-buffer overview))))
3013       (gnus-message 4 (gnus-agent-expire-done-message)))))
3014
3015 (defun gnus-agent-expire-group-1 (group overview active articles force)
3016   ;; Internal function - requires caller to have set
3017   ;; gnus-command-method, initialized overview buffer, and to have
3018   ;; provided a non-nil active
3019
3020   (let ((dir (gnus-agent-group-pathname group)))
3021     (gnus-agent-with-refreshed-group
3022      group
3023      (when (boundp 'gnus-agent-expire-current-dirs)
3024        (set 'gnus-agent-expire-current-dirs
3025             (cons dir
3026                   (symbol-value 'gnus-agent-expire-current-dirs))))
3027
3028      (if (and (not force)
3029               (eq 'DISABLE (gnus-agent-find-parameter group
3030                                                       'agent-enable-expiration)))
3031          (gnus-message 5 "Expiry skipping over %s" group)
3032        (gnus-message 5 "Expiring articles in %s" group)
3033        (gnus-agent-load-alist group)
3034        (let* ((bytes-freed 0)
3035               (size-files-deleted 0.0)
3036               (files-deleted 0)
3037               (nov-entries-deleted 0)
3038               (info (gnus-get-info group))
3039               (alist gnus-agent-article-alist)
3040               (day (- (time-to-days (current-time))
3041                       (gnus-agent-find-parameter group 'agent-days-until-old)))
3042               (specials (if (and alist
3043                                  (not force))
3044                             ;; This could be a bit of a problem.  I need to
3045                             ;; keep the last article to avoid refetching
3046                             ;; headers when using nntp in the backend.  At
3047                             ;; the same time, if someone uses a backend
3048                             ;; that supports article moving then I may have
3049                             ;; to remove the last article to complete the
3050                             ;; move.  Right now, I'm going to assume that
3051                             ;; FORCE overrides specials.
3052                             (list (caar (last alist)))))
3053               (unreads ;; Articles that are excluded from the
3054                ;; expiration process
3055                (cond (gnus-agent-expire-all
3056                       ;; All articles are marked read by global decree
3057                       nil)
3058                      ((eq articles t)
3059                       ;; All articles are marked read by function
3060                       ;; parameter
3061                       nil)
3062                      ((not articles)
3063                       ;; Unread articles are marked protected from
3064                       ;; expiration Don't call
3065                       ;; gnus-list-of-unread-articles as it returns
3066                       ;; articles that have not been fetched into the
3067                       ;; agent.
3068                       (ignore-errors
3069                         (gnus-agent-unread-articles group)))
3070                      (t
3071                       ;; All articles EXCEPT those named by the caller
3072                       ;; are protected from expiration
3073                       (gnus-sorted-difference
3074                        (gnus-uncompress-range
3075                         (cons (caar alist)
3076                               (caar (last alist))))
3077                        (sort articles '<)))))
3078               (marked ;; More articles that are excluded from the
3079                ;; expiration process
3080                (cond (gnus-agent-expire-all
3081                       ;; All articles are unmarked by global decree
3082                       nil)
3083                      ((eq articles t)
3084                       ;; All articles are unmarked by function
3085                       ;; parameter
3086                       nil)
3087                      (articles
3088                       ;; All articles may as well be unmarked as the
3089                       ;; unreads list already names the articles we are
3090                       ;; going to keep
3091                       nil)
3092                      (t
3093                       ;; Ticked and/or dormant articles are excluded
3094                       ;; from expiration
3095                       (nconc
3096                        (gnus-uncompress-range
3097                         (cdr (assq 'tick (gnus-info-marks info))))
3098                        (gnus-uncompress-range
3099                         (cdr (assq 'dormant
3100                                    (gnus-info-marks info))))))))
3101               (nov-file (concat dir ".overview"))
3102               (cnt 0)
3103               (completed -1)
3104               dlist
3105               type)
3106
3107          ;; The normal article alist contains elements that look like
3108          ;; (article# .  fetch_date) I need to combine other
3109          ;; information with this list.  For example, a flag indicating
3110          ;; that a particular article MUST BE KEPT.  To do this, I'm
3111          ;; going to transform the elements to look like (article#
3112          ;; fetch_date keep_flag NOV_entry_position) Later, I'll reverse
3113          ;; the process to generate the expired article alist.
3114
3115          ;; Convert the alist elements to (article# fetch_date nil
3116          ;; nil).
3117          (setq dlist (mapcar (lambda (e)
3118                                (list (car e) (cdr e) nil nil)) alist))
3119
3120          ;; Convert the keep lists to elements that look like (article#
3121          ;; nil keep_flag nil) then append it to the expanded dlist
3122          ;; These statements are sorted by ascending precidence of the
3123          ;; keep_flag.
3124          (setq dlist (nconc dlist
3125                             (mapcar (lambda (e)
3126                                       (list e nil 'unread  nil))
3127                                     unreads)))
3128          (setq dlist (nconc dlist
3129                             (mapcar (lambda (e)
3130                                       (list e nil 'marked  nil))
3131                                     marked)))
3132          (setq dlist (nconc dlist
3133                             (mapcar (lambda (e)
3134                                       (list e nil 'special nil))
3135                                     specials)))
3136
3137          (set-buffer overview)
3138          (erase-buffer)
3139          (buffer-disable-undo)
3140          (when (file-exists-p nov-file)
3141            (gnus-message 7 "gnus-agent-expire: Loading overview...")
3142            (nnheader-insert-file-contents nov-file)
3143            (goto-char (point-min))
3144         
3145            (let (p)
3146              (while (< (setq p (point)) (point-max))
3147                (condition-case nil
3148                    ;; If I successfully read an integer (the plus zero
3149                    ;; ensures a numeric type), append the position
3150                    ;; to the list
3151                    (push (list (+ 0 (read (current-buffer))) nil nil
3152                                p)
3153                          dlist)
3154                  (error
3155                   (gnus-message 1 "gnus-agent-expire: read error \
3156 occurred when reading expression at %s in %s.  Skipping to next \
3157 line." (point) nov-file)))
3158                ;; Whether I succeeded, or failed, it doesn't matter.
3159                ;; Move to the next line then try again.
3160                (forward-line 1)))
3161
3162            (gnus-message
3163             7 "gnus-agent-expire: Loading overview... Done"))
3164          (set-buffer-modified-p nil)
3165
3166          ;; At this point, all of the information is in dlist.  The
3167          ;; only problem is that much of it is spread across multiple
3168          ;; entries.  Sort then MERGE!!
3169          (gnus-message 7 "gnus-agent-expire: Sorting entries... ")
3170          ;; If two entries have the same article-number then sort by
3171          ;; ascending keep_flag.
3172          (let ((special 0)
3173                (marked 1)
3174                (unread 2))
3175            (setq dlist
3176                  (sort dlist
3177                        (lambda (a b)
3178                          (cond ((< (nth 0 a) (nth 0 b))
3179                                 t)
3180                                ((> (nth 0 a) (nth 0 b))
3181                                 nil)
3182                                (t
3183                                 (let ((a (or (symbol-value (nth 2 a))
3184                                              3))
3185                                       (b (or (symbol-value (nth 2 b))
3186                                              3)))
3187                                   (<= a b))))))))
3188          (gnus-message 7 "gnus-agent-expire: Sorting entries... Done")
3189          (gnus-message 7 "gnus-agent-expire: Merging entries... ")
3190          (let ((dlist dlist))
3191            (while (cdr dlist)           ; I'm not at the end-of-list
3192              (if (eq (caar dlist) (caadr dlist))
3193                  (let ((first (cdr (car dlist)))
3194                        (secnd (cdr (cadr dlist))))
3195                    (setcar first (or (car first)
3196                                      (car secnd))) ; fetch_date
3197                    (setq first (cdr first)
3198                          secnd (cdr secnd))
3199                    (setcar first (or (car first)
3200                                      (car secnd))) ; Keep_flag
3201                    (setq first (cdr first)
3202                          secnd (cdr secnd))
3203                    (setcar first (or (car first)
3204                                      (car secnd))) ; NOV_entry_position
3205
3206                    (setcdr dlist (cddr dlist)))
3207                (setq dlist (cdr dlist)))))
3208
3209          ;; Check the order of the entry positions.  They should be in
3210          ;; ascending order.  If they aren't, the positions must be
3211          ;; converted to markers.
3212          (when (let ((dlist dlist)
3213                      (prev-pos -1)
3214                      pos)
3215                  (while dlist
3216                    (if (setq pos (nth 3 (pop dlist)))
3217                        (if (< pos prev-pos)
3218                            (throw 'sort-results 'unsorted)
3219                          (setq prev-pos pos)))))
3220            (gnus-message 7 "gnus-agent-expire: Unsorted overview; inserting markers to compensate.")
3221            (mapcar (lambda (entry)
3222                      (let ((pos (nth 3 entry)))
3223                        (if pos
3224                            (setf (nth 3 entry)
3225                                  (set-marker (make-marker)
3226                                              pos)))))
3227                    dlist))
3228
3229          (gnus-message 7 "gnus-agent-expire: Merging entries... Done")
3230
3231          (let* ((len (float (length dlist)))
3232                 (alist (list nil))
3233                 (tail-alist alist)
3234                 (position-offset 0)
3235                 )
3236
3237            (while dlist
3238              (let ((new-completed (truncate (* 100.0
3239                                                (/ (setq cnt (1+ cnt))
3240                                                   len))))
3241                    message-log-max)
3242                (when (> new-completed completed)
3243                  (setq completed new-completed)
3244                  (gnus-message 7 "%3d%% completed..."  completed)))
3245              (let* ((entry          (car dlist))
3246                     (article-number (nth 0 entry))
3247                     (fetch-date     (nth 1 entry))
3248                     (keep           (nth 2 entry))
3249                     (marker         (nth 3 entry)))
3250
3251                (cond
3252                 ;; Kept articles are unread, marked, or special.
3253                 (keep
3254                  (gnus-agent-message 10
3255                                      "gnus-agent-expire: %s:%d: Kept %s article%s."
3256                                      group article-number keep (if fetch-date " and file" ""))
3257                  (when fetch-date
3258                    (unless (file-exists-p
3259                             (concat dir (number-to-string
3260                                          article-number)))
3261                      (setf (nth 1 entry) nil)
3262                      (gnus-agent-message 3 "gnus-agent-expire cleared \
3263 download flag on %s:%d as the cached article file is missing."
3264                                          group (caar dlist)))
3265                    (unless marker
3266                      (gnus-message 1 "gnus-agent-expire detected a \
3267 missing NOV entry.  Run gnus-agent-regenerate-group to restore it.")))
3268                  (gnus-agent-append-to-list
3269                   tail-alist
3270                   (cons article-number fetch-date)))
3271
3272                 ;; The following articles are READ, UNMARKED, and
3273                 ;; ORDINARY.  See if they can be EXPIRED!!!
3274                 ((setq type
3275                        (cond
3276                         ((not (integerp fetch-date))
3277                          'read) ;; never fetched article (may expire
3278                         ;; right now)
3279                         ((not (file-exists-p
3280                                (concat dir (number-to-string
3281                                             article-number))))
3282                          (setf (nth 1 entry) nil)
3283                          'externally-expired) ;; Can't find the cached
3284                         ;; article.  Handle case
3285                         ;; as though this article
3286                         ;; was never fetched.
3287
3288                         ;; We now have the arrival day, so we see
3289                         ;; whether it's old enough to be expired.
3290                         ((< fetch-date day)
3291                          'expired)
3292                         (force
3293                          'forced)))
3294
3295                  ;; I found some reason to expire this entry.
3296
3297                  (let ((actions nil))
3298                    (when (memq type '(forced expired))
3299                      (ignore-errors     ; Just being paranoid.
3300                        (let* ((file-name (nnheader-concat dir (number-to-string
3301                                                                article-number)))
3302                               (size (float (nth 7 (file-attributes file-name)))))
3303                          (incf bytes-freed size)
3304                          (incf size-files-deleted size)
3305                          (incf files-deleted)
3306                          (delete-file file-name))
3307                        (push "expired cached article" actions))
3308                      (setf (nth 1 entry) nil)
3309                      )
3310
3311                    (when marker
3312                      (push "NOV entry removed" actions)
3313
3314                      (goto-char (if (markerp marker)
3315                                     marker
3316                                   (- marker position-offset)))
3317
3318                      (incf nov-entries-deleted)
3319
3320                      (let* ((from (point-at-bol))
3321                             (to (progn (forward-line 1) (point)))
3322                             (freed (- to from)))
3323                        (incf bytes-freed freed)
3324                        (incf position-offset freed)
3325                        (delete-region from to)))
3326
3327                    ;; If considering all articles is set, I can only
3328                    ;; expire article IDs that are no longer in the
3329                    ;; active range (That is, articles that preceed the
3330                    ;; first article in the new alist).
3331                    (if (and gnus-agent-consider-all-articles
3332                             (>= article-number (car active)))
3333                        ;; I have to keep this ID in the alist
3334                        (gnus-agent-append-to-list
3335                         tail-alist (cons article-number fetch-date))
3336                      (push (format "Removed %s article number from \
3337 article alist" type) actions))
3338
3339                    (when actions
3340                      (gnus-agent-message 8 "gnus-agent-expire: %s:%d: %s"
3341                                          group article-number
3342                                          (mapconcat 'identity actions ", ")))))
3343                 (t
3344                  (gnus-agent-message
3345                   10 "gnus-agent-expire: %s:%d: Article kept as \
3346 expiration tests failed." group article-number)
3347                  (gnus-agent-append-to-list
3348                   tail-alist (cons article-number fetch-date)))
3349                 )
3350
3351                ;; Remove markers as I intend to reuse this buffer again.
3352                (when (and marker
3353                           (markerp marker))
3354                  (set-marker marker nil))
3355
3356                (setq dlist (cdr dlist))))
3357
3358            (setq alist (cdr alist))
3359
3360            (let ((inhibit-quit t))
3361              (unless (equal alist gnus-agent-article-alist)
3362                (setq gnus-agent-article-alist alist)
3363                (gnus-agent-save-alist group))
3364
3365              (when (buffer-modified-p)
3366                (gnus-make-directory dir)
3367                (write-region-as-coding-system gnus-agent-file-coding-system
3368                                               (point-min) (point-max) nov-file
3369                                               nil 'silent)
3370                ;; clear the modified flag as that I'm not confused by
3371                ;; its status on the next pass through this routine.
3372                (set-buffer-modified-p nil)
3373                (gnus-agent-update-view-total-fetched-for group t))
3374
3375              (when (eq articles t)
3376                (gnus-summary-update-info))))
3377
3378          (when (boundp 'gnus-agent-expire-stats)
3379            (let ((stats (symbol-value 'gnus-agent-expire-stats)))
3380              (incf (nth 2 stats) bytes-freed)
3381              (incf (nth 1 stats) files-deleted)
3382              (incf (nth 0 stats) nov-entries-deleted)))
3383
3384          (gnus-agent-update-files-total-fetched-for group (- size-files-deleted)))))))
3385
3386 (defun gnus-agent-expire (&optional articles group force)
3387   "Expire all old articles.
3388 If you want to force expiring of certain articles, this function can
3389 take ARTICLES, GROUP and FORCE parameters as well.
3390
3391 The articles on which the expiration process runs are selected as follows:
3392   if ARTICLES is null, all read and unmarked articles.
3393   if ARTICLES is t, all articles.
3394   if ARTICLES is a list, just those articles.
3395 Setting GROUP will limit expiration to that group.
3396 FORCE is equivalent to setting the expiration predicates to true."
3397   (interactive)
3398
3399   (if group
3400       (gnus-agent-expire-group group articles force)
3401     (if (or (not (eq articles t))
3402             (yes-or-no-p "Are you sure that you want to expire all \
3403 articles in every agentized group? "))
3404         (let ((methods (gnus-agent-covered-methods))
3405               ;; Bind gnus-agent-expire-current-dirs to enable tracking
3406               ;; of agent directories.
3407               (gnus-agent-expire-current-dirs nil)
3408               ;; Bind gnus-agent-expire-stats to enable tracking of
3409               ;; expiration statistics across all groups
3410               (gnus-agent-expire-stats (list 0 0 0.0))
3411               gnus-command-method overview orig)
3412           (setq overview (gnus-get-buffer-create " *expire overview*"))
3413           (unwind-protect
3414               (while (setq gnus-command-method (pop methods))
3415                 (let ((active-file (gnus-agent-lib-file "active")))
3416                   (when (file-exists-p active-file)
3417                     (with-temp-buffer
3418                       (nnheader-insert-file-contents active-file)
3419                       (gnus-active-to-gnus-format
3420                        gnus-command-method
3421                        (setq orig (gnus-make-hashtable
3422                                    (count-lines (point-min) (point-max))))))
3423                     (dolist (expiring-group (gnus-groups-from-server
3424                                              gnus-command-method))
3425                       (let* ((active
3426                               (gnus-gethash-safe expiring-group orig)))
3427
3428                         (when active
3429                           (save-excursion
3430                             (gnus-agent-expire-group-1
3431                              expiring-group overview active articles force))))))))
3432             (kill-buffer overview))
3433           (gnus-agent-expire-unagentized-dirs)
3434           (gnus-message 4 (gnus-agent-expire-done-message))))))
3435
3436 (defun gnus-agent-expire-done-message ()
3437   (if (and (> gnus-verbose 4)
3438            (boundp 'gnus-agent-expire-stats))
3439       (let* ((stats (symbol-value 'gnus-agent-expire-stats))
3440              (size (nth 2 stats))
3441             (units '(B KB MB GB)))
3442         (while (and (> size 1024.0)
3443                     (cdr units))
3444           (setq size (/ size 1024.0)
3445                 units (cdr units)))
3446
3447         (format "Expiry recovered %d NOV entries, deleted %d files,\
3448  and freed %f %s."
3449                 (nth 0 stats)
3450                 (nth 1 stats)
3451                 size (car units)))
3452     "Expiry...done"))
3453
3454 (defun gnus-agent-expire-unagentized-dirs ()
3455   (when (and gnus-agent-expire-unagentized-dirs
3456              (boundp 'gnus-agent-expire-current-dirs))
3457     (let* ((keep (gnus-make-hashtable))
3458            ;; Formally bind gnus-agent-expire-current-dirs so that the
3459            ;; compiler will not complain about free references.
3460            (gnus-agent-expire-current-dirs
3461             (symbol-value 'gnus-agent-expire-current-dirs))
3462            dir)
3463
3464       (gnus-sethash gnus-agent-directory t keep)
3465       (while gnus-agent-expire-current-dirs
3466         (setq dir (pop gnus-agent-expire-current-dirs))
3467         (when (and (stringp dir)
3468                    (file-directory-p dir))
3469           (while (not (gnus-gethash dir keep))
3470             (gnus-sethash dir t keep)
3471             (setq dir (file-name-directory (directory-file-name dir))))))
3472
3473       (let* (to-remove
3474              checker
3475              (checker
3476               (function
3477                (lambda (d)
3478                  "Given a directory, check it and its subdirectories for
3479               membership in the keep hash.  If it isn't found, add
3480               it to to-remove."
3481                  (let ((files (directory-files d))
3482                        file)
3483                    (while (setq file (pop files))
3484                      (cond ((equal file ".") ; Ignore self
3485                             nil)
3486                            ((equal file "..") ; Ignore parent
3487                             nil)
3488                            ((equal file ".overview")
3489                             ;; Directory must contain .overview to be
3490                             ;; agent's cache of a group.
3491                             (let ((d (file-name-as-directory d))
3492                                   r)
3493                               ;; Search ancestor's for last directory NOT
3494                               ;; found in keep hash.
3495                               (while (not (gnus-gethash
3496                                            (setq d (file-name-directory d)) keep))
3497                                 (setq r d
3498                                       d (directory-file-name d)))
3499                               ;; if ANY ancestor was NOT in keep hash and
3500                               ;; it it's already in to-remove, add it to
3501                               ;; to-remove.
3502                               (if (and r
3503                                        (not (member r to-remove)))
3504                                   (push r to-remove))))
3505                            ((file-directory-p (setq file (nnheader-concat d file)))
3506                             (funcall checker file)))))))))
3507         (funcall checker (expand-file-name gnus-agent-directory))
3508
3509         (when (and to-remove
3510                    (or gnus-expert-user
3511                        (gnus-y-or-n-p
3512                         "gnus-agent-expire has identified local directories that are\
3513  not currently required by any agentized group.  Do you wish to consider\
3514  deleting them?")))
3515           (while to-remove
3516             (let ((dir (pop to-remove)))
3517               (if (gnus-y-or-n-p (format "Delete %s? " dir))
3518                   (let* (delete-recursive
3519                          (delete-recursive
3520                           (function
3521                            (lambda (f-or-d)
3522                              (ignore-errors
3523                                (if (file-directory-p f-or-d)
3524                                    (condition-case nil
3525                                        (delete-directory f-or-d)
3526                                      (file-error
3527                                       (mapcar (lambda (f)
3528                                                 (or (member f '("." ".."))
3529                                                     (funcall delete-recursive
3530                                                              (nnheader-concat
3531                                                               f-or-d f))))
3532                                               (directory-files f-or-d))
3533                                       (delete-directory f-or-d)))
3534                                  (delete-file f-or-d)))))))
3535                     (funcall delete-recursive dir))))))))))
3536
3537 ;;;###autoload
3538 (defun gnus-agent-batch ()
3539   "Start Gnus, send queue and fetch session."
3540   (interactive)
3541   (let ((init-file-user "")
3542         (gnus-always-read-dribble-file t))
3543     (gnus))
3544   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
3545     (gnus-group-send-queue)
3546     (gnus-agent-fetch-session)))
3547
3548 (defun gnus-agent-unread-articles (group)
3549   (let* ((read (gnus-info-read (gnus-get-info group)))
3550          (known (gnus-agent-load-alist group))
3551          (unread (list nil))
3552          (tail-unread unread))
3553     (while (and known read)
3554       (let ((candidate (car (pop known))))
3555         (while (let* ((range (car read))
3556                       (min   (if (numberp range) range (car range)))
3557                       (max   (if (numberp range) range (cdr range))))
3558                  (cond ((or (not min)
3559                             (< candidate min))
3560                         (gnus-agent-append-to-list tail-unread candidate)
3561                         nil)
3562                        ((> candidate max)
3563                         (setq read (cdr read))
3564                         ;; return t so that I always loop one more
3565                         ;; time.  If I just iterated off the end of
3566                         ;; read, min will become nil and the current
3567                         ;; candidate will be added to the unread list.
3568                         t))))))
3569     (while known
3570       (gnus-agent-append-to-list tail-unread (car (pop known))))
3571     (cdr unread)))
3572
3573 (defun gnus-agent-uncached-articles (articles group &optional cached-header)
3574   "Restrict ARTICLES to numbers already fetched.
3575 Returns a sublist of ARTICLES that excludes those article ids in GROUP
3576 that have already been fetched.
3577 If CACHED-HEADER is nil, articles are only excluded if the article itself
3578 has been fetched."
3579
3580   ;; Logically equivalent to: (gnus-sorted-difference articles (mapcar
3581   ;; 'car gnus-agent-article-alist))
3582
3583   ;; Functionally, I don't need to construct a temp list using mapcar.
3584
3585   (if (and (or gnus-agent-cache (not gnus-plugged))
3586            (gnus-agent-load-alist group))
3587     (let* ((ref gnus-agent-article-alist)
3588            (arts articles)
3589            (uncached (list nil))
3590            (tail-uncached uncached))
3591       (while (and ref arts)
3592         (let ((v1 (car arts))
3593               (v2 (caar ref)))
3594           (cond ((< v1 v2) ; v1 does not appear in the reference list
3595                  (gnus-agent-append-to-list tail-uncached v1)
3596                  (setq arts (cdr arts)))
3597                 ((= v1 v2)
3598                  (unless (or cached-header (cdar ref)) ; v1 is already cached
3599                    (gnus-agent-append-to-list tail-uncached v1))
3600                  (setq arts (cdr arts))
3601                  (setq ref (cdr ref)))
3602                 (t ; reference article (v2) preceeds the list being filtered
3603                  (setq ref (cdr ref))))))
3604       (while arts
3605         (gnus-agent-append-to-list tail-uncached (pop arts)))
3606       (cdr uncached))
3607     ;; if gnus-agent-load-alist fails, no articles are cached.
3608     articles))
3609
3610 (defun gnus-agent-retrieve-headers (articles group &optional fetch-old)
3611   (save-excursion
3612     (gnus-agent-create-buffer)
3613     (let ((gnus-decode-encoded-word-function 'identity)
3614           (file (gnus-agent-article-name ".overview" group))
3615           cached-articles uncached-articles)
3616       (gnus-make-directory (nnheader-translate-file-chars
3617                             (file-name-directory file) t))
3618
3619       ;; Populate temp buffer with known headers
3620       (when (file-exists-p file)
3621         (with-current-buffer gnus-agent-overview-buffer
3622           (erase-buffer)
3623           (let ((nnheader-file-coding-system
3624                  gnus-agent-file-coding-system))
3625             (nnheader-insert-nov-file file (car articles)))))
3626
3627       (if (setq uncached-articles (gnus-agent-uncached-articles articles group
3628                                                                 t))
3629           (progn
3630             ;; Populate nntp-server-buffer with uncached headers
3631             (set-buffer nntp-server-buffer)
3632             (erase-buffer)
3633             (cond ((not (eq 'nov (let (gnus-agent) ; Turn off agent
3634                                    (gnus-retrieve-headers
3635                                     uncached-articles group fetch-old))))
3636                    (nnvirtual-convert-headers))
3637                   ((eq 'nntp (car gnus-current-select-method))
3638                    ;; The author of gnus-get-newsgroup-headers-xover
3639                    ;; reports that the XOVER command is commonly
3640                    ;; unreliable. The problem is that recently
3641                    ;; posted articles may not be entered into the
3642                    ;; NOV database in time to respond to my XOVER
3643                    ;; query.
3644                    ;;
3645                    ;; I'm going to use his assumption that the NOV
3646                    ;; database is updated in order of ascending
3647                    ;; article ID.  Therefore, a response containing
3648                    ;; article ID N implies that all articles from 1
3649                    ;; to N-1 are up-to-date.  Therefore, missing
3650                    ;; articles in that range have expired.
3651
3652                    (set-buffer nntp-server-buffer)
3653                    (let* ((fetched-articles (list nil))
3654                           (tail-fetched-articles fetched-articles)
3655                           (min (cond ((numberp fetch-old)
3656                                       (max 1 (- (car articles) fetch-old)))
3657                                      (fetch-old
3658                                       1)
3659                                      (t
3660                                       (car articles))))
3661                           (max (car (last articles))))
3662
3663                      ;; Get the list of articles that were fetched
3664                      (goto-char (point-min))
3665                      (let ((pm (point-max))
3666                            art)
3667                        (while (< (point) pm)
3668                          (when (setq art (gnus-agent-read-article-number))
3669                            (gnus-agent-append-to-list tail-fetched-articles art))
3670                          (forward-line 1)))
3671
3672                      ;; Clip this list to the headers that will
3673                      ;; actually be returned
3674                      (setq fetched-articles (gnus-list-range-intersection
3675                                              (cdr fetched-articles)
3676                                              (cons min max)))
3677
3678                      ;; Clip the uncached articles list to exclude
3679                      ;; IDs after the last FETCHED header.  The
3680                      ;; excluded IDs may be fetchable using HEAD.
3681                      (if (car tail-fetched-articles)
3682                          (setq uncached-articles
3683                                (gnus-list-range-intersection
3684                                 uncached-articles
3685                                 (cons (car uncached-articles)
3686                                       (car tail-fetched-articles)))))
3687
3688                      ;; Create the list of articles that were
3689                      ;; "successfully" fetched.  Success, in this
3690                      ;; case, means that the ID should not be
3691                      ;; fetched again.  In the case of an expired
3692                      ;; article, the header will not be fetched.
3693                      (setq uncached-articles
3694                            (gnus-sorted-nunion fetched-articles
3695                                                uncached-articles))
3696                      )))
3697
3698             ;; Erase the temp buffer
3699             (set-buffer gnus-agent-overview-buffer)
3700             (erase-buffer)
3701
3702             ;; Copy the nntp-server-buffer to the temp buffer
3703             (set-buffer nntp-server-buffer)
3704             (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
3705
3706             ;; Merge the temp buffer with the known headers (found on
3707             ;; disk in FILE) into the nntp-server-buffer
3708             (when uncached-articles
3709               (gnus-agent-braid-nov group uncached-articles file))
3710
3711             ;; Save the new set of known headers to FILE
3712             (set-buffer nntp-server-buffer)
3713             (gnus-agent-check-overview-buffer)
3714             (write-region-as-coding-system
3715              gnus-agent-file-coding-system
3716              (point-min) (point-max) file nil 'silent)
3717
3718             (gnus-agent-update-view-total-fetched-for group t)
3719
3720             ;; Update the group's article alist to include the newly
3721             ;; fetched articles.
3722             (gnus-agent-load-alist group)
3723             (gnus-agent-save-alist group uncached-articles nil)
3724             )
3725
3726         ;; Copy the temp buffer to the nntp-server-buffer
3727         (set-buffer nntp-server-buffer)
3728         (erase-buffer)
3729         (insert-buffer-substring gnus-agent-overview-buffer)))
3730
3731     (if (and fetch-old
3732              (not (numberp fetch-old)))
3733         t                               ; Don't remove anything.
3734       (nnheader-nov-delete-outside-range
3735        (if fetch-old (max 1 (- (car articles) fetch-old))
3736          (car articles))
3737        (car (last articles)))
3738       t)
3739
3740     'nov))
3741
3742 (defun gnus-agent-request-article (article group)
3743   "Retrieve ARTICLE in GROUP from the agent cache."
3744   (when (and gnus-agent
3745              (or gnus-agent-cache
3746                  (not gnus-plugged))
3747              (numberp article))
3748     (let* ((gnus-command-method (gnus-find-method-for-group group))
3749            (file (gnus-agent-article-name (number-to-string article) group))
3750            (buffer-read-only nil))
3751       (when (and (file-exists-p file)
3752                  (> (nth 7 (file-attributes file)) 0))
3753         (erase-buffer)
3754         (gnus-kill-all-overlays)
3755         (insert-file-contents-as-coding-system gnus-cache-coding-system file)
3756         t))))
3757
3758 (defun gnus-agent-regenerate-group (group &optional reread)
3759   "Regenerate GROUP.
3760 If REREAD is t, all articles in the .overview are marked as unread.
3761 If REREAD is a list, the specified articles will be marked as unread.
3762 In addition, their NOV entries in .overview will be refreshed using
3763 the articles' current headers.
3764 If REREAD is not nil, downloaded articles are marked as unread."
3765   (interactive
3766    (list (let ((def (or (gnus-group-group-name)
3767                         gnus-newsgroup-name)))
3768            (let ((select (read-string (if def
3769                                           (concat "Group Name ("
3770                                                   def "): ")
3771                                         "Group Name: "))))
3772              (if (and (equal "" select)
3773                       def)
3774                  def
3775                select)))
3776          (catch 'mark
3777            (while (let (c
3778                         (cursor-in-echo-area t)
3779                         (echo-keystrokes 0))
3780                     (message "Mark as unread: (n)one / (a)ll / all (d)ownloaded articles? (n) ")
3781                     (setq c (read-char-exclusive))
3782
3783                     (cond ((or (eq c ?\r) (eq c ?n) (eq c ?N))
3784                            (throw 'mark nil))
3785                           ((or (eq c ?a) (eq c ?A))
3786                            (throw 'mark t))
3787                           ((or (eq c ?d) (eq c ?D))
3788                            (throw 'mark 'some)))
3789                     (gnus-message 3 "Ignoring unexpected input")
3790                     (sit-for 1)
3791                     t)))))
3792   (when group
3793     (gnus-message 5 "Regenerating in %s" group)
3794     (let* ((gnus-command-method (or gnus-command-method
3795                                     (gnus-find-method-for-group group)))
3796            (file (gnus-agent-article-name ".overview" group))
3797            (dir (file-name-directory file))
3798            point
3799            (downloaded (if (file-exists-p dir)
3800                            (sort (mapcar (lambda (name) (string-to-number name))
3801                                          (directory-files dir nil "^[0-9]+$" t))
3802                                  '>)
3803                          (progn (gnus-make-directory dir) nil)))
3804            dl nov-arts
3805            alist header
3806            regenerated)
3807
3808       (mm-with-unibyte-buffer
3809         (if (file-exists-p file)
3810             (let ((nnheader-file-coding-system
3811                    gnus-agent-file-coding-system))
3812               (nnheader-insert-file-contents file)))
3813         (set-buffer-modified-p nil)
3814
3815         ;; Load the article IDs found in the overview file.  As a
3816         ;; side-effect, validate the file contents.
3817         (let ((load t))
3818           (while load
3819             (setq load nil)
3820             (goto-char (point-min))
3821             (while (< (point) (point-max))
3822               (cond ((and (looking-at "[0-9]+\t")
3823                           (<= (- (match-end 0) (match-beginning 0)) 9))
3824                      (push (read (current-buffer)) nov-arts)
3825                      (forward-line 1)
3826                      (let ((l1 (car nov-arts))
3827                            (l2 (cadr nov-arts)))
3828                        (cond ((and (listp reread) (memq l1 reread))
3829                               (gnus-delete-line)
3830                               (setq nov-arts (cdr nov-arts))
3831                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3832  entry of article %s deleted." l1))
3833                              ((not l2)
3834                               nil)
3835                              ((< l1 l2)
3836                               (gnus-message 3 "gnus-agent-regenerate-group: NOV\
3837  entries are NOT in ascending order.")
3838                               ;; Don't sort now as I haven't verified
3839                               ;; that every line begins with a number
3840                               (setq load t))
3841                              ((= l1 l2)
3842                               (forward-line -1)
3843                               (gnus-message 4 "gnus-agent-regenerate-group: NOV\
3844  entries contained duplicate of article %s.      Duplicate deleted." l1)
3845                               (gnus-delete-line)
3846                               (setq nov-arts (cdr nov-arts))))))
3847                     (t
3848                      (gnus-message 1 "gnus-agent-regenerate-group: NOV\
3849  entries contained line that did not begin with an article number.  Deleted\
3850  line.")
3851                      (gnus-delete-line))))
3852             (when load
3853               (gnus-message 5 "gnus-agent-regenerate-group: Sorting NOV\
3854  entries into ascending order.")
3855               (sort-numeric-fields 1 (point-min) (point-max))
3856               (setq nov-arts nil))))
3857         (gnus-agent-check-overview-buffer)
3858
3859         ;; Construct a new article alist whose nodes match every header
3860         ;; in the .overview file.  As a side-effect, missing headers are
3861         ;; reconstructed from the downloaded article file.
3862         (while (or downloaded nov-arts)
3863           (cond ((and downloaded
3864                       (or (not nov-arts)
3865                           (> (car downloaded) (car nov-arts))))
3866                  ;; This entry is missing from the overview file
3867                  (gnus-message 3 "Regenerating NOV %s %d..." group
3868                                (car downloaded))
3869                  (let ((file (concat dir (number-to-string (car downloaded)))))
3870                    (mm-with-unibyte-buffer
3871                      (nnheader-insert-file-contents file)
3872                      (nnheader-remove-body)
3873                      (setq header (nnheader-parse-naked-head)))
3874                    (mail-header-set-number header (car downloaded))
3875                    (if nov-arts
3876                        (let ((key (concat "^" (int-to-string (car nov-arts))
3877                                           "\t")))
3878                          (or (re-search-backward key nil t)
3879                              (re-search-forward key))
3880                          (forward-line 1))
3881                      (goto-char (point-min)))
3882                    (nnheader-insert-nov header))
3883                  (setq nov-arts (cons (car downloaded) nov-arts)))
3884                 ((eq (car downloaded) (car nov-arts))
3885                  ;; This entry in the overview has been downloaded
3886                  (push (cons (car downloaded)
3887                              (time-to-days
3888                               (nth 5 (file-attributes
3889                                       (concat dir (number-to-string
3890                                                    (car downloaded))))))) alist)
3891                  (setq downloaded (cdr downloaded))
3892                  (setq nov-arts (cdr nov-arts)))
3893                 (t
3894                  ;; This entry in the overview has not been downloaded
3895                  (push (cons (car nov-arts) nil) alist)
3896                  (setq nov-arts (cdr nov-arts)))))
3897
3898         ;; When gnus-agent-consider-all-articles is set,
3899         ;; gnus-agent-regenerate-group should NOT remove article IDs from
3900         ;; the alist.  Those IDs serve as markers to indicate that an
3901         ;; attempt has been made to fetch that article's header.
3902
3903         ;; When gnus-agent-consider-all-articles is NOT set,
3904         ;; gnus-agent-regenerate-group can remove the article ID of every
3905         ;; article (with the exception of the last ID in the list - it's
3906         ;; special) that no longer appears in the overview.  In this
3907         ;; situtation, the last article ID in the list implies that it,
3908         ;; and every article ID preceeding it, have been fetched from the
3909         ;; server.
3910
3911         (if gnus-agent-consider-all-articles
3912             ;; Restore all article IDs that were not found in the overview file.
3913             (let* ((n (cons nil alist))
3914                    (merged n)
3915                    (o (gnus-agent-load-alist group)))
3916               (while o
3917                 (let ((nID (caadr n))
3918                       (oID (caar o)))
3919                   (cond ((not nID)
3920                          (setq n (setcdr n (list (list oID))))
3921                          (setq o (cdr o)))
3922                         ((< oID nID)
3923                          (setcdr n (cons (list oID) (cdr n)))
3924                          (setq o (cdr o)))
3925                         ((= oID nID)
3926                          (setq o (cdr o))
3927                          (setq n (cdr n)))
3928                         (t
3929                          (setq n (cdr n))))))
3930               (setq alist (cdr merged)))
3931           ;; Restore the last article ID if it is not already in the new alist
3932           (let ((n (last alist))
3933                 (o (last (gnus-agent-load-alist group))))
3934             (cond ((not o)
3935                    nil)
3936                   ((not n)
3937                    (push (cons (caar o) nil) alist))
3938                   ((< (caar n) (caar o))
3939                    (setcdr n (list (car o)))))))
3940
3941         (let ((inhibit-quit t))
3942           (if (setq regenerated (buffer-modified-p))
3943               (write-region-as-coding-system
3944                gnus-agent-file-coding-system
3945                (point-min) (point-max) file nil 'silent))
3946
3947           (setq regenerated (or regenerated
3948                                 (and reread gnus-agent-article-alist)
3949                                 (not (equal alist gnus-agent-article-alist))))
3950
3951           (setq gnus-agent-article-alist alist)
3952
3953           (when regenerated
3954             (gnus-agent-save-alist group)
3955
3956             ;; I have to alter the group's active range NOW as
3957             ;; gnus-make-ascending-articles-unread will use it to
3958             ;; recalculate the number of unread articles in the group
3959
3960             (let ((group (gnus-group-real-name group))
3961                   (group-active (or (gnus-active group)
3962                                     (gnus-activate-group group))))
3963               (gnus-agent-possibly-alter-active group group-active)))))
3964
3965       (when (and reread gnus-agent-article-alist)
3966         (gnus-agent-synchronize-group-flags 
3967          group 
3968          (list (list
3969                 (if (listp reread)
3970                     reread
3971                   (delq nil (mapcar (function (lambda (c)
3972                                                 (cond ((eq reread t)
3973                                                        (car c))
3974                                                       ((cdr c)
3975                                                        (car c)))))
3976                                     gnus-agent-article-alist)))
3977                 'del '(read)))
3978          gnus-command-method)
3979
3980         (when regenerated
3981           (gnus-agent-update-files-total-fetched-for group nil)))
3982
3983       (gnus-message 5 "")
3984       regenerated)))
3985
3986 ;;;###autoload
3987 (defun gnus-agent-regenerate (&optional clean reread)
3988   "Regenerate all agent covered files.
3989 If CLEAN, obsolete (ignore)."
3990   (interactive "P")
3991   (let (regenerated)
3992     (gnus-message 4 "Regenerating Gnus agent files...")
3993     (dolist (gnus-command-method (gnus-agent-covered-methods))
3994         (dolist (group (gnus-groups-from-server gnus-command-method))
3995           (setq regenerated (or (gnus-agent-regenerate-group group reread)
3996                                 regenerated))))
3997     (gnus-message 4 "Regenerating Gnus agent files...done")
3998
3999     regenerated))
4000
4001 (defun gnus-agent-go-online (&optional force)
4002   "Switch servers into online status."
4003   (interactive (list t))
4004   (dolist (server gnus-opened-servers)
4005     (when (eq (nth 1 server) 'offline)
4006       (if (if (eq force 'ask)
4007               (gnus-y-or-n-p
4008                (format "Switch %s:%s into online status? "
4009                        (caar server) (cadar server)))
4010             force)
4011           (setcar (nthcdr 1 server) 'close)))))
4012
4013 (defun gnus-agent-toggle-group-plugged (group)
4014   "Toggle the status of the server of the current group."
4015   (interactive (list (gnus-group-group-name)))
4016   (let* ((method (gnus-find-method-for-group group))
4017          (status (cadr (assoc method gnus-opened-servers))))
4018     (if (eq status 'offline)
4019         (gnus-server-set-status method 'closed)
4020       (gnus-close-server method)
4021       (gnus-server-set-status method 'offline))
4022     (message "Turn %s:%s from %s to %s." (car method) (cadr method)
4023              (if (eq status 'offline) 'offline 'online)
4024              (if (eq status 'offline) 'online 'offline))))
4025
4026 (defun gnus-agent-group-covered-p (group)
4027   (gnus-agent-method-p (gnus-group-method group)))
4028
4029 ;; Added to support XEmacs
4030 (eval-and-compile
4031   (unless (fboundp 'directory-files-and-attributes)
4032     (defun directory-files-and-attributes (directory
4033                                            &optional full match nosort)
4034       (let (result)
4035         (dolist (file (directory-files directory full match nosort))
4036           (push (cons file (file-attributes file)) result))
4037         (nreverse result)))))
4038
4039 (defun gnus-agent-update-files-total-fetched-for
4040   (group delta &optional method path)
4041   "Update, or set, the total disk space used by the articles that the
4042 agent has fetched."
4043   (when gnus-agent-total-fetched-hashtb
4044     (gnus-agent-with-refreshed-group
4045      group
4046      ;; if null, gnus-agent-group-pathname will calc method.
4047      (let* ((gnus-command-method method)
4048             (path (or path (gnus-agent-group-pathname group)))
4049             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4050                        (gnus-sethash path (make-list 3 0)
4051                                      gnus-agent-total-fetched-hashtb))))
4052        (when (listp delta)
4053          (if delta
4054              (let ((sum 0.0)
4055                    file)
4056                (while (setq file (pop delta))
4057                  (incf sum (float (or (nth 7 (file-attributes
4058                                               (nnheader-concat
4059                                                path
4060                                                (if (numberp file)
4061                                                    (number-to-string file)
4062                                                  file)))) 0))))
4063                (setq delta sum))
4064            (let ((sum (- (nth 2 entry)))
4065                  (info (directory-files-and-attributes path nil "^-?[0-9]+$" t))
4066                  file)
4067              (while (setq file (pop info))
4068                (incf sum (float (or (nth 8 file) 0))))
4069              (setq delta sum))))
4070
4071        (setq gnus-agent-need-update-total-fetched-for t)
4072        (incf (nth 2 entry) delta)))))
4073
4074 (defun gnus-agent-update-view-total-fetched-for
4075   (group agent-over &optional method path)
4076   "Update, or set, the total disk space used by the .agentview and
4077 .overview files.  These files are calculated separately as they can be
4078 modified."
4079   (when gnus-agent-total-fetched-hashtb
4080     (gnus-agent-with-refreshed-group
4081      group
4082      ;; if null, gnus-agent-group-pathname will calc method.
4083      (let* ((gnus-command-method method)
4084             (path (or path (gnus-agent-group-pathname group)))
4085             (entry (or (gnus-gethash path gnus-agent-total-fetched-hashtb)
4086                        (gnus-sethash path (make-list 3 0)
4087                                      gnus-agent-total-fetched-hashtb)))
4088             (size (or (nth 7 (file-attributes
4089                               (nnheader-concat
4090                                path (if agent-over
4091                                         ".overview"
4092                                       ".agentview"))))
4093                       0)))
4094        (setq gnus-agent-need-update-total-fetched-for t)
4095        (setf (nth (if agent-over 1 0) entry) size)))))
4096
4097 (defun gnus-agent-total-fetched-for (group &optional method no-inhibit)
4098   "Get the total disk space used by the specified GROUP."
4099   (unless gnus-agent-total-fetched-hashtb
4100     (setq gnus-agent-total-fetched-hashtb (gnus-make-hashtable 1024)))
4101
4102   ;; if null, gnus-agent-group-pathname will calc method.
4103   (let* ((gnus-command-method method)
4104          (path (gnus-agent-group-pathname group))
4105          (entry (gnus-gethash path gnus-agent-total-fetched-hashtb)))
4106     (if entry
4107         (apply '+ entry)
4108       (let ((gnus-agent-inhibit-update-total-fetched-for (not no-inhibit)))
4109         (+
4110          (gnus-agent-update-view-total-fetched-for  group nil method path)
4111          (gnus-agent-update-view-total-fetched-for  group t   method path)
4112          (gnus-agent-update-files-total-fetched-for group nil method path))))))
4113
4114 (provide 'gnus-agent)
4115
4116 ;;; gnus-agent.el ends here