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