9df7c0f5de4dfab9d3014f4b7951c47d9ff4ca5f
[gnus] / lisp / nnfolder.el
1 ;;; nnfolder.el --- mail folder access for Gnus
2 ;; Copyright (C) 1995-2000 Free Software Foundation, Inc.
3
4 ;; Author: Scott Byer <byer@mv.us.adobe.com>
5 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
7 ;; Keywords: mail
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30 (require 'nnheader)
31 (require 'message)
32 (require 'nnmail)
33 (require 'nnoo)
34 (eval-when-compile (require 'cl))
35 (require 'gnus-util)
36
37 (nnoo-declare nnfolder)
38
39 (defvoo nnfolder-directory (expand-file-name message-directory)
40   "The name of the nnfolder directory.")
41
42 (defvoo nnfolder-active-file
43     (nnheader-concat nnfolder-directory "active")
44   "The name of the active file.")
45
46 ;; I renamed this variable to something more in keeping with the general GNU
47 ;; style. -SLB
48
49 (defvoo nnfolder-ignore-active-file nil
50   "If non-nil, the active file is ignores.
51 This causes nnfolder to do some extra work in order to determine the
52 true active ranges of an mbox file.  Note that the active file is
53 still saved, but it's values are not used.  This costs some extra time
54 when scanning an mbox when opening it.")
55
56 (defvoo nnfolder-distrust-mbox nil
57   "If non-nil, the folder will be distrusted.
58 This means that nnfolder will not trust the user with respect to
59 inserting unaccounted for mail in the middle of an mbox file.  This
60 can greatly slow down scans, which now must scan the entire file for
61 unmarked messages.  When nil, scans occur forward from the last marked
62 message, a huge time saver for large mailboxes.")
63
64 (defvoo nnfolder-newsgroups-file
65     (concat (file-name-as-directory nnfolder-directory) "newsgroups")
66   "Mail newsgroups description file.")
67
68 (defvoo nnfolder-get-new-mail t
69   "If non-nil, nnfolder will check the incoming mail file and split the mail.")
70
71 (defvoo nnfolder-prepare-save-mail-hook nil
72   "Hook run narrowed to an article before saving.")
73
74 (defvoo nnfolder-save-buffer-hook nil
75   "Hook run before saving the nnfolder mbox buffer.")
76
77 (defvoo nnfolder-inhibit-expiry nil
78   "If non-nil, inhibit expiry.")
79
80 \f
81
82 (defconst nnfolder-version "nnfolder 1.0"
83   "nnfolder version.")
84
85 (defconst nnfolder-article-marker "X-Gnus-Article-Number: "
86   "String used to demarcate what the article number for a message is.")
87
88 (defvoo nnfolder-current-group nil)
89 (defvoo nnfolder-current-buffer nil)
90 (defvoo nnfolder-status-string "")
91 (defvoo nnfolder-group-alist nil)
92 (defvoo nnfolder-buffer-alist nil)
93 (defvoo nnfolder-scantime-alist nil)
94 (defvoo nnfolder-active-timestamp nil)
95 (defvoo nnfolder-active-file-coding-system mm-text-coding-system)
96 (defvoo nnfolder-active-file-coding-system-for-write 
97     nnmail-active-file-coding-system)
98 (defvoo nnfolder-file-coding-system mm-text-coding-system)
99 (defvoo nnfolder-file-coding-system-for-write nnheader-file-coding-system
100   "Coding system for save nnfolder file.
101 If NIL, NNFOLDER-FILE-CODING-SYSTEM is used.")
102
103 \f
104
105 ;;; Interface functions
106
107 (nnoo-define-basics nnfolder)
108
109 (deffoo nnfolder-retrieve-headers (articles &optional group server fetch-old)
110   (save-excursion
111     (set-buffer nntp-server-buffer)
112     (erase-buffer)
113     (let (article start stop)
114       (nnfolder-possibly-change-group group server)
115       (when nnfolder-current-buffer
116         (set-buffer nnfolder-current-buffer)
117         (goto-char (point-min))
118         (if (stringp (car articles))
119             'headers
120           (while (setq article (pop articles))
121             (set-buffer nnfolder-current-buffer)
122             (when (nnfolder-goto-article article)
123               (setq start (point))
124               (setq stop (if (search-forward "\n\n" nil t)
125                              (1- (point))
126                            (point-max)))
127               (set-buffer nntp-server-buffer)
128               (insert (format "221 %d Article retrieved.\n" article))
129               (insert-buffer-substring nnfolder-current-buffer start stop)
130               (goto-char (point-max))
131               (insert ".\n")))
132
133           (set-buffer nntp-server-buffer)
134           (nnheader-fold-continuation-lines)
135           'headers)))))
136
137 (deffoo nnfolder-open-server (server &optional defs)
138   (nnoo-change-server 'nnfolder server defs)
139   (nnmail-activate 'nnfolder t)
140   (gnus-make-directory nnfolder-directory)
141   (cond
142    ((not (file-exists-p nnfolder-directory))
143     (nnfolder-close-server)
144     (nnheader-report 'nnfolder "Couldn't create directory: %s"
145                      nnfolder-directory))
146    ((not (file-directory-p (file-truename nnfolder-directory)))
147     (nnfolder-close-server)
148     (nnheader-report 'nnfolder "Not a directory: %s" nnfolder-directory))
149    (t
150     (nnmail-activate 'nnfolder)
151     (nnheader-report 'nnfolder "Opened server %s using directory %s"
152                      server nnfolder-directory)
153     t)))
154
155 (deffoo nnfolder-request-close ()
156   (let ((alist nnfolder-buffer-alist))
157     (while alist
158       (nnfolder-close-group (caar alist) nil t)
159       (setq alist (cdr alist))))
160   (nnoo-close-server 'nnfolder)
161   (setq nnfolder-buffer-alist nil
162         nnfolder-group-alist nil))
163
164 (deffoo nnfolder-request-article (article &optional group server buffer)
165   (nnfolder-possibly-change-group group server)
166   (save-excursion
167     (set-buffer nnfolder-current-buffer)
168     (goto-char (point-min))
169     (when (nnfolder-goto-article article)
170       (let (start stop)
171         (setq start (point))
172         (forward-line 1)
173         (unless (and (nnmail-search-unix-mail-delim)
174                      (forward-line -1))
175           (goto-char (point-max)))
176         (setq stop (point))
177         (let ((nntp-server-buffer (or buffer nntp-server-buffer)))
178           (set-buffer nntp-server-buffer)
179           (erase-buffer)
180           (insert-buffer-substring nnfolder-current-buffer start stop)
181           (goto-char (point-min))
182           (while (looking-at "From ")
183             (delete-char 5)
184             (insert "X-From-Line: ")
185             (forward-line 1))
186           (if (numberp article)
187               (cons nnfolder-current-group article)
188             (goto-char (point-min))
189             (cons nnfolder-current-group
190                   (if (search-forward (concat "\n" nnfolder-article-marker) 
191                                       nil t)
192                       (string-to-int
193                        (buffer-substring
194                         (point) (progn (end-of-line) (point))))
195                     -1))))))))
196
197 (deffoo nnfolder-request-group (group &optional server dont-check)
198   (nnfolder-possibly-change-group group server t)
199   (save-excursion
200     (if (not (assoc group nnfolder-group-alist))
201         (nnheader-report 'nnfolder "No such group: %s" group)
202       (if dont-check
203           (progn
204             (nnheader-report 'nnfolder "Selected group %s" group)
205             t)
206         (let* ((active (assoc group nnfolder-group-alist))
207                (group (car active))
208                (range (cadr active)))
209           (cond
210            ((null active)
211             (nnheader-report 'nnfolder "No such group: %s" group))
212            ((null nnfolder-current-group)
213             (nnheader-report 'nnfolder "Empty group: %s" group))
214            (t
215             (nnheader-report 'nnfolder "Selected group %s" group)
216             (nnheader-insert "211 %d %d %d %s\n"
217                              (1+ (- (cdr range) (car range)))
218                              (car range) (cdr range) group))))))))
219
220 (deffoo nnfolder-request-scan (&optional group server)
221   (nnfolder-possibly-change-group nil server)
222   (when nnfolder-get-new-mail
223     (nnfolder-possibly-change-group group server)
224     (nnmail-get-new-mail
225      'nnfolder
226      (lambda ()
227        (let ((bufs nnfolder-buffer-alist))
228          (save-excursion
229            (while bufs
230              (if (not (gnus-buffer-live-p (nth 1 (car bufs))))
231                  (setq nnfolder-buffer-alist
232                        (delq (car bufs) nnfolder-buffer-alist))
233                (set-buffer (nth 1 (car bufs)))
234                (nnfolder-save-buffer)
235                (kill-buffer (current-buffer)))
236              (setq bufs (cdr bufs))))))
237      nnfolder-directory
238      group)))
239
240 ;; Don't close the buffer if we're not shutting down the server.  This way,
241 ;; we can keep the buffer in the group buffer cache, and not have to grovel
242 ;; over the buffer again unless we add new mail to it or modify it in some
243 ;; way.
244
245 (deffoo nnfolder-close-group (group &optional server force)
246   ;; Make sure we _had_ the group open.
247   (when (or (assoc group nnfolder-buffer-alist)
248             (equal group nnfolder-current-group))
249     (let ((inf (assoc group nnfolder-buffer-alist)))
250       (when inf
251         (when (and nnfolder-current-group
252                    nnfolder-current-buffer)
253           (push (list nnfolder-current-group nnfolder-current-buffer)
254                 nnfolder-buffer-alist))
255         (setq nnfolder-buffer-alist
256               (delq inf nnfolder-buffer-alist))
257         (setq nnfolder-current-buffer (cadr inf)
258               nnfolder-current-group (car inf))))
259     (when (and nnfolder-current-buffer
260                (buffer-name nnfolder-current-buffer))
261       (save-excursion
262         (set-buffer nnfolder-current-buffer)
263         ;; If the buffer was modified, write the file out now.
264         (nnfolder-save-buffer)
265         ;; If we're shutting the server down, we need to kill the
266         ;; buffer and remove it from the open buffer list.  Or, of
267         ;; course, if we're trying to minimize our space impact.
268         (kill-buffer (current-buffer))
269         (setq nnfolder-buffer-alist (delq (assoc group nnfolder-buffer-alist)
270                                           nnfolder-buffer-alist)))))
271   (setq nnfolder-current-group nil
272         nnfolder-current-buffer nil)
273   t)
274
275 (deffoo nnfolder-request-create-group (group &optional server args)
276   (nnfolder-possibly-change-group nil server)
277   (nnmail-activate 'nnfolder)
278   (when group
279     (unless (assoc group nnfolder-group-alist)
280       (push (list group (cons 1 0)) nnfolder-group-alist)
281       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
282       (nnfolder-read-folder group)))
283   t)
284
285 (deffoo nnfolder-request-list (&optional server)
286   (nnfolder-possibly-change-group nil server)
287   (save-excursion
288     (let ((nnmail-file-coding-system nnfolder-active-file-coding-system))
289       (nnmail-find-file nnfolder-active-file)
290       (setq nnfolder-group-alist (nnmail-get-active)))
291     t))
292
293 (deffoo nnfolder-request-newgroups (date &optional server)
294   (nnfolder-possibly-change-group nil server)
295   (nnfolder-request-list server))
296
297 (deffoo nnfolder-request-list-newsgroups (&optional server)
298   (nnfolder-possibly-change-group nil server)
299   (save-excursion
300     (let ((nnmail-file-coding-system nnfolder-file-coding-system))
301       (nnmail-find-file nnfolder-newsgroups-file))))
302
303 ;; Return a list consisting of all article numbers existing in the
304 ;; current folder.
305
306 (defun nnfolder-existing-articles ()
307   (save-excursion
308     (when nnfolder-current-buffer
309       (set-buffer nnfolder-current-buffer)
310       (goto-char (point-min))
311       (let ((marker (concat "\n" nnfolder-article-marker))
312             (number "[0-9]+")
313             numbers)
314       
315         (while (and (search-forward marker nil t)
316                     (re-search-forward number nil t))
317           (let ((newnum (string-to-number (match-string 0))))
318             (if (nnmail-within-headers-p)
319                 (push newnum numbers))))
320         numbers))))
321
322 (deffoo nnfolder-request-expire-articles
323     (articles newsgroup &optional server force)
324   (nnfolder-possibly-change-group newsgroup server)
325   (let* ((is-old t)
326          ;; The articles we have deleted so far.
327          (deleted-articles nil)
328          ;; The articles that really exist and will
329          ;; be expired if they are old enough.
330          (maybe-expirable
331           (gnus-intersection articles (nnfolder-existing-articles))))
332     (nnmail-activate 'nnfolder)
333
334     (save-excursion
335       (set-buffer nnfolder-current-buffer)
336       ;; Since messages are sorted in arrival order and expired in the
337       ;; same order, we can stop as soon as we find a message that is
338       ;; too old.
339       (while (and maybe-expirable is-old)
340         (goto-char (point-min))
341         (when (and (nnfolder-goto-article (car maybe-expirable))
342                    (search-forward (concat "\n" nnfolder-article-marker)
343                                    nil t))
344           (forward-sexp)
345           (when (setq is-old
346                       (nnmail-expired-article-p
347                        newsgroup
348                        (buffer-substring
349                         (point) (progn (end-of-line) (point)))
350                        force nnfolder-inhibit-expiry))
351             (nnheader-message 5 "Deleting article %d..."
352                               (car maybe-expirable) newsgroup)
353             (nnfolder-delete-mail)
354             ;; Must remember which articles were actually deleted
355             (push (car maybe-expirable) deleted-articles)))
356         (setq maybe-expirable (cdr maybe-expirable)))
357       (unless nnfolder-inhibit-expiry
358         (nnheader-message 5 "Deleting articles...done"))
359       (nnfolder-save-buffer)
360       (nnfolder-adjust-min-active newsgroup)
361       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
362       (gnus-sorted-complement articles (nreverse deleted-articles)))))
363
364 (deffoo nnfolder-request-move-article (article group server
365                                                accept-form &optional last)
366   (save-excursion
367     (let ((buf (get-buffer-create " *nnfolder move*"))
368           result)
369       (and
370        (nnfolder-request-article article group server)
371        (save-excursion
372          (set-buffer buf)
373          (erase-buffer)
374          (insert-buffer-substring nntp-server-buffer)
375          (goto-char (point-min))
376          (while (re-search-forward
377                  (concat "^" nnfolder-article-marker)
378                  (save-excursion (and (search-forward "\n\n" nil t) (point))) 
379                  t)
380            (delete-region (progn (beginning-of-line) (point))
381                           (progn (forward-line 1) (point))))
382          (setq result (eval accept-form))
383          (kill-buffer buf)
384          result)
385        (save-excursion
386          (nnfolder-possibly-change-group group server)
387          (set-buffer nnfolder-current-buffer)
388          (goto-char (point-min))
389          (when (nnfolder-goto-article article)
390            (nnfolder-delete-mail))
391          (when last
392            (nnfolder-save-buffer)
393            (nnfolder-adjust-min-active group)
394            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))))
395       result)))
396
397 (deffoo nnfolder-request-accept-article (group &optional server last)
398   (save-excursion
399     (nnfolder-possibly-change-group group server)
400     (nnmail-check-syntax)
401     (let ((buf (current-buffer))
402           result art-group)
403       (goto-char (point-min))
404       (when (looking-at "X-From-Line: ")
405         (replace-match "From "))
406       (and
407        (nnfolder-request-list)
408        (save-excursion
409          (set-buffer buf)
410          (goto-char (point-min))
411          (if (search-forward "\n\n" nil t)
412              (forward-line -1)
413            (goto-char (point-max)))
414          (while (re-search-backward (concat "^" nnfolder-article-marker) nil t)
415            (delete-region (point) (progn (forward-line 1) (point))))
416          (when nnmail-cache-accepted-message-ids
417            (nnmail-cache-insert (nnmail-fetch-field "message-id")))
418          (setq result (if (stringp group)
419                           (list (cons group (nnfolder-active-number group)))
420                         (setq art-group
421                               (nnmail-article-group 'nnfolder-active-number))))
422          (if (and (null result)
423                   (yes-or-no-p "Moved to `junk' group; delete article? "))
424              (setq result 'junk)
425            (setq result
426                  (car (nnfolder-save-mail result)))))
427        (when last
428          (save-excursion
429            (nnfolder-possibly-change-folder (or (caar art-group) group))
430            (nnfolder-save-buffer)
431            (when nnmail-cache-accepted-message-ids
432              (nnmail-cache-close)))))
433       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
434       (unless result
435         (nnheader-report 'nnfolder "Couldn't store article"))
436       result)))
437
438 (deffoo nnfolder-request-replace-article (article group buffer)
439   (nnfolder-possibly-change-group group)
440   (save-excursion
441     (set-buffer buffer)
442     (goto-char (point-min))
443     (let (xfrom)
444       (while (re-search-forward "^X-From-Line: \\(.*\\)$" nil t)
445         (setq xfrom (match-string 1))
446         (gnus-delete-line))
447       (goto-char (point-min))
448       (if xfrom
449           (insert "From " xfrom "\n")
450         (unless (looking-at "From ")
451           (insert "From nobody " (current-time-string) "\n"))))
452     (nnfolder-normalize-buffer)
453     (set-buffer nnfolder-current-buffer)
454     (goto-char (point-min))
455     (if (not (nnfolder-goto-article article))
456         nil
457       (nnfolder-delete-mail)
458       (insert-buffer-substring buffer)
459       (nnfolder-save-buffer)
460       t)))
461
462 (deffoo nnfolder-request-delete-group (group &optional force server)
463   (nnfolder-close-group group server t)
464   ;; Delete all articles in GROUP.
465   (if (not force)
466       ()                                ; Don't delete the articles.
467     ;; Delete the file that holds the group.
468     (ignore-errors
469       (delete-file (nnfolder-group-pathname group))))
470   ;; Remove the group from all structures.
471   (setq nnfolder-group-alist
472         (delq (assoc group nnfolder-group-alist) nnfolder-group-alist)
473         nnfolder-current-group nil
474         nnfolder-current-buffer nil)
475   ;; Save the active file.
476   (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
477   t)
478
479 (deffoo nnfolder-request-rename-group (group new-name &optional server)
480   (nnfolder-possibly-change-group group server)
481   (save-excursion
482     (set-buffer nnfolder-current-buffer)
483     (and (file-writable-p buffer-file-name)
484          (ignore-errors
485            (rename-file
486             buffer-file-name
487             (let ((new-file (nnfolder-group-pathname new-name)))
488               (gnus-make-directory (file-name-directory new-file))
489               new-file))
490            t)
491          ;; That went ok, so we change the internal structures.
492          (let ((entry (assoc group nnfolder-group-alist)))
493            (and entry (setcar entry new-name))
494            (setq nnfolder-current-buffer nil
495                  nnfolder-current-group nil)
496            ;; Save the new group alist.
497            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
498            ;; We kill the buffer instead of renaming it and stuff.
499            (kill-buffer (current-buffer))
500            t))))
501
502 (defun nnfolder-request-regenerate (server)
503   (nnfolder-possibly-change-group nil server)
504   (nnfolder-generate-active-file)
505   t)
506
507 \f
508 ;;; Internal functions.
509
510 (defun nnfolder-adjust-min-active (group)
511   ;; Find the lowest active article in this group.
512   (let* ((active (cadr (assoc group nnfolder-group-alist)))
513          (marker (concat "\n" nnfolder-article-marker))
514          (number "[0-9]+")
515          (activemin (cdr active)))
516     (save-excursion
517       (set-buffer nnfolder-current-buffer)
518       (goto-char (point-min))
519       (while (and (search-forward marker nil t)
520                   (re-search-forward number nil t))
521         (let ((newnum (string-to-number (match-string 0))))
522           (if (nnmail-within-headers-p)
523               (setq activemin (min activemin newnum)))))
524       (setcar active activemin))))
525
526 (defun nnfolder-article-string (article)
527   (if (numberp article)
528       (concat "\n" nnfolder-article-marker (int-to-string article) " ")
529     (concat "\nMessage-ID: " article)))
530
531 (defun nnfolder-goto-article (article)
532   "Place point at the start of the headers of ARTICLE.
533 ARTICLE can be an article number or a Message-ID.
534 Returns t if successful, nil otherwise."
535   (let ((art-string (nnfolder-article-string article))
536         start found)
537     ;; It is likely that we are at or before the delimiter line.
538     ;; We therefore go to the end of the previous line, and start
539     ;; searching from there.
540     (beginning-of-line)
541     (unless (bobp)
542       (forward-char -1))
543     (setq start (point))
544     ;; First search forward.
545     (while (and (setq found (search-forward art-string nil t))
546                 (not (nnmail-within-headers-p))))
547     ;; If unsuccessful, search backward from where we started,
548     (unless found
549       (goto-char start)
550       (while (and (setq found (search-backward art-string nil t))
551                   (not (nnmail-within-headers-p)))))
552     (when found
553       (nnmail-search-unix-mail-delim-backward))))
554
555 (defun nnfolder-delete-mail (&optional leave-delim)
556   "Delete the message that point is in.
557 If optional argument LEAVE-DELIM is t, then mailbox delimiter is not
558 deleted.  Point is left where the deleted region was."
559   (save-restriction
560     (narrow-to-region
561      (save-excursion
562        ;; In case point is at the beginning of the message already.
563        (forward-line 1)
564        (nnmail-search-unix-mail-delim-backward)
565        (if leave-delim (progn (forward-line 1) (point))
566          (point)))
567      (progn
568        (forward-line 1)
569        (if (nnmail-search-unix-mail-delim)
570            (point)
571          (point-max))))
572     (run-hooks 'nnfolder-delete-mail-hook)
573     (delete-region (point-min) (point-max))))
574
575 (defun nnfolder-possibly-change-group (group &optional server dont-check)
576   ;; Change servers.
577   (when (and server
578              (not (nnfolder-server-opened server)))
579     (nnfolder-open-server server))
580   (unless (gnus-buffer-live-p nnfolder-current-buffer)
581     (setq nnfolder-current-buffer nil
582           nnfolder-current-group nil))
583   ;; Change group.
584   (when (and group
585              (not (equal group nnfolder-current-group)))
586     (let ((pathname-coding-system nnmail-pathname-coding-system))
587       (nnmail-activate 'nnfolder)
588       (when (and (not (assoc group nnfolder-group-alist))
589                  (not (file-exists-p
590                        (nnfolder-group-pathname group))))
591         ;; The group doesn't exist, so we create a new entry for it.
592         (push (list group (cons 1 0)) nnfolder-group-alist)
593         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
594
595       (if dont-check
596           (setq nnfolder-current-group group
597                 nnfolder-current-buffer nil)
598         (let (inf file)
599           ;; If we have to change groups, see if we don't already have the
600           ;; folder in memory.  If we do, verify the modtime and destroy
601           ;; the folder if needed so we can rescan it.
602           (setq nnfolder-current-buffer
603                 (nth 1 (assoc group nnfolder-buffer-alist)))
604
605           ;; If the buffer is not live, make sure it isn't in the alist.  If it
606           ;; is live, verify that nobody else has touched the file since last
607           ;; time.
608           (when (and nnfolder-current-buffer
609                      (not (gnus-buffer-live-p nnfolder-current-buffer)))
610             (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)
611                   nnfolder-current-buffer nil))
612
613           (setq nnfolder-current-group group)
614
615           (when (or (not nnfolder-current-buffer)
616                     (not (verify-visited-file-modtime
617                           nnfolder-current-buffer)))
618             (save-excursion
619               (setq file (nnfolder-group-pathname group))
620               ;; See whether we need to create the new file.
621               (unless (file-exists-p file)
622                 (gnus-make-directory (file-name-directory file))
623                 (let ((nnmail-file-coding-system 
624                        (or nnfolder-file-coding-system-for-write
625                            nnfolder-file-coding-system-for-write)))
626                   (nnmail-write-region 1 1 file t 'nomesg)))
627               (when (setq nnfolder-current-buffer (nnfolder-read-folder group))
628                 (set-buffer nnfolder-current-buffer)
629                 (push (list group nnfolder-current-buffer)
630                       nnfolder-buffer-alist)))))))))
631
632 (defun nnfolder-save-mail (group-art-list)
633   "Called narrowed to an article."
634   (let* (save-list group-art)
635     (goto-char (point-min))
636     ;; The From line may have been quoted by movemail.
637     (when (looking-at ">From")
638       (delete-char 1))
639     ;; This might come from somewhere else.
640     (unless (looking-at "From ")
641       (insert "From nobody " (current-time-string) "\n")
642       (goto-char (point-min)))
643     ;; Quote all "From " lines in the article.
644     (forward-line 1)
645     (let (case-fold-search)
646       (while (re-search-forward "^From " nil t)
647         (beginning-of-line)
648         (insert "> ")))
649     (setq save-list group-art-list)
650     (nnmail-insert-lines)
651     (nnmail-insert-xref group-art-list)
652     (run-hooks 'nnmail-prepare-save-mail-hook)
653     (run-hooks 'nnfolder-prepare-save-mail-hook)
654
655     ;; Insert the mail into each of the destination groups.
656     (while (setq group-art (pop group-art-list))
657       ;; Kill any previous newsgroup markers.
658       (goto-char (point-min))
659       (if (search-forward "\n\n" nil t)
660           (forward-line -1)
661         (goto-char (point-max)))
662       (while (search-backward (concat "\n" nnfolder-article-marker) nil t)
663         (delete-region (1+ (point)) (progn (forward-line 2) (point))))
664
665       ;; Insert the new newsgroup marker.
666       (nnfolder-insert-newsgroup-line group-art)
667
668       (save-excursion
669         (let ((beg (point-min))
670               (end (point-max))
671               (obuf (current-buffer)))
672           (nnfolder-possibly-change-folder (car group-art))
673           (let ((buffer-read-only nil))
674             (nnfolder-normalize-buffer)
675             (insert-buffer-substring obuf beg end)))))
676
677     ;; Did we save it anywhere?
678     save-list))
679
680 (defun nnfolder-normalize-buffer ()
681   "Make sure there are two newlines at the end of the buffer."
682   (goto-char (point-max))
683   (skip-chars-backward "\n")
684   (delete-region (point) (point-max))
685   (insert "\n\n"))
686
687 (defun nnfolder-insert-newsgroup-line (group-art)
688   (save-excursion
689     (goto-char (point-min))
690     (unless (search-forward "\n\n" nil t)
691       (goto-char (point-max))
692       (insert "\n"))
693     (forward-char -1)
694     (insert (format (concat nnfolder-article-marker "%d   %s\n")
695                     (cdr group-art) (current-time-string)))))
696
697 (defun nnfolder-active-number (group)
698   ;; Find the next article number in GROUP.
699   (let ((active (cadr (assoc group nnfolder-group-alist))))
700     (if active
701         (setcdr active (1+ (cdr active)))
702       ;; This group is new, so we create a new entry for it.
703       ;; This might be a bit naughty... creating groups on the drop of
704       ;; a hat, but I don't know...
705       (push (list group (setq active (cons 1 1)))
706             nnfolder-group-alist))
707     (cdr active)))
708
709 (defun nnfolder-possibly-change-folder (group)
710   (let ((inf (assoc group nnfolder-buffer-alist)))
711     (if (and inf
712              (gnus-buffer-live-p (cadr inf)))
713         (set-buffer (cadr inf))
714       (when inf
715         (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)))
716       (when nnfolder-group-alist
717         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
718       (push (list group (nnfolder-read-folder group))
719             nnfolder-buffer-alist))))
720
721 ;; This method has a problem if you've accidentally let the active list get
722 ;; out of sync with the files.  This could happen, say, if you've
723 ;; accidentally gotten new mail with something other than Gnus (but why
724 ;; would _that_ ever happen? :-).  In that case, we will be in the middle of
725 ;; processing the file, ready to add new X-Gnus article number markers, and
726 ;; we'll run across a message with no ID yet - the active list _may_not_ be
727 ;; ready for us yet.
728
729 ;; To handle this, I'm modifying this routine to maintain the maximum ID seen
730 ;; so far, and when we hit a message with no ID, we will _manually_ scan the
731 ;; rest of the message looking for any more, possibly higher IDs.  We'll
732 ;; assume the maximum that we find is the highest active.  Note that this
733 ;; shouldn't cost us much extra time at all, but will be a lot less
734 ;; vulnerable to glitches between the mbox and the active file.
735
736 (defun nnfolder-read-folder (group)
737   (let* ((file (nnfolder-group-pathname group))
738          (buffer (set-buffer
739                   (let ((nnheader-file-coding-system 
740                          nnfolder-file-coding-system))
741                     (nnheader-find-file-noselect file)))))
742     (if (equal (cadr (assoc group nnfolder-scantime-alist))
743                (nth 5 (file-attributes file)))
744         ;; This looks up-to-date, so we don't do any scanning.
745         (if (file-exists-p file)
746             buffer
747           (push (list group buffer) nnfolder-buffer-alist)
748           (set-buffer-modified-p t)
749           (nnfolder-save-buffer))
750       ;; Parse the damn thing.
751       (save-excursion
752         (goto-char (point-min))
753         ;; Remove any blank lines at the start.
754         (while (eq (following-char) ?\n)
755           (delete-char 1))
756         (nnmail-activate 'nnfolder)
757         ;; Read in the file.
758         (let ((delim "^From ")
759               (marker (concat "\n" nnfolder-article-marker))
760               (number "[0-9]+")
761               (active (or (cadr (assoc group nnfolder-group-alist))
762                           (cons 1 0)))
763               (scantime (assoc group nnfolder-scantime-alist))
764               (minid (lsh -1 -1))
765               maxid start end newscantime
766               buffer-read-only)
767           (buffer-disable-undo)
768           (setq maxid (cdr active))
769           (goto-char (point-min))
770
771           ;; Anytime the active number is 1 or 0, it is suspect.  In that
772           ;; case, search the file manually to find the active number.  Or,
773           ;; of course, if we're being paranoid.  (This would also be the
774           ;; place to build other lists from the header markers, such as
775           ;; expunge lists, etc., if we ever desired to abandon the active
776           ;; file entirely for mboxes.)
777           (when (or nnfolder-ignore-active-file
778                     (< maxid 2))
779             (while (and (search-forward marker nil t)
780                         (re-search-forward number nil t))
781               (let ((newnum (string-to-number (match-string 0))))
782                 (if (nnmail-within-headers-p)
783                     (setq maxid (max maxid newnum)
784                           minid (min minid newnum)))))
785             (setcar active (max 1 (min minid maxid)))
786             (setcdr active (max maxid (cdr active)))
787             (goto-char (point-min)))
788
789           ;; As long as we trust that the user will only insert unmarked mail
790           ;; at the end, go to the end and search backwards for the last
791           ;; marker.  Find the start of that message, and begin to search for
792           ;; unmarked messages from there.
793           (when (not (or nnfolder-distrust-mbox
794                          (< maxid 2)))
795             (goto-char (point-max))
796             (unless (re-search-backward marker nil t)
797               (goto-char (point-min)))
798             (when (nnmail-search-unix-mail-delim)
799               (goto-char (point-min))))
800
801           ;; Keep track of the active number on our own, and insert it back
802           ;; into the active list when we're done.  Also, prime the pump to
803           ;; cut down on the number of searches we do.
804           (unless (nnmail-search-unix-mail-delim)
805             (goto-char (point-max)))
806           (setq end (point-marker))
807           (while (not (= end (point-max)))
808             (setq start (marker-position end))
809             (goto-char end)
810             ;; There may be more than one "From " line, so we skip past
811             ;; them.
812             (while (looking-at delim)
813               (forward-line 1))
814             (set-marker end (if (nnmail-search-unix-mail-delim)
815                                 (point)
816                               (point-max)))
817             (goto-char start)
818             (when (not (search-forward marker end t))
819               (narrow-to-region start end)
820               (nnmail-insert-lines)
821               (nnfolder-insert-newsgroup-line
822                (cons nil (nnfolder-active-number nnfolder-current-group)))
823               (widen)))
824
825           (set-marker end nil)
826           ;; Make absolutely sure that the active list reflects reality!
827           (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
828           ;; Set the scantime for this group.
829           (setq newscantime (visited-file-modtime))
830           (if scantime
831               (setcdr scantime (list newscantime))
832             (push (list nnfolder-current-group newscantime)
833                   nnfolder-scantime-alist))
834           (current-buffer))))))
835
836 ;;;###autoload
837 (defun nnfolder-generate-active-file ()
838   "Look for mbox folders in the nnfolder directory and make them into groups.
839 This command does not work if you use short group names."
840   (interactive)
841   (nnmail-activate 'nnfolder)
842   (let ((files (directory-files nnfolder-directory))
843         file)
844     (while (setq file (pop files))
845       (when (and (not (backup-file-name-p file))
846                  (message-mail-file-mbox-p
847                   (nnheader-concat nnfolder-directory file)))
848         (let ((oldgroup (assoc file nnfolder-group-alist)))
849           (if oldgroup
850               (nnheader-message 5 "Refreshing group %s..." file)
851             (nnheader-message 5 "Adding group %s..." file))
852           (if oldgroup
853               (setq nnfolder-group-alist
854                     (delq oldgroup (copy-sequence nnfolder-group-alist))))
855           (push (list file (cons 1 0)) nnfolder-group-alist)
856           (nnfolder-possibly-change-folder file)
857           (nnfolder-possibly-change-group file)
858           (nnfolder-close-group file))))
859     (nnheader-message 5 "")))
860
861 (defun nnfolder-group-pathname (group)
862   "Make pathname for GROUP."
863   (setq group
864         (mm-encode-coding-string group nnmail-pathname-coding-system))
865   (let ((dir (file-name-as-directory (expand-file-name nnfolder-directory))))
866     ;; If this file exists, we use it directly.
867     (if (or nnmail-use-long-file-names
868             (file-exists-p (concat dir group)))
869         (concat dir group)
870       ;; If not, we translate dots into slashes.
871       (concat dir (nnheader-replace-chars-in-string group ?. ?/)))))
872
873 (defun nnfolder-save-buffer ()
874   "Save the buffer."
875   (when (buffer-modified-p)
876     (run-hooks 'nnfolder-save-buffer-hook)
877     (gnus-make-directory (file-name-directory (buffer-file-name)))
878     (let ((coding-system-for-write 
879            (or nnfolder-file-coding-system-for-write
880                nnfolder-file-coding-system)))
881       (save-buffer))))
882
883 (defun nnfolder-save-active (group-alist active-file)
884   (let ((nnmail-active-file-coding-system
885          (or nnfolder-active-file-coding-system-for-write
886              nnfolder-active-file-coding-system)))
887     (nnmail-save-active group-alist active-file)))
888
889 (provide 'nnfolder)
890
891 ;;; nnfolder.el ends here