Fixes for XEmacs
[gnus] / lisp / gnus-agent.el
1 ;;; gnus-agent.el --- unplugged support for Gnus
2 ;; Copyright (C) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
10 ;; any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
21
22 ;;; Commentary:
23
24 ;;; Code:
25
26 (require 'gnus)
27 (require 'gnus-cache)
28 (require 'nnvirtual)
29 (require 'gnus-sum)
30 (require 'gnus-score)
31 (eval-when-compile
32   (if (featurep 'xemacs)
33       (require 'itimer)
34     (require 'timer))
35   (require 'cl))
36
37 (defcustom gnus-agent-directory (nnheader-concat gnus-directory "agent/")
38   "Where the Gnus agent will store its files."
39   :group 'gnus-agent
40   :type 'directory)
41
42 (defcustom gnus-agent-plugged-hook nil
43   "Hook run when plugging into the network."
44   :group 'gnus-agent
45   :type 'hook)
46
47 (defcustom gnus-agent-unplugged-hook nil
48   "Hook run when unplugging from the network."
49   :group 'gnus-agent
50   :type 'hook)
51
52 (defcustom gnus-agent-handle-level gnus-level-subscribed
53   "Groups on levels higher than this variable will be ignored by the Agent."
54   :group 'gnus-agent
55   :type 'integer)
56
57 (defcustom gnus-agent-expire-days 7
58   "Read articles older than this will be expired."
59   :group 'gnus-agent
60   :type 'integer)
61
62 (defcustom gnus-agent-expire-all nil
63   "If non-nil, also expire unread, ticked and dormant articles.
64 If nil, only read articles will be expired."
65   :group 'gnus-agent
66   :type 'boolean)
67
68 (defcustom gnus-agent-group-mode-hook nil
69   "Hook run in Agent group minor modes."
70   :group 'gnus-agent
71   :type 'hook)
72
73 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
74 (when (featurep 'xemacs)
75   (add-hook 'gnus-agent-group-mode-hook 'gnus-xmas-agent-group-menu-add))
76
77 (defcustom gnus-agent-summary-mode-hook nil
78   "Hook run in Agent summary minor modes."
79   :group 'gnus-agent
80   :type 'hook)
81
82 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
83 (when (featurep 'xemacs)
84   (add-hook 'gnus-agent-summary-mode-hook 'gnus-xmas-agent-summary-menu-add))
85
86 (defcustom gnus-agent-server-mode-hook nil
87   "Hook run in Agent summary minor modes."
88   :group 'gnus-agent
89   :type 'hook)
90
91 ;; Extracted from gnus-xmas-redefine in order to preserve user settings
92 (when (featurep 'xemacs)
93   (add-hook 'gnus-agent-server-mode-hook 'gnus-xmas-agent-server-menu-add))
94
95 (defcustom gnus-agent-confirmation-function 'y-or-n-p
96   "Function to confirm when error happens."
97   :version "21.1"
98   :group 'gnus-agent
99   :type 'function)
100
101 (defcustom gnus-agent-synchronize-flags 'ask
102   "Indicate if flags are synchronized when you plug in.
103 If this is `ask' the hook will query the user."
104   :version "21.1"
105   :type '(choice (const :tag "Always" t)
106                  (const :tag "Never" nil)
107                  (const :tag "Ask" ask))
108   :group 'gnus-agent)
109
110 ;;; Internal variables
111
112 (defvar gnus-agent-history-buffers nil)
113 (defvar gnus-agent-buffer-alist nil)
114 (defvar gnus-agent-article-alist nil)
115 (defvar gnus-agent-group-alist nil)
116 (defvar gnus-agent-covered-methods nil)
117 (defvar gnus-category-alist nil)
118 (defvar gnus-agent-current-history nil)
119 (defvar gnus-agent-overview-buffer nil)
120 (defvar gnus-category-predicate-cache nil)
121 (defvar gnus-category-group-cache nil)
122 (defvar gnus-agent-spam-hashtb nil)
123 (defvar gnus-agent-file-name nil)
124 (defvar gnus-agent-send-mail-function nil)
125 (defvar gnus-agent-file-coding-system 'raw-text)
126
127 ;; Dynamic variables
128 (defvar gnus-headers)
129 (defvar gnus-score)
130
131 ;;;
132 ;;; Setup
133 ;;;
134
135 (defun gnus-open-agent ()
136   (setq gnus-agent t)
137   (gnus-agent-read-servers)
138   (gnus-category-read)
139   (gnus-agent-create-buffer)
140   (add-hook 'gnus-group-mode-hook 'gnus-agent-mode)
141   (add-hook 'gnus-summary-mode-hook 'gnus-agent-mode)
142   (add-hook 'gnus-server-mode-hook 'gnus-agent-mode))
143
144 (defun gnus-agent-create-buffer ()
145   (if (gnus-buffer-live-p gnus-agent-overview-buffer)
146       t
147     (setq gnus-agent-overview-buffer
148           (gnus-get-buffer-create " *Gnus agent overview*"))
149     (with-current-buffer gnus-agent-overview-buffer
150       (mm-enable-multibyte))
151     nil))
152
153 (gnus-add-shutdown 'gnus-close-agent 'gnus)
154
155 (defun gnus-close-agent ()
156   (setq gnus-agent-covered-methods nil
157         gnus-category-predicate-cache nil
158         gnus-category-group-cache nil
159         gnus-agent-spam-hashtb nil)
160   (gnus-kill-buffer gnus-agent-overview-buffer))
161
162 ;;;
163 ;;; Utility functions
164 ;;;
165
166 (defun gnus-agent-read-file (file)
167   "Load FILE and do a `read' there."
168   (with-temp-buffer
169     (ignore-errors
170       (nnheader-insert-file-contents file)
171       (goto-char (point-min))
172       (read (current-buffer)))))
173
174 (defsubst gnus-agent-method ()
175   (concat (symbol-name (car gnus-command-method)) "/"
176           (if (equal (cadr gnus-command-method) "")
177               "unnamed"
178             (cadr gnus-command-method))))
179
180 (defsubst gnus-agent-directory ()
181   "Path of the Gnus agent directory."
182   (nnheader-concat gnus-agent-directory
183                    (nnheader-translate-file-chars (gnus-agent-method)) "/"))
184
185 (defun gnus-agent-lib-file (file)
186   "The full path of the Gnus agent library FILE."
187   (expand-file-name file
188                     (file-name-as-directory
189                      (expand-file-name "agent.lib" (gnus-agent-directory)))))
190
191 ;;; Fetching setup functions.
192
193 (defun gnus-agent-start-fetch ()
194   "Initialize data structures for efficient fetching."
195   (gnus-agent-open-history)
196   (setq gnus-agent-current-history (gnus-agent-history-buffer))
197   (gnus-agent-create-buffer))
198
199 (defun gnus-agent-stop-fetch ()
200   "Save all data structures and clean up."
201   (gnus-agent-save-history)
202   (gnus-agent-close-history)
203   (setq gnus-agent-spam-hashtb nil)
204   (save-excursion
205     (set-buffer nntp-server-buffer)
206     (widen)))
207
208 (defmacro gnus-agent-with-fetch (&rest forms)
209   "Do FORMS safely."
210   `(unwind-protect
211        (let ((gnus-agent-fetching t))
212          (gnus-agent-start-fetch)
213          ,@forms)
214      (gnus-agent-stop-fetch)))
215
216 (put 'gnus-agent-with-fetch 'lisp-indent-function 0)
217 (put 'gnus-agent-with-fetch 'edebug-form-spec '(body))
218
219 ;;;
220 ;;; Mode infestation
221 ;;;
222
223 (defvar gnus-agent-mode-hook nil
224   "Hook run when installing agent mode.")
225
226 (defvar gnus-agent-mode nil)
227 (defvar gnus-agent-mode-status '(gnus-agent-mode " Plugged"))
228
229 (defun gnus-agent-mode ()
230   "Minor mode for providing a agent support in Gnus buffers."
231   (let* ((buffer (progn (string-match "^gnus-\\(.*\\)-mode$"
232                                       (symbol-name major-mode))
233                         (match-string 1 (symbol-name major-mode))))
234          (mode (intern (format "gnus-agent-%s-mode" buffer))))
235     (set (make-local-variable 'gnus-agent-mode) t)
236     (set mode nil)
237     (set (make-local-variable mode) t)
238     ;; Set up the menu.
239     (when (gnus-visual-p 'agent-menu 'menu)
240       (funcall (intern (format "gnus-agent-%s-make-menu-bar" buffer))))
241     (unless (assq 'gnus-agent-mode minor-mode-alist)
242       (push gnus-agent-mode-status minor-mode-alist))
243     (unless (assq mode minor-mode-map-alist)
244       (push (cons mode (symbol-value (intern (format "gnus-agent-%s-mode-map"
245                                                      buffer))))
246             minor-mode-map-alist))
247     (when (eq major-mode 'gnus-group-mode)
248       (gnus-agent-toggle-plugged gnus-plugged))
249     (gnus-run-hooks 'gnus-agent-mode-hook
250                     (intern (format "gnus-agent-%s-mode-hook" buffer)))))
251
252 (defvar gnus-agent-group-mode-map (make-sparse-keymap))
253 (gnus-define-keys gnus-agent-group-mode-map
254   "Ju" gnus-agent-fetch-groups
255   "Jc" gnus-enter-category-buffer
256   "Jj" gnus-agent-toggle-plugged
257   "Js" gnus-agent-fetch-session
258   "JY" gnus-agent-synchronize-flags
259   "JS" gnus-group-send-drafts
260   "Ja" gnus-agent-add-group
261   "Jr" gnus-agent-remove-group)
262
263 (defun gnus-agent-group-make-menu-bar ()
264   (unless (boundp 'gnus-agent-group-menu)
265     (easy-menu-define
266      gnus-agent-group-menu gnus-agent-group-mode-map ""
267      '("Agent"
268        ["Toggle plugged" gnus-agent-toggle-plugged t]
269        ["List categories" gnus-enter-category-buffer t]
270        ["Send drafts" gnus-group-send-drafts gnus-plugged]
271        ("Fetch"
272         ["All" gnus-agent-fetch-session gnus-plugged]
273         ["Group" gnus-agent-fetch-group gnus-plugged])))))
274
275 (defvar gnus-agent-summary-mode-map (make-sparse-keymap))
276 (gnus-define-keys gnus-agent-summary-mode-map
277   "Jj" gnus-agent-toggle-plugged
278   "J#" gnus-agent-mark-article
279   "J\M-#" gnus-agent-unmark-article
280   "@" gnus-agent-toggle-mark
281   "Jc" gnus-agent-catchup)
282
283 (defun gnus-agent-summary-make-menu-bar ()
284   (unless (boundp 'gnus-agent-summary-menu)
285     (easy-menu-define
286      gnus-agent-summary-menu gnus-agent-summary-mode-map ""
287      '("Agent"
288        ["Toggle plugged" gnus-agent-toggle-plugged t]
289        ["Mark as downloadable" gnus-agent-mark-article t]
290        ["Unmark as downloadable" gnus-agent-unmark-article t]
291        ["Toggle mark" gnus-agent-toggle-mark t]
292        ["Catchup undownloaded" gnus-agent-catchup t]))))
293
294 (defvar gnus-agent-server-mode-map (make-sparse-keymap))
295 (gnus-define-keys gnus-agent-server-mode-map
296   "Jj" gnus-agent-toggle-plugged
297   "Ja" gnus-agent-add-server
298   "Jr" gnus-agent-remove-server)
299
300 (defun gnus-agent-server-make-menu-bar ()
301   (unless (boundp 'gnus-agent-server-menu)
302     (easy-menu-define
303      gnus-agent-server-menu gnus-agent-server-mode-map ""
304      '("Agent"
305        ["Toggle plugged" gnus-agent-toggle-plugged t]
306        ["Add" gnus-agent-add-server t]
307        ["Remove" gnus-agent-remove-server t]))))
308
309 (defun gnus-agent-toggle-plugged (plugged)
310   "Toggle whether Gnus is unplugged or not."
311   (interactive (list (not gnus-plugged)))
312   (if plugged
313       (progn
314         (setq gnus-plugged plugged)
315         (gnus-agent-possibly-synchronize-flags)
316         (gnus-run-hooks 'gnus-agent-plugged-hook)
317         (setcar (cdr gnus-agent-mode-status) " Plugged"))
318     (gnus-agent-close-connections)
319     (setq gnus-plugged plugged)
320     (gnus-run-hooks 'gnus-agent-unplugged-hook)
321     (setcar (cdr gnus-agent-mode-status) " Unplugged"))
322   (set-buffer-modified-p t))
323
324 (defun gnus-agent-close-connections ()
325   "Close all methods covered by the Gnus agent."
326   (let ((methods gnus-agent-covered-methods))
327     (while methods
328       (gnus-close-server (pop methods)))))
329
330 ;;;###autoload
331 (defun gnus-unplugged ()
332   "Start Gnus unplugged."
333   (interactive)
334   (setq gnus-plugged nil)
335   (gnus))
336
337 ;;;###autoload
338 (defun gnus-plugged ()
339   "Start Gnus plugged."
340   (interactive)
341   (setq gnus-plugged t)
342   (gnus))
343
344 ;;;###autoload
345 (defun gnus-agentize ()
346   "Allow Gnus to be an offline newsreader.
347 The normal usage of this command is to put the following as the
348 last form in your `.gnus.el' file:
349
350 \(gnus-agentize)
351
352 This will modify the `gnus-before-startup-hook', `gnus-post-method',
353 and `message-send-mail-function' variables, and install the Gnus
354 agent minor mode in all Gnus buffers."
355   (interactive)
356   (gnus-open-agent)
357   (add-hook 'gnus-setup-news-hook 'gnus-agent-queue-setup)
358   (unless gnus-agent-send-mail-function
359     (setq gnus-agent-send-mail-function message-send-mail-function
360           message-send-mail-function 'gnus-agent-send-mail))
361   (unless gnus-agent-covered-methods
362     (setq gnus-agent-covered-methods (list gnus-select-method))))
363
364 (defun gnus-agent-queue-setup ()
365   "Make sure the queue group exists."
366   (unless (gnus-gethash "nndraft:queue" gnus-newsrc-hashtb)
367     (gnus-request-create-group "queue" '(nndraft ""))
368     (let ((gnus-level-default-subscribed 1))
369       (gnus-subscribe-group "nndraft:queue" nil '(nndraft "")))
370     (gnus-group-set-parameter
371      "nndraft:queue" 'gnus-dummy '((gnus-draft-mode)))))
372
373 (defun gnus-agent-send-mail ()
374   (if gnus-plugged
375       (funcall gnus-agent-send-mail-function)
376     (goto-char (point-min))
377     (re-search-forward
378      (concat "^" (regexp-quote mail-header-separator) "\n"))
379     (replace-match "\n")
380     (gnus-agent-insert-meta-information 'mail)
381     (gnus-request-accept-article "nndraft:queue" nil t t)))
382
383 (defun gnus-agent-insert-meta-information (type &optional method)
384   "Insert meta-information into the message that says how it's to be posted.
385 TYPE can be either `mail' or `news'.  If the latter, then METHOD can
386 be a select method."
387   (save-excursion
388     (message-remove-header gnus-agent-meta-information-header)
389     (goto-char (point-min))
390     (insert gnus-agent-meta-information-header ": "
391             (symbol-name type) " " (format "%S" method)
392             "\n")
393     (forward-char -1)
394     (while (search-backward "\n" nil t)
395       (replace-match "\\n" t t))))
396
397 (defun gnus-agent-restore-gcc ()
398   "Restore GCC field from saved header."
399   (save-excursion
400     (goto-char (point-min))
401     (while (re-search-forward (concat gnus-agent-gcc-header ":") nil t)
402       (replace-match "Gcc:" 'fixedcase))))
403
404 (defun gnus-agent-any-covered-gcc ()
405   (save-restriction
406     (message-narrow-to-headers)
407     (let* ((gcc (mail-fetch-field "gcc" nil t))
408            (methods (and gcc
409                          (mapcar 'gnus-inews-group-method
410                                  (message-unquote-tokens
411                                   (message-tokenize-header
412                                    gcc " ,")))))
413            covered)
414       (while (and (not covered) methods)
415         (setq covered
416               (member (car methods) gnus-agent-covered-methods)
417               methods (cdr methods)))
418       covered)))
419
420 (defun gnus-agent-possibly-save-gcc ()
421   "Save GCC if Gnus is unplugged."
422   (when (and (not gnus-plugged) (gnus-agent-any-covered-gcc))
423     (save-excursion
424       (goto-char (point-min))
425       (let ((case-fold-search t))
426         (while (re-search-forward "^gcc:" nil t)
427           (replace-match (concat gnus-agent-gcc-header ":") 'fixedcase))))))
428
429 (defun gnus-agent-possibly-do-gcc ()
430   "Do GCC if Gnus is plugged."
431   (when (or gnus-plugged (not (gnus-agent-any-covered-gcc)))
432     (gnus-inews-do-gcc)))
433
434 ;;;
435 ;;; Group mode commands
436 ;;;
437
438 (defun gnus-agent-fetch-groups (n)
439   "Put all new articles in the current groups into the Agent."
440   (interactive "P")
441   (unless gnus-plugged
442     (error "Groups can't be fetched when Gnus is unplugged"))
443   (gnus-group-iterate n 'gnus-agent-fetch-group))
444
445 (defun gnus-agent-fetch-group (group)
446   "Put all new articles in GROUP into the Agent."
447   (interactive (list (gnus-group-group-name)))
448   (unless gnus-plugged
449     (error "Groups can't be fetched when Gnus is unplugged"))
450   (unless group
451     (error "No group on the current line"))
452   (let ((gnus-command-method (gnus-find-method-for-group group)))
453     (gnus-agent-with-fetch
454       (gnus-agent-fetch-group-1 group gnus-command-method)
455       (gnus-message 5 "Fetching %s...done" group))))
456
457 (defun gnus-agent-add-group (category arg)
458   "Add the current group to an agent category."
459   (interactive
460    (list
461     (intern
462      (completing-read
463       "Add to category: "
464       (mapcar (lambda (cat) (list (symbol-name (car cat))))
465               gnus-category-alist)
466       nil t))
467     current-prefix-arg))
468   (let ((cat (assq category gnus-category-alist))
469         c groups)
470     (gnus-group-iterate arg
471       (lambda (group)
472         (when (cadddr (setq c (gnus-group-category group)))
473           (setf (cadddr c) (delete group (cadddr c))))
474         (push group groups)))
475     (setf (cadddr cat) (nconc (cadddr cat) groups))
476     (gnus-category-write)))
477
478 (defun gnus-agent-remove-group (arg)
479   "Remove the current group from its agent category, if any."
480   (interactive "P")
481   (let (c)
482     (gnus-group-iterate arg
483       (lambda (group)
484         (when (cadddr (setq c (gnus-group-category group)))
485           (setf (cadddr c) (delete group (cadddr c))))))
486     (gnus-category-write)))
487
488 (defun gnus-agent-synchronize-flags ()
489   "Synchronize unplugged flags with servers."
490   (interactive)
491   (save-excursion
492     (dolist (gnus-command-method gnus-agent-covered-methods)
493       (when (file-exists-p (gnus-agent-lib-file "flags"))
494         (gnus-agent-synchronize-flags-server gnus-command-method)))))
495
496 (defun gnus-agent-possibly-synchronize-flags ()
497   "Synchronize flags according to `gnus-agent-synchronize-flags'."
498   (interactive)
499   (save-excursion
500     (dolist (gnus-command-method gnus-agent-covered-methods)
501       (when (file-exists-p (gnus-agent-lib-file "flags"))
502         (gnus-agent-possibly-synchronize-flags-server gnus-command-method)))))
503
504 (defun gnus-agent-synchronize-flags-server (method)
505   "Synchronize flags set when unplugged for server."
506   (let ((gnus-command-method method))
507     (when (file-exists-p (gnus-agent-lib-file "flags"))
508       (set-buffer (get-buffer-create " *Gnus Agent flag synchronize*"))
509       (erase-buffer)
510       (nnheader-insert-file-contents (gnus-agent-lib-file "flags"))
511       (if (null (gnus-check-server gnus-command-method))
512           (message "Couldn't open server %s" (nth 1 gnus-command-method))
513         (while (not (eobp))
514           (if (null (eval (read (current-buffer))))
515               (progn (forward-line)
516                      (kill-line -1))
517             (write-file (gnus-agent-lib-file "flags"))
518             (error "Couldn't set flags from file %s"
519                    (gnus-agent-lib-file "flags"))))
520         (delete-file (gnus-agent-lib-file "flags")))
521       (kill-buffer nil))))
522
523 (defun gnus-agent-possibly-synchronize-flags-server (method)
524   "Synchronize flags for server according to `gnus-agent-synchronize-flags'."
525   (when (or (and gnus-agent-synchronize-flags
526                  (not (eq gnus-agent-synchronize-flags 'ask)))
527             (and (eq gnus-agent-synchronize-flags 'ask)
528                  (gnus-y-or-n-p (format "Synchronize flags on server `%s'? "
529                                         (cadr method)))))
530     (gnus-agent-synchronize-flags-server method)))
531
532 ;;;
533 ;;; Server mode commands
534 ;;;
535
536 (defun gnus-agent-add-server (server)
537   "Enroll SERVER in the agent program."
538   (interactive (list (gnus-server-server-name)))
539   (unless server
540     (error "No server on the current line"))
541   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
542     (when (member method gnus-agent-covered-methods)
543       (error "Server already in the agent program"))
544     (push method gnus-agent-covered-methods)
545     (gnus-agent-write-servers)
546     (message "Entered %s into the Agent" server)))
547
548 (defun gnus-agent-remove-server (server)
549   "Remove SERVER from the agent program."
550   (interactive (list (gnus-server-server-name)))
551   (unless server
552     (error "No server on the current line"))
553   (let ((method (gnus-server-get-method nil (gnus-server-server-name))))
554     (unless (member method gnus-agent-covered-methods)
555       (error "Server not in the agent program"))
556     (setq gnus-agent-covered-methods
557           (delete method gnus-agent-covered-methods))
558     (gnus-agent-write-servers)
559     (message "Removed %s from the agent" server)))
560
561 (defun gnus-agent-read-servers ()
562   "Read the alist of covered servers."
563   (setq gnus-agent-covered-methods
564         (gnus-agent-read-file
565          (nnheader-concat gnus-agent-directory "lib/servers"))))
566
567 (defun gnus-agent-write-servers ()
568   "Write the alist of covered servers."
569   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
570   (let ((coding-system-for-write nnheader-file-coding-system)
571         (file-name-coding-system nnmail-pathname-coding-system))
572     (with-temp-file (nnheader-concat gnus-agent-directory "lib/servers")
573       (prin1 gnus-agent-covered-methods (current-buffer)))))
574
575 ;;;
576 ;;; Summary commands
577 ;;;
578
579 (defun gnus-agent-mark-article (n &optional unmark)
580   "Mark the next N articles as downloadable.
581 If N is negative, mark backward instead.  If UNMARK is non-nil, remove
582 the mark instead.  The difference between N and the actual number of
583 articles marked is returned."
584   (interactive "p")
585   (let ((backward (< n 0))
586         (n (abs n)))
587     (while (and
588             (> n 0)
589             (progn
590               (gnus-summary-set-agent-mark
591                (gnus-summary-article-number) unmark)
592               (zerop (gnus-summary-next-subject (if backward -1 1) nil t))))
593       (setq n (1- n)))
594     (when (/= 0 n)
595       (gnus-message 7 "No more articles"))
596     (gnus-summary-recenter)
597     (gnus-summary-position-point)
598     n))
599
600 (defun gnus-agent-unmark-article (n)
601   "Remove the downloadable mark from the next N articles.
602 If N is negative, unmark backward instead.  The difference between N and
603 the actual number of articles unmarked is returned."
604   (interactive "p")
605   (gnus-agent-mark-article n t))
606
607 (defun gnus-agent-toggle-mark (n)
608   "Toggle the downloadable mark from the next N articles.
609 If N is negative, toggle backward instead.  The difference between N and
610 the actual number of articles toggled is returned."
611   (interactive "p")
612   (gnus-agent-mark-article n 'toggle))
613
614 (defun gnus-summary-set-agent-mark (article &optional unmark)
615   "Mark ARTICLE as downloadable."
616   (let ((unmark (if (and (not (null unmark)) (not (eq t unmark)))
617                     (memq article gnus-newsgroup-downloadable)
618                   unmark)))
619     (if unmark
620         (progn
621           (setq gnus-newsgroup-downloadable
622                 (delq article gnus-newsgroup-downloadable))
623           (push article gnus-newsgroup-undownloaded))
624       (setq gnus-newsgroup-undownloaded
625             (delq article gnus-newsgroup-undownloaded))
626       (push article gnus-newsgroup-downloadable))
627     (gnus-summary-update-mark
628      (if unmark gnus-undownloaded-mark gnus-downloadable-mark)
629      'unread)))
630
631 (defun gnus-agent-get-undownloaded-list ()
632   "Mark all unfetched articles as read."
633   (let ((gnus-command-method (gnus-find-method-for-group gnus-newsgroup-name)))
634     (when (and (not gnus-plugged)
635                (gnus-agent-method-p gnus-command-method))
636       (gnus-agent-load-alist gnus-newsgroup-name)
637       ;; First mark all undownloaded articles as undownloaded.
638       (let ((articles (append gnus-newsgroup-unreads
639                               gnus-newsgroup-marked
640                               gnus-newsgroup-dormant))
641             article)
642         (while (setq article (pop articles))
643           (unless (or (cdr (assq article gnus-agent-article-alist))
644                       (memq article gnus-newsgroup-downloadable)
645                       (memq article gnus-newsgroup-cached))
646             (push article gnus-newsgroup-undownloaded))))
647       ;; Then mark downloaded downloadable as not-downloadable,
648       ;; if you get my drift.
649       (let ((articles gnus-newsgroup-downloadable)
650             article)
651         (while (setq article (pop articles))
652           (when (cdr (assq article gnus-agent-article-alist))
653             (setq gnus-newsgroup-downloadable
654                   (delq article gnus-newsgroup-downloadable))))))))
655
656 (defun gnus-agent-catchup ()
657   "Mark all undownloaded articles as read."
658   (interactive)
659   (save-excursion
660     (while gnus-newsgroup-undownloaded
661       (gnus-summary-mark-article
662        (pop gnus-newsgroup-undownloaded) gnus-catchup-mark)))
663   (gnus-summary-position-point))
664
665 ;;;
666 ;;; Internal functions
667 ;;;
668
669 (defun gnus-agent-save-active (method)
670   (gnus-agent-save-active-1 method 'gnus-active-to-gnus-format))
671
672 (defun gnus-agent-save-active-1 (method function)
673   (when (gnus-agent-method-p method)
674     (let* ((gnus-command-method method)
675            (new (gnus-make-hashtable (count-lines (point-min) (point-max))))
676            (file (gnus-agent-lib-file "active")))
677       (funcall function nil new)
678       (gnus-agent-write-active file new)
679       (erase-buffer)
680       (nnheader-insert-file-contents file))))
681
682 (defun gnus-agent-write-active (file new)
683   (let ((orig (gnus-make-hashtable (count-lines (point-min) (point-max))))
684         (file (gnus-agent-lib-file "active"))
685         elem osym)
686     (when (file-exists-p file)
687       (with-temp-buffer
688         (nnheader-insert-file-contents file)
689         (gnus-active-to-gnus-format nil orig))
690       (mapatoms
691        (lambda (sym)
692          (when (and sym (boundp sym))
693            (if (and (boundp (setq osym (intern (symbol-name sym) orig)))
694                     (setq elem (symbol-value osym)))
695                (setcdr elem (cdr (symbol-value sym)))
696              (set (intern (symbol-name sym) orig) (symbol-value sym)))))
697        new))
698     (gnus-make-directory (file-name-directory file))
699     (let ((coding-system-for-write gnus-agent-file-coding-system))
700       ;; The hashtable contains real names of groups,  no more prefix
701       ;; removing, so set `full' to `t'.
702       (gnus-write-active-file file orig t))))
703
704 (defun gnus-agent-save-groups (method)
705   (gnus-agent-save-active-1 method 'gnus-groups-to-gnus-format))
706
707 (defun gnus-agent-save-group-info (method group active)
708   (when (gnus-agent-method-p method)
709     (let* ((gnus-command-method method)
710            (coding-system-for-write nnheader-file-coding-system)
711            (file-name-coding-system nnmail-pathname-coding-system)
712            (file (gnus-agent-lib-file "active"))
713            oactive)
714       (gnus-make-directory (file-name-directory file))
715       (with-temp-file file
716         ;; Emacs got problem to match non-ASCII group in multibyte buffer.
717         (mm-disable-multibyte)
718         (when (file-exists-p file)
719           (nnheader-insert-file-contents file))
720         (goto-char (point-min))
721         (when (re-search-forward
722                (concat "^" (regexp-quote group) " ") nil t)
723           (save-excursion
724             (save-restriction
725               (narrow-to-region (match-beginning 0)
726                                 (progn
727                                   (forward-line 1)
728                                   (point)))
729               (setq oactive (car (nnmail-parse-active)))))
730           (gnus-delete-line))
731         (insert (format "%S %d %d y\n" (intern group)
732                         (cdr active)
733                         (or (car oactive) (car active))))
734         (goto-char (point-max))
735         (while (search-backward "\\." nil t)
736           (delete-char 1))))))
737
738 (defun gnus-agent-group-path (group)
739   "Translate GROUP into a path."
740   (if nnmail-use-long-file-names
741       (gnus-group-real-name group)
742     (nnheader-translate-file-chars
743      (nnheader-replace-chars-in-string
744       (nnheader-replace-duplicate-chars-in-string
745        (nnheader-replace-chars-in-string
746         (gnus-group-real-name group)
747         ?/ ?_)
748        ?. ?_)
749       ?. ?/))))
750
751 \f
752
753 (defun gnus-agent-method-p (method)
754   "Say whether METHOD is covered by the agent."
755   (member method gnus-agent-covered-methods))
756
757 (defun gnus-agent-get-function (method)
758   (if (and (not gnus-plugged)
759            (gnus-agent-method-p method))
760       (progn
761         (require 'nnagent)
762         'nnagent)
763     (car method)))
764
765 ;;; History functions
766
767 (defun gnus-agent-history-buffer ()
768   (cdr (assoc (gnus-agent-method) gnus-agent-history-buffers)))
769
770 (defun gnus-agent-open-history ()
771   (save-excursion
772     (push (cons (gnus-agent-method)
773                 (set-buffer (gnus-get-buffer-create
774                              (format " *Gnus agent %s history*"
775                                      (gnus-agent-method)))))
776           gnus-agent-history-buffers)
777     (mm-disable-multibyte) ;; everything is binary
778     (erase-buffer)
779     (insert "\n")
780     (let ((file (gnus-agent-lib-file "history")))
781       (when (file-exists-p file)
782         (nnheader-insert-file-contents file))
783       (set (make-local-variable 'gnus-agent-file-name) file))))
784
785 (defun gnus-agent-save-history ()
786   (save-excursion
787     (set-buffer gnus-agent-current-history)
788     (gnus-make-directory (file-name-directory gnus-agent-file-name))
789     (let ((coding-system-for-write gnus-agent-file-coding-system))
790       (write-region (1+ (point-min)) (point-max)
791                     gnus-agent-file-name nil 'silent))))
792
793 (defun gnus-agent-close-history ()
794   (when (gnus-buffer-live-p gnus-agent-current-history)
795     (kill-buffer gnus-agent-current-history)
796     (setq gnus-agent-history-buffers
797           (delq (assoc (gnus-agent-method) gnus-agent-history-buffers)
798                 gnus-agent-history-buffers))))
799
800 (defun gnus-agent-enter-history (id group-arts date)
801   (save-excursion
802     (set-buffer gnus-agent-current-history)
803     (goto-char (point-max))
804     (let ((p (point)))
805       (insert id "\t" (number-to-string date) "\t")
806       (while group-arts
807         (insert (format "%S" (intern (caar group-arts)))
808                 " " (number-to-string (cdr (pop group-arts)))
809                 " "))
810       (insert "\n")
811       (while (search-backward "\\." p t)
812         (delete-char 1)))))
813
814 (defun gnus-agent-article-in-history-p (id)
815   (save-excursion
816     (set-buffer (gnus-agent-history-buffer))
817     (goto-char (point-min))
818     (search-forward (concat "\n" id "\t") nil t)))
819
820 (defun gnus-agent-history-path (id)
821   (save-excursion
822     (set-buffer (gnus-agent-history-buffer))
823     (goto-char (point-min))
824     (when (search-forward (concat "\n" id "\t") nil t)
825       (let ((method (gnus-agent-method)))
826         (let (paths group)
827           (while (not (numberp (setq group (read (current-buffer)))))
828             (push (concat method "/" group) paths))
829           (nreverse paths))))))
830
831 ;;;
832 ;;; Fetching
833 ;;;
834
835 (defun gnus-agent-fetch-articles (group articles)
836   "Fetch ARTICLES from GROUP and put them into the Agent."
837   (when articles
838     ;; Prune off articles that we have already fetched.
839     (while (and articles
840                 (cdr (assq (car articles) gnus-agent-article-alist)))
841       (pop articles))
842     (let ((arts articles))
843       (while (cdr arts)
844         (if (cdr (assq (cadr arts) gnus-agent-article-alist))
845             (setcdr arts (cddr arts))
846           (setq arts (cdr arts)))))
847     (when articles
848       (let ((dir (concat
849                   (gnus-agent-directory)
850                   (gnus-agent-group-path group) "/"))
851             (date (time-to-days (current-time)))
852             (case-fold-search t)
853             pos crosses id elem)
854         (gnus-make-directory dir)
855         (gnus-message 7 "Fetching articles for %s..." group)
856         ;; Fetch the articles from the backend.
857         (if (gnus-check-backend-function 'retrieve-articles group)
858             (setq pos (gnus-retrieve-articles articles group))
859           (with-temp-buffer
860             (let (article)
861               (while (setq article (pop articles))
862                 (when (or
863                        (gnus-backlog-request-article group article
864                                                      nntp-server-buffer)
865                        (gnus-request-article article group))
866                   (goto-char (point-max))
867                   (push (cons article (point)) pos)
868                   (insert-buffer-substring nntp-server-buffer)))
869               (copy-to-buffer nntp-server-buffer (point-min) (point-max))
870               (setq pos (nreverse pos)))))
871         ;; Then save these articles into the Agent.
872         (save-excursion
873           (set-buffer nntp-server-buffer)
874           (while pos
875             (narrow-to-region (cdar pos) (or (cdadr pos) (point-max)))
876             (goto-char (point-min))
877             (when (search-forward "\n\n" nil t)
878               (when (search-backward "\nXrefs: " nil t)
879                 ;; Handle crossposting.
880                 (skip-chars-forward "^ ")
881                 (skip-chars-forward " ")
882                 (setq crosses nil)
883                 (while (looking-at "\\([^: \n]+\\):\\([0-9]+\\) +")
884                   (push (cons (buffer-substring (match-beginning 1)
885                                                 (match-end 1))
886                               (buffer-substring (match-beginning 2)
887                                                 (match-end 2)))
888                         crosses)
889                   (goto-char (match-end 0)))
890                 (gnus-agent-crosspost crosses (caar pos))))
891             (goto-char (point-min))
892             (if (not (re-search-forward "^Message-ID: *<\\([^>\n]+\\)>" nil t))
893                 (setq id "No-Message-ID-in-article")
894               (setq id (buffer-substring (match-beginning 1) (match-end 1))))
895             (let ((coding-system-for-write
896                    gnus-agent-file-coding-system))
897               (write-region (point-min) (point-max)
898                             (concat dir (number-to-string (caar pos)))
899                             nil 'silent))
900             (when (setq elem (assq (caar pos) gnus-agent-article-alist))
901               (setcdr elem t))
902             (gnus-agent-enter-history
903              id (or crosses (list (cons group (caar pos)))) date)
904             (widen)
905             (pop pos)))
906         (gnus-agent-save-alist group)))))
907
908 (defun gnus-agent-crosspost (crosses article)
909   (let (gnus-agent-article-alist group alist beg end)
910     (save-excursion
911       (set-buffer gnus-agent-overview-buffer)
912       (when (nnheader-find-nov-line article)
913         (forward-word 1)
914         (setq beg (point))
915         (setq end (progn (forward-line 1) (point)))))
916     (while crosses
917       (setq group (caar crosses))
918       (unless (setq alist (assoc group gnus-agent-group-alist))
919         (push (setq alist (list group (gnus-agent-load-alist (caar crosses))))
920               gnus-agent-group-alist))
921       (setcdr alist (cons (cons (cdar crosses) t) (cdr alist)))
922       (save-excursion
923         (set-buffer (gnus-get-buffer-create (format " *Gnus agent overview %s*"
924                                                     group)))
925         (when (= (point-max) (point-min))
926           (push (cons group (current-buffer)) gnus-agent-buffer-alist)
927           (ignore-errors
928             (nnheader-insert-file-contents
929              (gnus-agent-article-name ".overview" group))))
930         (nnheader-find-nov-line (string-to-number (cdar crosses)))
931         (insert (string-to-number (cdar crosses)))
932         (insert-buffer-substring gnus-agent-overview-buffer beg end))
933       (pop crosses))))
934
935 (defun gnus-agent-flush-cache ()
936   (save-excursion
937     (while gnus-agent-buffer-alist
938       (set-buffer (cdar gnus-agent-buffer-alist))
939       (let ((coding-system-for-write
940              gnus-agent-file-coding-system))
941         (write-region (point-min) (point-max)
942                       (gnus-agent-article-name ".overview"
943                                                (caar gnus-agent-buffer-alist))
944                       nil 'silent))
945       (pop gnus-agent-buffer-alist))
946     (while gnus-agent-group-alist
947       (with-temp-file (caar gnus-agent-group-alist)
948         (princ (cdar gnus-agent-group-alist))
949         (insert "\n"))
950       (pop gnus-agent-group-alist))))
951
952 (defun gnus-agent-fetch-headers (group &optional force)
953   (let ((articles (gnus-list-of-unread-articles group))
954         (gnus-decode-encoded-word-function 'identity)
955         (file (gnus-agent-article-name ".overview" group)))
956     ;; Add article with marks to list of article headers we want to fetch.
957     (dolist (arts (gnus-info-marks (gnus-get-info group)))
958       (setq articles (gnus-union (gnus-uncompress-sequence (cdr arts))
959                             articles)))
960     (setq articles (sort articles '<))
961     ;; Remove known articles.
962     (when (gnus-agent-load-alist group)
963       (setq articles (gnus-sorted-intersection
964                       articles
965                       (gnus-uncompress-range
966                        (cons (1+ (caar (last gnus-agent-article-alist)))
967                              (cdr (gnus-active group)))))))
968     ;; Fetch them.
969     (gnus-make-directory (nnheader-translate-file-chars
970                           (file-name-directory file) t))
971     (when articles
972       (gnus-message 7 "Fetching headers for %s..." group)
973       (save-excursion
974         (set-buffer nntp-server-buffer)
975         (unless (eq 'nov (gnus-retrieve-headers articles group))
976           (nnvirtual-convert-headers))
977         ;; Save these headers for later processing.
978         (copy-to-buffer gnus-agent-overview-buffer (point-min) (point-max))
979         (when (file-exists-p file)
980           (gnus-agent-braid-nov group articles file))
981         (let ((coding-system-for-write
982                gnus-agent-file-coding-system))
983           (write-region (point-min) (point-max) file nil 'silent))
984         (gnus-agent-save-alist group articles nil)
985         (gnus-agent-enter-history
986          "last-header-fetched-for-session"
987          (list (cons group (nth (- (length  articles) 1) articles)))
988          (time-to-days (current-time)))
989         articles))))
990
991 (defsubst gnus-agent-copy-nov-line (article)
992   (let (b e)
993     (set-buffer gnus-agent-overview-buffer)
994     (setq b (point))
995     (if (eq article (read (current-buffer)))
996         (setq e (progn (forward-line 1) (point)))
997       (progn
998         (beginning-of-line)
999         (setq e b)))
1000     (set-buffer nntp-server-buffer)
1001     (insert-buffer-substring gnus-agent-overview-buffer b e)))
1002
1003 (defun gnus-agent-braid-nov (group articles file)
1004   (set-buffer gnus-agent-overview-buffer)
1005   (goto-char (point-min))
1006   (set-buffer nntp-server-buffer)
1007   (erase-buffer)
1008   (nnheader-insert-file-contents file)
1009   (goto-char (point-max))
1010   (if (or (= (point-min) (point-max))
1011           (progn
1012             (forward-line -1)
1013             (< (read (current-buffer)) (car articles))))
1014       ;; We have only headers that are after the older headers,
1015       ;; so we just append them.
1016       (progn
1017         (goto-char (point-max))
1018         (insert-buffer-substring gnus-agent-overview-buffer))
1019     ;; We do it the hard way.
1020     (nnheader-find-nov-line (car articles))
1021     (gnus-agent-copy-nov-line (car articles))
1022     (pop articles)
1023     (while (and articles
1024                 (not (eobp)))
1025       (while (and (not (eobp))
1026                   (< (read (current-buffer)) (car articles)))
1027         (forward-line 1))
1028       (beginning-of-line)
1029       (unless (eobp)
1030         (gnus-agent-copy-nov-line (car articles))
1031         (setq articles (cdr articles))))
1032     (when articles
1033       (let (b e)
1034         (set-buffer gnus-agent-overview-buffer)
1035         (setq b (point)
1036               e (point-max))
1037         (set-buffer nntp-server-buffer)
1038         (insert-buffer-substring gnus-agent-overview-buffer b e)))))
1039
1040 (defun gnus-agent-load-alist (group &optional dir)
1041   "Load the article-state alist for GROUP."
1042   (setq gnus-agent-article-alist
1043         (gnus-agent-read-file
1044          (if dir
1045              (expand-file-name ".agentview" dir)
1046            (gnus-agent-article-name ".agentview" group)))))
1047
1048 (defun gnus-agent-save-alist (group &optional articles state dir)
1049   "Save the article-state alist for GROUP."
1050   (let ((file-name-coding-system nnmail-pathname-coding-system))
1051       (with-temp-file (if dir
1052                           (expand-file-name ".agentview" dir)
1053                         (gnus-agent-article-name ".agentview" group))
1054         (princ (setq gnus-agent-article-alist
1055                      (nconc gnus-agent-article-alist
1056                             (mapcar (lambda (article) (cons article state))
1057                                     articles)))
1058                (current-buffer))
1059         (insert "\n"))))
1060
1061 (defun gnus-agent-article-name (article group)
1062   (expand-file-name (if (stringp article) article (string-to-number article))
1063                     (file-name-as-directory
1064                      (expand-file-name (gnus-agent-group-path group)
1065                                        (gnus-agent-directory)))))
1066
1067 (defun gnus-agent-batch-confirmation (msg)
1068   "Show error message and return t."
1069   (gnus-message 1 msg)
1070   t)
1071
1072 ;;;###autoload
1073 (defun gnus-agent-batch-fetch ()
1074   "Start Gnus and fetch session."
1075   (interactive)
1076   (gnus)
1077   (let ((gnus-agent-confirmation-function 'gnus-agent-batch-confirmation))
1078     (gnus-agent-fetch-session))
1079   (gnus-group-exit))
1080
1081 (defun gnus-agent-fetch-session ()
1082   "Fetch all articles and headers that are eligible for fetching."
1083   (interactive)
1084   (unless gnus-agent-covered-methods
1085     (error "No servers are covered by the Gnus agent"))
1086   (unless gnus-plugged
1087     (error "Can't fetch articles while Gnus is unplugged"))
1088   (let ((methods gnus-agent-covered-methods)
1089         groups group gnus-command-method)
1090     (save-excursion
1091       (while methods
1092         (condition-case err
1093             (progn
1094               (setq gnus-command-method (car methods))
1095               (when (or (gnus-server-opened gnus-command-method)
1096                         (gnus-open-server gnus-command-method))
1097                 (setq groups (gnus-groups-from-server (car methods)))
1098                 (gnus-agent-with-fetch
1099                   (while (setq group (pop groups))
1100                     (when (<= (gnus-group-level group) gnus-agent-handle-level)
1101                       (gnus-agent-fetch-group-1 group gnus-command-method))))))
1102           (error
1103            (unless (funcall gnus-agent-confirmation-function
1104                             (format "Error (%s).  Continue? " err))
1105              (error "Cannot fetch articles into the Gnus agent.")))
1106           (quit
1107            (unless (funcall gnus-agent-confirmation-function
1108                             (format "Quit fetching session (%s).  Continue? "
1109                                     err))
1110              (signal 'quit "Cannot fetch articles into the Gnus agent."))))
1111         (pop methods))
1112       (gnus-message 6 "Finished fetching articles into the Gnus agent"))))
1113
1114 (defun gnus-agent-fetch-group-1 (group method)
1115   "Fetch GROUP."
1116   (let ((gnus-command-method method)
1117         (gnus-newsgroup-name group)
1118         gnus-newsgroup-dependencies gnus-newsgroup-headers
1119         gnus-newsgroup-scored gnus-headers gnus-score
1120         gnus-use-cache articles arts
1121         category predicate info marks score-param
1122         (gnus-summary-expunge-below gnus-summary-expunge-below)
1123         (gnus-summary-mark-below gnus-summary-mark-below)
1124         (gnus-orphan-score gnus-orphan-score)
1125         ;; Maybe some other gnus-summary local variables should also
1126         ;; be put here.
1127         )
1128     (unless (gnus-check-group group)
1129       (error "Can't open server for %s" group))
1130     ;; Fetch headers.
1131     (when (and (or (gnus-active group) (gnus-activate-group group))
1132                (setq articles (gnus-agent-fetch-headers group))
1133                (let ((nntp-server-buffer gnus-agent-overview-buffer))
1134                  ;; Parse them and see which articles we want to fetch.
1135                  (setq gnus-newsgroup-dependencies
1136                        (make-vector (length articles) 0))
1137                  (setq gnus-newsgroup-headers
1138                        (gnus-get-newsgroup-headers-xover articles nil nil
1139                                                          group))
1140                  ;; `gnus-agent-overview-buffer' may be killed for
1141                  ;; timeout reason.  If so, recreate it.
1142                  (gnus-agent-create-buffer)))
1143       (setq category (gnus-group-category group))
1144       (setq predicate
1145             (gnus-get-predicate
1146              (or (gnus-group-find-parameter group 'agent-predicate t)
1147                  (cadr category))))
1148       (if (memq (caaddr predicate) '(gnus-agent-true gnus-agent-false))
1149           ;; Simple implementation
1150           (setq arts
1151                 (and (eq (caaddr predicate) 'gnus-agent-true) articles))
1152         (setq arts nil)
1153         (setq score-param
1154               (or (gnus-group-get-parameter group 'agent-score t)
1155                   (caddr category)))
1156         ;; Translate score-param into real one
1157         (cond
1158          ((not score-param))
1159          ((eq score-param 'file)
1160           (setq score-param (gnus-all-score-files group)))
1161          ((stringp (car score-param)))
1162          (t
1163           (setq score-param (list (list score-param)))))
1164         (when score-param
1165           (gnus-score-headers score-param))
1166         (while (setq gnus-headers (pop gnus-newsgroup-headers))
1167           (setq gnus-score
1168                 (or (cdr (assq (mail-header-number gnus-headers)
1169                                gnus-newsgroup-scored))
1170                     gnus-summary-default-score))
1171           (when (funcall predicate)
1172             (push (mail-header-number gnus-headers)
1173                   arts))))
1174       ;; Fetch the articles.
1175       (when arts
1176         (gnus-agent-fetch-articles group arts)))
1177     ;; Perhaps we have some additional articles to fetch.
1178     (setq arts (assq 'download (gnus-info-marks
1179                                 (setq info (gnus-get-info group)))))
1180     (when (cdr arts)
1181       (gnus-agent-fetch-articles
1182        group (gnus-uncompress-range (cdr arts)))
1183       (setq marks (delq arts (gnus-info-marks info)))
1184       (gnus-info-set-marks info marks)
1185       (gnus-dribble-enter
1186        (concat "(gnus-group-set-info '"
1187                (gnus-prin1-to-string info)
1188                ")")))))
1189
1190 ;;;
1191 ;;; Agent Category Mode
1192 ;;;
1193
1194 (defvar gnus-category-mode-hook nil
1195   "Hook run in `gnus-category-mode' buffers.")
1196
1197 (defvar gnus-category-line-format "     %(%20c%): %g\n"
1198   "Format of category lines.")
1199
1200 (defvar gnus-category-mode-line-format "Gnus: %%b"
1201   "The format specification for the category mode line.")
1202
1203 (defvar gnus-agent-short-article 100
1204   "Articles that have fewer lines than this are short.")
1205
1206 (defvar gnus-agent-long-article 200
1207   "Articles that have more lines than this are long.")
1208
1209 (defvar gnus-agent-low-score 0
1210   "Articles that have a score lower than this have a low score.")
1211
1212 (defvar gnus-agent-high-score 0
1213   "Articles that have a score higher than this have a high score.")
1214
1215
1216 ;;; Internal variables.
1217
1218 (defvar gnus-category-buffer "*Agent Category*")
1219
1220 (defvar gnus-category-line-format-alist
1221   `((?c gnus-tmp-name ?s)
1222     (?g gnus-tmp-groups ?d)))
1223
1224 (defvar gnus-category-mode-line-format-alist
1225   `((?u user-defined ?s)))
1226
1227 (defvar gnus-category-line-format-spec nil)
1228 (defvar gnus-category-mode-line-format-spec nil)
1229
1230 (defvar gnus-category-mode-map nil)
1231 (put 'gnus-category-mode 'mode-class 'special)
1232
1233 (unless gnus-category-mode-map
1234   (setq gnus-category-mode-map (make-sparse-keymap))
1235   (suppress-keymap gnus-category-mode-map)
1236
1237   (gnus-define-keys gnus-category-mode-map
1238     "q" gnus-category-exit
1239     "k" gnus-category-kill
1240     "c" gnus-category-copy
1241     "a" gnus-category-add
1242     "p" gnus-category-edit-predicate
1243     "g" gnus-category-edit-groups
1244     "s" gnus-category-edit-score
1245     "l" gnus-category-list
1246
1247     "\C-c\C-i" gnus-info-find-node
1248     "\C-c\C-b" gnus-bug))
1249
1250 (defvar gnus-category-menu-hook nil
1251   "*Hook run after the creation of the menu.")
1252
1253 (defun gnus-category-make-menu-bar ()
1254   (gnus-turn-off-edit-menu 'category)
1255   (unless (boundp 'gnus-category-menu)
1256     (easy-menu-define
1257      gnus-category-menu gnus-category-mode-map ""
1258      '("Categories"
1259        ["Add" gnus-category-add t]
1260        ["Kill" gnus-category-kill t]
1261        ["Copy" gnus-category-copy t]
1262        ["Edit predicate" gnus-category-edit-predicate t]
1263        ["Edit score" gnus-category-edit-score t]
1264        ["Edit groups" gnus-category-edit-groups t]
1265        ["Exit" gnus-category-exit t]))
1266
1267     (gnus-run-hooks 'gnus-category-menu-hook)))
1268
1269 (defun gnus-category-mode ()
1270   "Major mode for listing and editing agent categories.
1271
1272 All normal editing commands are switched off.
1273 \\<gnus-category-mode-map>
1274 For more in-depth information on this mode, read the manual
1275 (`\\[gnus-info-find-node]').
1276
1277 The following commands are available:
1278
1279 \\{gnus-category-mode-map}"
1280   (interactive)
1281   (when (gnus-visual-p 'category-menu 'menu)
1282     (gnus-category-make-menu-bar))
1283   (kill-all-local-variables)
1284   (gnus-simplify-mode-line)
1285   (setq major-mode 'gnus-category-mode)
1286   (setq mode-name "Category")
1287   (gnus-set-default-directory)
1288   (setq mode-line-process nil)
1289   (use-local-map gnus-category-mode-map)
1290   (buffer-disable-undo)
1291   (setq truncate-lines t)
1292   (setq buffer-read-only t)
1293   (gnus-run-hooks 'gnus-category-mode-hook))
1294
1295 (defalias 'gnus-category-position-point 'gnus-goto-colon)
1296
1297 (defun gnus-category-insert-line (category)
1298   (let* ((gnus-tmp-name (car category))
1299          (gnus-tmp-groups (length (cadddr category))))
1300     (beginning-of-line)
1301     (gnus-add-text-properties
1302      (point)
1303      (prog1 (1+ (point))
1304        ;; Insert the text.
1305        (eval gnus-category-line-format-spec))
1306      (list 'gnus-category gnus-tmp-name))))
1307
1308 (defun gnus-enter-category-buffer ()
1309   "Go to the Category buffer."
1310   (interactive)
1311   (gnus-category-setup-buffer)
1312   (gnus-configure-windows 'category)
1313   (gnus-category-prepare))
1314
1315 (defun gnus-category-setup-buffer ()
1316   (unless (get-buffer gnus-category-buffer)
1317     (save-excursion
1318       (set-buffer (gnus-get-buffer-create gnus-category-buffer))
1319       (gnus-category-mode))))
1320
1321 (defun gnus-category-prepare ()
1322   (gnus-set-format 'category-mode)
1323   (gnus-set-format 'category t)
1324   (let ((alist gnus-category-alist)
1325         (buffer-read-only nil))
1326     (erase-buffer)
1327     (while alist
1328       (gnus-category-insert-line (pop alist)))
1329     (goto-char (point-min))
1330     (gnus-category-position-point)))
1331
1332 (defun gnus-category-name ()
1333   (or (get-text-property (gnus-point-at-bol) 'gnus-category)
1334       (error "No category on the current line")))
1335
1336 (defun gnus-category-read ()
1337   "Read the category alist."
1338   (setq gnus-category-alist
1339         (or (gnus-agent-read-file
1340              (nnheader-concat gnus-agent-directory "lib/categories"))
1341             (list (list 'default 'short nil nil)))))
1342
1343 (defun gnus-category-write ()
1344   "Write the category alist."
1345   (setq gnus-category-predicate-cache nil
1346         gnus-category-group-cache nil)
1347   (gnus-make-directory (nnheader-concat gnus-agent-directory "lib"))
1348   (with-temp-file (nnheader-concat gnus-agent-directory "lib/categories")
1349     (prin1 gnus-category-alist (current-buffer))))
1350
1351 (defun gnus-category-edit-predicate (category)
1352   "Edit the predicate for CATEGORY."
1353   (interactive (list (gnus-category-name)))
1354   (let ((info (assq category gnus-category-alist)))
1355     (gnus-edit-form
1356      (cadr info) (format "Editing the predicate for category %s" category)
1357      `(lambda (predicate)
1358         (setcar (cdr (assq ',category gnus-category-alist)) predicate)
1359         (gnus-category-write)
1360         (gnus-category-list)))))
1361
1362 (defun gnus-category-edit-score (category)
1363   "Edit the score expression for CATEGORY."
1364   (interactive (list (gnus-category-name)))
1365   (let ((info (assq category gnus-category-alist)))
1366     (gnus-edit-form
1367      (caddr info)
1368      (format "Editing the score expression for category %s" category)
1369      `(lambda (groups)
1370         (setcar (cddr (assq ',category gnus-category-alist)) groups)
1371         (gnus-category-write)
1372         (gnus-category-list)))))
1373
1374 (defun gnus-category-edit-groups (category)
1375   "Edit the group list for CATEGORY."
1376   (interactive (list (gnus-category-name)))
1377   (let ((info (assq category gnus-category-alist)))
1378     (gnus-edit-form
1379      (cadddr info) (format "Editing the group list for category %s" category)
1380      `(lambda (groups)
1381         (setcar (nthcdr 3 (assq ',category gnus-category-alist)) groups)
1382         (gnus-category-write)
1383         (gnus-category-list)))))
1384
1385 (defun gnus-category-kill (category)
1386   "Kill the current category."
1387   (interactive (list (gnus-category-name)))
1388   (let ((info (assq category gnus-category-alist))
1389         (buffer-read-only nil))
1390     (gnus-delete-line)
1391     (setq gnus-category-alist (delq info gnus-category-alist))
1392     (gnus-category-write)))
1393
1394 (defun gnus-category-copy (category to)
1395   "Copy the current category."
1396   (interactive (list (gnus-category-name) (intern (read-string "New name: "))))
1397   (let ((info (assq category gnus-category-alist)))
1398     (push (list to (gnus-copy-sequence (cadr info))
1399                 (gnus-copy-sequence (caddr info)) nil)
1400           gnus-category-alist)
1401     (gnus-category-write)
1402     (gnus-category-list)))
1403
1404 (defun gnus-category-add (category)
1405   "Create a new category."
1406   (interactive "SCategory name: ")
1407   (when (assq category gnus-category-alist)
1408     (error "Category %s already exists" category))
1409   (push (list category 'false nil nil)
1410         gnus-category-alist)
1411   (gnus-category-write)
1412   (gnus-category-list))
1413
1414 (defun gnus-category-list ()
1415   "List all categories."
1416   (interactive)
1417   (gnus-category-prepare))
1418
1419 (defun gnus-category-exit ()
1420   "Return to the group buffer."
1421   (interactive)
1422   (kill-buffer (current-buffer))
1423   (gnus-configure-windows 'group t))
1424
1425 ;; To avoid having 8-bit characters in the source file.
1426 (defvar gnus-category-not (list '! 'not (intern (format "%c" 172))))
1427
1428 (defvar gnus-category-predicate-alist
1429   '((spam . gnus-agent-spam-p)
1430     (short . gnus-agent-short-p)
1431     (long . gnus-agent-long-p)
1432     (low . gnus-agent-low-scored-p)
1433     (high . gnus-agent-high-scored-p)
1434     (true . gnus-agent-true)
1435     (false . gnus-agent-false))
1436   "Mapping from short score predicate symbols to predicate functions.")
1437
1438 (defun gnus-agent-spam-p ()
1439   "Say whether an article is spam or not."
1440   (unless gnus-agent-spam-hashtb
1441     (setq gnus-agent-spam-hashtb (gnus-make-hashtable 1000)))
1442   (if (not (equal (mail-header-references gnus-headers) ""))
1443       nil
1444     (let ((string (gnus-simplify-subject (mail-header-subject gnus-headers))))
1445       (prog1
1446           (gnus-gethash string gnus-agent-spam-hashtb)
1447         (gnus-sethash string t gnus-agent-spam-hashtb)))))
1448
1449 (defun gnus-agent-short-p ()
1450   "Say whether an article is short or not."
1451   (< (mail-header-lines gnus-headers) gnus-agent-short-article))
1452
1453 (defun gnus-agent-long-p ()
1454   "Say whether an article is long or not."
1455   (> (mail-header-lines gnus-headers) gnus-agent-long-article))
1456
1457 (defun gnus-agent-low-scored-p ()
1458   "Say whether an article has a low score or not."
1459   (< gnus-score gnus-agent-low-score))
1460
1461 (defun gnus-agent-high-scored-p ()
1462   "Say whether an article has a high score or not."
1463   (> gnus-score gnus-agent-high-score))
1464
1465 (defun gnus-category-make-function (cat)
1466   "Make a function from category CAT."
1467   `(lambda () ,(gnus-category-make-function-1 cat)))
1468
1469 (defun gnus-agent-true ()
1470   "Return t."
1471   t)
1472
1473 (defun gnus-agent-false ()
1474   "Return nil."
1475   nil)
1476
1477 (defun gnus-category-make-function-1 (cat)
1478   "Make a function from category CAT."
1479   (cond
1480    ;; Functions are just returned as is.
1481    ((or (symbolp cat)
1482         (gnus-functionp cat))
1483     `(,(or (cdr (assq cat gnus-category-predicate-alist))
1484            cat)))
1485    ;; More complex category.
1486    ((consp cat)
1487     `(,(cond
1488         ((memq (car cat) '(& and))
1489          'and)
1490         ((memq (car cat) '(| or))
1491          'or)
1492         ((memq (car cat) gnus-category-not)
1493          'not))
1494       ,@(mapcar 'gnus-category-make-function-1 (cdr cat))))
1495    (t
1496     (error "Unknown category type: %s" cat))))
1497
1498 (defun gnus-get-predicate (predicate)
1499   "Return the predicate for CATEGORY."
1500   (or (cdr (assoc predicate gnus-category-predicate-cache))
1501       (cdar (push (cons predicate
1502                         (gnus-category-make-function predicate))
1503                   gnus-category-predicate-cache))))
1504
1505 (defun gnus-group-category (group)
1506   "Return the category GROUP belongs to."
1507   (unless gnus-category-group-cache
1508     (setq gnus-category-group-cache (gnus-make-hashtable 1000))
1509     (let ((cs gnus-category-alist)
1510           groups cat)
1511       (while (setq cat (pop cs))
1512         (setq groups (cadddr cat))
1513         (while groups
1514           (gnus-sethash (pop groups) cat gnus-category-group-cache)))))
1515   (or (gnus-gethash group gnus-category-group-cache)
1516       (assq 'default gnus-category-alist)))
1517
1518 (defun gnus-agent-expire ()
1519   "Expire all old articles."
1520   (interactive)
1521   (let ((methods gnus-agent-covered-methods)
1522         (day (- (time-to-days (current-time)) gnus-agent-expire-days))
1523         gnus-command-method sym group articles
1524         history overview file histories elem art nov-file low info
1525         unreads marked article orig lowest highest)
1526     (save-excursion
1527       (setq overview (gnus-get-buffer-create " *expire overview*"))
1528       (while (setq gnus-command-method (pop methods))
1529         (when (file-exists-p (gnus-agent-lib-file "active"))
1530           (with-temp-buffer
1531             (nnheader-insert-file-contents (gnus-agent-lib-file "active"))
1532             (gnus-active-to-gnus-format
1533              gnus-command-method
1534              (setq orig (gnus-make-hashtable
1535                          (count-lines (point-min) (point-max))))))
1536           (let ((expiry-hashtb (gnus-make-hashtable 1023)))
1537             (gnus-agent-open-history)
1538             (set-buffer
1539              (setq gnus-agent-current-history
1540                    (setq history (gnus-agent-history-buffer))))
1541             (goto-char (point-min))
1542             (when (> (buffer-size) 1)
1543               (goto-char (point-min))
1544               (while (not (eobp))
1545                 (skip-chars-forward "^\t")
1546                 (if (let ((fetch-date (read (current-buffer))))
1547                       (if (numberp fetch-date)
1548                           (>  fetch-date day)
1549                         ;; History file is corrupted.
1550                         (gnus-message
1551                          5
1552                          (format "File %s is corrupted!"
1553                                  (gnus-agent-lib-file "history")))
1554                         (sit-for 1)
1555                         ;; Ignore it
1556                         t))
1557                     ;; New article; we don't expire it.
1558                     (forward-line 1)
1559                   ;; Old article.  Schedule it for possible nuking.
1560                   (while (not (eolp))
1561                     (setq sym (let ((obarray expiry-hashtb) s)
1562                                 (setq s (read (current-buffer)))
1563                                 (if (stringp s) (intern s) s)))
1564                     (if (boundp sym)
1565                         (set sym (cons (cons (read (current-buffer)) (point))
1566                                        (symbol-value sym)))
1567                       (set sym (list (cons (read (current-buffer)) (point)))))
1568                     (skip-chars-forward " "))
1569                   (forward-line 1)))
1570               ;; We now have all articles that can possibly be expired.
1571               (mapatoms
1572                (lambda (sym)
1573                  (setq group (symbol-name sym)
1574                        articles (sort (symbol-value sym) 'car-less-than-car)
1575                        low (car (gnus-active group))
1576                        info (gnus-get-info group)
1577                        unreads (ignore-errors
1578                                  (gnus-list-of-unread-articles group))
1579                        marked (nconc
1580                                (gnus-uncompress-range
1581                                 (cdr (assq 'tick (gnus-info-marks info))))
1582                                (gnus-uncompress-range
1583                                 (cdr (assq 'dormant
1584                                            (gnus-info-marks info)))))
1585                        nov-file (gnus-agent-article-name ".overview" group)
1586                        lowest nil
1587                        highest nil)
1588                  (gnus-agent-load-alist group)
1589                  (gnus-message 5 "Expiring articles in %s" group)
1590                  (set-buffer overview)
1591                  (erase-buffer)
1592                  (when (file-exists-p nov-file)
1593                    (nnheader-insert-file-contents nov-file))
1594                  (goto-char (point-min))
1595                  (setq article 0)
1596                  (while (setq elem (pop articles))
1597                    (setq article (car elem))
1598                    (when (or (null low)
1599                              (< article low)
1600                              gnus-agent-expire-all
1601                              (and (not (memq article unreads))
1602                                   (not (memq article marked))))
1603                      ;; Find and nuke the NOV line.
1604                      (while (and (not (eobp))
1605                                  (or (not (numberp
1606                                            (setq art (read (current-buffer)))))
1607                                      (< art article)))
1608                        (if (and (numberp art)
1609                                 (file-exists-p
1610                                  (gnus-agent-article-name
1611                                   (number-to-string art) group)))
1612                            (progn
1613                              (unless lowest
1614                                (setq lowest art))
1615                              (setq highest art)
1616                              (forward-line 1))
1617                          ;; Remove old NOV lines that have no articles.
1618                          (gnus-delete-line)))
1619                      (if (or (eobp)
1620                              (/= art article))
1621                          (beginning-of-line)
1622                        (gnus-delete-line))
1623                      ;; Nuke the article.
1624                      (when (file-exists-p
1625                             (setq file (gnus-agent-article-name
1626                                         (number-to-string article)
1627                                         group)))
1628                        (delete-file file))
1629                      ;; Schedule the history line for nuking.
1630                      (push (cdr elem) histories)))
1631                  (gnus-make-directory (file-name-directory nov-file))
1632                  (let ((coding-system-for-write
1633                         gnus-agent-file-coding-system))
1634                    (write-region (point-min) (point-max) nov-file nil 'silent))
1635                  ;; Delete the unwanted entries in the alist.
1636                  (setq gnus-agent-article-alist
1637                        (sort gnus-agent-article-alist 'car-less-than-car))
1638                  (let* ((alist gnus-agent-article-alist)
1639                         (prev (cons nil alist))
1640                         (first prev)
1641                         expired)
1642                    (while (and alist
1643                                (<= (caar alist) article))
1644                      (if (or (not (cdar alist))
1645                              (not (file-exists-p
1646                                    (gnus-agent-article-name
1647                                     (number-to-string
1648                                      (caar alist))
1649                                     group))))
1650                          (progn
1651                            (push (caar alist) expired)
1652                            (setcdr prev (setq alist (cdr alist))))
1653                        (setq prev alist
1654                              alist (cdr alist))))
1655                    (setq gnus-agent-article-alist (cdr first))
1656                    (gnus-agent-save-alist group)
1657                    ;; Mark all articles up to the first article
1658                    ;; in `gnus-article-alist' as read.
1659                    (when (and info (caar gnus-agent-article-alist))
1660                      (setcar (nthcdr 2 info)
1661                              (gnus-range-add
1662                               (nth 2 info)
1663                               (cons 1 (- (caar gnus-agent-article-alist) 1)))))
1664                    ;; Maybe everything has been expired from `gnus-article-alist'
1665                    ;; and so the above marking as read could not be conducted,
1666                    ;; or there are expired article within the range of the alist.
1667                    (when (and info
1668                               expired
1669                               (or (not (caar gnus-agent-article-alist))
1670                                   (> (car expired)
1671                                      (caar gnus-agent-article-alist))))
1672                      (setcar (nthcdr 2 info)
1673                              (gnus-add-to-range
1674                               (nth 2 info)
1675                               (nreverse expired))))
1676                    (gnus-dribble-enter
1677                     (concat "(gnus-group-set-info '"
1678                             (gnus-prin1-to-string info)
1679                             ")")))
1680                  (when lowest
1681                    (if (gnus-gethash group orig)
1682                        (setcar (gnus-gethash group orig) lowest)
1683                      (gnus-sethash group (cons lowest highest) orig))))
1684                expiry-hashtb)
1685               (set-buffer history)
1686               (setq histories (nreverse (sort histories '<)))
1687               (while histories
1688                 (goto-char (pop histories))
1689                 (gnus-delete-line))
1690               (gnus-agent-save-history)
1691               (gnus-agent-close-history)
1692               (gnus-write-active-file
1693                (gnus-agent-lib-file "active") orig))
1694             (gnus-message 4 "Expiry...done")))))))
1695
1696 ;;;###autoload
1697 (defun gnus-agent-batch ()
1698   (interactive)
1699   (let ((init-file-user "")
1700         (gnus-always-read-dribble-file t))
1701     (gnus))
1702   (gnus-group-send-drafts)
1703   (gnus-agent-fetch-session))
1704
1705 (provide 'gnus-agent)
1706
1707 ;;; gnus-agent.el ends here