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