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