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