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