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