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