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