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