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