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