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