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