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