ce3c20b720aab754f133b13633f95670576c54d5
[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       (and
453        (nnfolder-request-list)
454        (save-excursion
455          (set-buffer buf)
456          (goto-char (point-min))
457          (if (search-forward "\n\n" nil t)
458              (forward-line -1)
459            (goto-char (point-max)))
460          (while (re-search-backward (concat "^" nnfolder-article-marker) nil t)
461            (delete-region (point) (progn (forward-line 1) (point))))
462          (when nnmail-cache-accepted-message-ids
463            (nnmail-cache-insert (nnmail-fetch-field "message-id")))
464          (setq result (if (stringp group)
465                           (list (cons group (nnfolder-active-number group)))
466                         (setq art-group
467                               (nnmail-article-group 'nnfolder-active-number))))
468          (if (and (null result)
469                   (yes-or-no-p "Moved to `junk' group; delete article? "))
470              (setq result 'junk)
471            (setq result
472                  (car (nnfolder-save-mail result)))))
473        (when last
474          (save-excursion
475            (nnfolder-possibly-change-folder (or (caar art-group) group))
476            (nnfolder-save-buffer)
477            (when nnmail-cache-accepted-message-ids
478              (nnmail-cache-close)))))
479       (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
480       (unless result
481         (nnheader-report 'nnfolder "Couldn't store article"))
482       result)))
483
484 (deffoo nnfolder-request-replace-article (article group buffer)
485   (nnfolder-possibly-change-group group)
486   (save-excursion
487     (set-buffer buffer)
488     (goto-char (point-min))
489     (let (xfrom)
490       (while (re-search-forward "^X-From-Line: \\(.*\\)$" nil t)
491         (setq xfrom (match-string 1))
492         (gnus-delete-line))
493       (goto-char (point-min))
494       (if xfrom
495           (insert "From " xfrom "\n")
496         (unless (looking-at "From ")
497           (insert "From nobody " (current-time-string) "\n"))))
498     (nnfolder-normalize-buffer)
499     (set-buffer nnfolder-current-buffer)
500     (goto-char (point-min))
501     (if (not (nnfolder-goto-article article))
502         nil
503       (nnfolder-delete-mail)
504       (insert-buffer-substring buffer)
505       (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
506         (save-excursion
507           (set-buffer buffer)
508           (let ((headers (nnfolder-parse-head article 
509                                               (point-min) (point-max))))
510             (with-current-buffer (nnfolder-open-nov group)
511               (if (nnheader-find-nov-line article)
512                   (delete-region (point) (progn (forward-line 1) (point))))
513               (nnheader-insert-nov headers)))))
514       (nnfolder-save-buffer)
515       t)))
516
517 (deffoo nnfolder-request-delete-group (group &optional force server)
518   (nnfolder-close-group group server t)
519   ;; Delete all articles in GROUP.
520   (if (not force)
521       ()                                ; Don't delete the articles.
522     ;; Delete the file that holds the group.
523     (ignore-errors
524       (delete-file (nnfolder-group-pathname group))
525       (delete-file (nnfolder-group-nov-pathname group))))
526   ;; Remove the group from all structures.
527   (setq nnfolder-group-alist
528         (delq (assoc group nnfolder-group-alist) nnfolder-group-alist)
529         nnfolder-current-group nil
530         nnfolder-current-buffer nil)
531   ;; Save the active file.
532   (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
533   t)
534
535 (deffoo nnfolder-request-rename-group (group new-name &optional server)
536   (nnfolder-possibly-change-group group server)
537   (save-excursion
538     (set-buffer nnfolder-current-buffer)
539     (and (file-writable-p buffer-file-name)
540          (ignore-errors
541            (let ((new-file (nnfolder-group-pathname new-name)))
542              (gnus-make-directory (file-name-directory new-file))
543              (rename-file buffer-file-name new-file)
544              (setq new-file (nnfolder-group-nov-pathname new-name))
545              (rename-file (nnfolder-group-nov-pathname group)
546                           new-file))
547            t)
548          ;; That went ok, so we change the internal structures.
549          (let ((entry (assoc group nnfolder-group-alist)))
550            (and entry (setcar entry new-name))
551            (setq nnfolder-current-buffer nil
552                  nnfolder-current-group nil)
553            ;; Save the new group alist.
554            (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
555            ;; We kill the buffer instead of renaming it and stuff.
556            (kill-buffer (current-buffer))
557            t))))
558
559 (deffoo nnfolder-request-regenerate (server)
560   (nnfolder-possibly-change-group nil server)
561   (nnfolder-generate-active-file)
562   t)
563
564 \f
565 ;;; Internal functions.
566
567 (defun nnfolder-adjust-min-active (group)
568   ;; Find the lowest active article in this group.
569   (let* ((active (cadr (assoc group nnfolder-group-alist)))
570          (marker (concat "\n" nnfolder-article-marker))
571          (number "[0-9]+")
572          (activemin (cdr active)))
573     (save-excursion
574       (set-buffer nnfolder-current-buffer)
575       (goto-char (point-min))
576       (while (and (search-forward marker nil t)
577                   (re-search-forward number nil t))
578         (let ((newnum (string-to-number (match-string 0))))
579           (if (nnmail-within-headers-p)
580               (setq activemin (min activemin newnum)))))
581       (setcar active activemin))))
582
583 (defun nnfolder-article-string (article)
584   (if (numberp article)
585       (concat "\n" nnfolder-article-marker (int-to-string article) " ")
586     (concat "\nMessage-ID: " article)))
587
588 (defun nnfolder-goto-article (article)
589   "Place point at the start of the headers of ARTICLE.
590 ARTICLE can be an article number or a Message-ID.
591 Returns t if successful, nil otherwise."
592   (let ((art-string (nnfolder-article-string article))
593         start found)
594     ;; It is likely that we are at or before the delimiter line.
595     ;; We therefore go to the end of the previous line, and start
596     ;; searching from there.
597     (beginning-of-line)
598     (unless (bobp)
599       (forward-char -1))
600     (setq start (point))
601     ;; First search forward.
602     (while (and (setq found (search-forward art-string nil t))
603                 (not (nnmail-within-headers-p))))
604     ;; If unsuccessful, search backward from where we started,
605     (unless found
606       (goto-char start)
607       (while (and (setq found (search-backward art-string nil t))
608                   (not (nnmail-within-headers-p)))))
609     (when found
610       (nnmail-search-unix-mail-delim-backward))))
611
612 (defun nnfolder-delete-mail (&optional leave-delim)
613   "Delete the message that point is in.
614 If optional argument LEAVE-DELIM is t, then mailbox delimiter is not
615 deleted.  Point is left where the deleted region was."
616   (save-restriction
617     (narrow-to-region
618      (save-excursion
619        ;; In case point is at the beginning of the message already.
620        (forward-line 1)
621        (nnmail-search-unix-mail-delim-backward)
622        (if leave-delim (progn (forward-line 1) (point))
623          (point)))
624      (progn
625        (forward-line 1)
626        (if (nnmail-search-unix-mail-delim)
627            (point)
628          (point-max))))
629     (run-hooks 'nnfolder-delete-mail-hook)
630     (delete-region (point-min) (point-max))))
631
632 (defun nnfolder-possibly-change-group (group &optional server dont-check)
633   ;; Change servers.
634   (when (and server
635              (not (nnfolder-server-opened server)))
636     (nnfolder-open-server server))
637   (unless (gnus-buffer-live-p nnfolder-current-buffer)
638     (setq nnfolder-current-buffer nil
639           nnfolder-current-group nil))
640   ;; Change group.
641   (let ((file-name-coding-system nnmail-pathname-coding-system)
642         (pathname-coding-system nnmail-pathname-coding-system))
643     (when (and group
644                (not (equal group nnfolder-current-group))
645                (progn
646                  (nnmail-activate 'nnfolder)
647                  (and (assoc group nnfolder-group-alist)
648                       (file-exists-p (nnfolder-group-pathname group)))))
649       (if dont-check
650           (setq nnfolder-current-group group
651                 nnfolder-current-buffer nil)
652         (let (inf file)
653           ;; If we have to change groups, see if we don't already have the
654           ;; folder in memory.  If we do, verify the modtime and destroy
655           ;; the folder if needed so we can rescan it.
656           (setq nnfolder-current-buffer
657                 (nth 1 (assoc group nnfolder-buffer-alist)))
658
659           ;; If the buffer is not live, make sure it isn't in the alist.  If it
660           ;; is live, verify that nobody else has touched the file since last
661           ;; time.
662           (when (and nnfolder-current-buffer
663                      (not (gnus-buffer-live-p nnfolder-current-buffer)))
664             (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)
665                   nnfolder-current-buffer nil))
666
667           (setq nnfolder-current-group group)
668
669           (when (or (not nnfolder-current-buffer)
670                     (not (verify-visited-file-modtime
671                           nnfolder-current-buffer)))
672             (save-excursion
673               (setq file (nnfolder-group-pathname group))
674               ;; See whether we need to create the new file.
675               (unless (file-exists-p file)
676                 (gnus-make-directory (file-name-directory file))
677                 (let ((nnmail-file-coding-system 
678                        (or nnfolder-file-coding-system-for-write
679                            nnfolder-file-coding-system-for-write)))
680                   (nnmail-write-region 1 1 file t 'nomesg)))
681               (when (setq nnfolder-current-buffer (nnfolder-read-folder group))
682                 (set-buffer nnfolder-current-buffer)
683                 (push (list group nnfolder-current-buffer)
684                       nnfolder-buffer-alist)))))))))
685
686 (defun nnfolder-save-mail (group-art-list)
687   "Called narrowed to an article."
688   (let* (save-list group-art)
689     (goto-char (point-min))
690     ;; The From line may have been quoted by movemail.
691     (when (looking-at ">From")
692       (delete-char 1))
693     ;; This might come from somewhere else.
694     (unless (looking-at "From ")
695       (insert "From nobody " (current-time-string) "\n")
696       (goto-char (point-min)))
697     ;; Quote all "From " lines in the article.
698     (forward-line 1)
699     (let (case-fold-search)
700       (while (re-search-forward "^From " nil t)
701         (beginning-of-line)
702         (insert "> ")))
703     (setq save-list group-art-list)
704     (nnmail-insert-lines)
705     (nnmail-insert-xref group-art-list)
706     (run-hooks 'nnmail-prepare-save-mail-hook)
707     (run-hooks 'nnfolder-prepare-save-mail-hook)
708
709     ;; Insert the mail into each of the destination groups.
710     (while (setq group-art (pop group-art-list))
711       ;; Kill any previous newsgroup markers.
712       (goto-char (point-min))
713       (if (search-forward "\n\n" nil t)
714           (forward-line -1)
715         (goto-char (point-max)))
716       (while (search-backward (concat "\n" nnfolder-article-marker) nil t)
717         (delete-region (1+ (point)) (progn (forward-line 2) (point))))
718
719       ;; Insert the new newsgroup marker.
720       (nnfolder-insert-newsgroup-line group-art)
721
722       (save-excursion
723         (let ((beg (point-min))
724               (end (point-max))
725               (obuf (current-buffer)))
726           (nnfolder-possibly-change-folder (car group-art))
727           (let ((buffer-read-only nil))
728             (nnfolder-normalize-buffer)
729             (insert-buffer-substring obuf beg end))
730           (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
731             (set-buffer obuf)
732             (nnfolder-add-nov (car group-art) (cdr group-art)
733                               (nnfolder-parse-head nil beg end))))))
734
735     ;; Did we save it anywhere?
736     save-list))
737
738 (defun nnfolder-normalize-buffer ()
739   "Make sure there are two newlines at the end of the buffer."
740   (goto-char (point-max))
741   (skip-chars-backward "\n")
742   (delete-region (point) (point-max))
743   (insert "\n\n"))
744
745 (defun nnfolder-insert-newsgroup-line (group-art)
746   (save-excursion
747     (goto-char (point-min))
748     (unless (search-forward "\n\n" nil t)
749       (goto-char (point-max))
750       (insert "\n"))
751     (forward-char -1)
752     (insert (format (concat nnfolder-article-marker "%d   %s\n")
753                     (cdr group-art) (current-time-string)))))
754
755 (defun nnfolder-active-number (group)
756   ;; Find the next article number in GROUP.
757   (let ((active (cadr (assoc group nnfolder-group-alist))))
758     (if active
759         (setcdr active (1+ (cdr active)))
760       ;; This group is new, so we create a new entry for it.
761       ;; This might be a bit naughty... creating groups on the drop of
762       ;; a hat, but I don't know...
763       (push (list group (setq active (cons 1 1)))
764             nnfolder-group-alist))
765     (cdr active)))
766
767 (defun nnfolder-possibly-change-folder (group)
768   (let ((inf (assoc group nnfolder-buffer-alist)))
769     (if (and inf
770              (gnus-buffer-live-p (cadr inf)))
771         (set-buffer (cadr inf))
772       (when inf
773         (setq nnfolder-buffer-alist (delq inf nnfolder-buffer-alist)))
774       (when nnfolder-group-alist
775         (nnfolder-save-active nnfolder-group-alist nnfolder-active-file))
776       (push (list group (nnfolder-read-folder group))
777             nnfolder-buffer-alist))))
778
779 ;; This method has a problem if you've accidentally let the active list get
780 ;; out of sync with the files.  This could happen, say, if you've
781 ;; accidentally gotten new mail with something other than Gnus (but why
782 ;; would _that_ ever happen? :-).  In that case, we will be in the middle of
783 ;; processing the file, ready to add new X-Gnus article number markers, and
784 ;; we'll run across a message with no ID yet - the active list _may_not_ be
785 ;; ready for us yet.
786
787 ;; To handle this, I'm modifying this routine to maintain the maximum ID seen
788 ;; so far, and when we hit a message with no ID, we will _manually_ scan the
789 ;; rest of the message looking for any more, possibly higher IDs.  We'll
790 ;; assume the maximum that we find is the highest active.  Note that this
791 ;; shouldn't cost us much extra time at all, but will be a lot less
792 ;; vulnerable to glitches between the mbox and the active file.
793
794 (defun nnfolder-read-folder (group)
795   (let* ((file (nnfolder-group-pathname group))
796          (nov  (nnfolder-group-nov-pathname group))
797          (buffer (set-buffer
798                   (let ((nnheader-file-coding-system 
799                          nnfolder-file-coding-system))
800                     (nnheader-find-file-noselect file)))))
801     (if (equal (cadr (assoc group nnfolder-scantime-alist))
802                (nth 5 (file-attributes file)))
803         ;; This looks up-to-date, so we don't do any scanning.
804         (if (file-exists-p file)
805             buffer
806           (push (list group buffer) nnfolder-buffer-alist)
807           (set-buffer-modified-p t)
808           (nnfolder-save-buffer))
809       ;; Parse the damn thing.
810       (save-excursion
811         (goto-char (point-min))
812         ;; Remove any blank lines at the start.
813         (while (eq (following-char) ?\n)
814           (delete-char 1))
815         (nnmail-activate 'nnfolder)
816         ;; Read in the file.
817         (let ((delim "^From ")
818               (marker (concat "\n" nnfolder-article-marker))
819               (number "[0-9]+")
820               (active (or (cadr (assoc group nnfolder-group-alist))
821                           (cons 1 0)))
822               (scantime (assoc group nnfolder-scantime-alist))
823               (minid (lsh -1 -1))
824               maxid start end newscantime
825               novbuf articles newnum
826               buffer-read-only)
827           (buffer-disable-undo)
828           (setq maxid (cdr active))
829
830           (unless (or gnus-nov-is-evil nnfolder-nov-is-evil
831                       (and (file-exists-p nov)
832                            (file-newer-than-file-p nov file)))
833             (unless (file-exists-p nov)
834               (gnus-make-directory (file-name-directory nov)))
835             (with-current-buffer
836                 (setq novbuf (nnfolder-open-nov group))
837               (goto-char (point-min))
838               (while (not (eobp))
839                 (push (read novbuf) articles)
840                 (forward-line 1))
841               (setq articles (nreverse articles))))
842           (goto-char (point-min))
843
844           ;; Anytime the active number is 1 or 0, it is suspect.  In that
845           ;; case, search the file manually to find the active number.  Or,
846           ;; of course, if we're being paranoid.  (This would also be the
847           ;; place to build other lists from the header markers, such as
848           ;; expunge lists, etc., if we ever desired to abandon the active
849           ;; file entirely for mboxes.)
850           (when (or nnfolder-ignore-active-file
851                     novbuf
852                     (< maxid 2))
853             (while (and (search-forward marker nil t)
854                         (looking-at number))
855               (setq newnum (string-to-number (match-string 0)))
856               (when (nnmail-within-headers-p)
857                 (setq maxid (max maxid newnum)
858                       minid (min minid newnum))
859                 (when novbuf
860                   (if (memq newnum articles)
861                       (setq articles (delq newnum articles))
862                     (let ((headers (nnfolder-parse-head newnum)))
863                       (with-current-buffer novbuf
864                         (nnheader-find-nov-line newnum)
865                         (nnheader-insert-nov headers)))))))
866             (when (and novbuf articles)
867               (with-current-buffer novbuf
868                 (dolist (article articles)
869                   (when (nnheader-find-nov-line article)
870                     (delete-region (point) 
871                                    (progn (forward-line 1) (point)))))))
872             (setcar active (max 1 (min minid maxid)))
873             (setcdr active (max maxid (cdr active)))
874             (goto-char (point-min)))
875
876           ;; As long as we trust that the user will only insert unmarked mail
877           ;; at the end, go to the end and search backwards for the last
878           ;; marker.  Find the start of that message, and begin to search for
879           ;; unmarked messages from there.
880           (when (not (or nnfolder-distrust-mbox
881                          (< maxid 2)))
882             (goto-char (point-max))
883             (unless (re-search-backward marker nil t)
884               (goto-char (point-min)))
885             ;;(when (nnmail-search-unix-mail-delim)
886             ;;  (goto-char (point-min)))
887             )
888
889           ;; Keep track of the active number on our own, and insert it back
890           ;; into the active list when we're done.  Also, prime the pump to
891           ;; cut down on the number of searches we do.
892           (unless (nnmail-search-unix-mail-delim)
893             (goto-char (point-max)))
894           (setq end (point-marker))
895           (while (not (= end (point-max)))
896             (setq start (marker-position end))
897             (goto-char end)
898             ;; There may be more than one "From " line, so we skip past
899             ;; them.
900             (while (looking-at delim)
901               (forward-line 1))
902             (set-marker end (if (nnmail-search-unix-mail-delim)
903                                 (point)
904                               (point-max)))
905             (goto-char start)
906             (when (not (search-forward marker end t))
907               (narrow-to-region start end)
908               (nnmail-insert-lines)
909               (nnfolder-insert-newsgroup-line
910                (cons nil 
911                      (setq newnum
912                            (nnfolder-active-number nnfolder-current-group))))
913               (when novbuf
914                 (let ((headers (nnfolder-parse-head newnum (point-min)
915                                                       (point-max))))
916                   (with-current-buffer novbuf
917                     (goto-char (point-max))
918                     (nnheader-insert-nov headers))))
919               (widen)))
920
921           (set-marker end nil)
922           ;; Make absolutely sure that the active list reflects reality!
923           (nnfolder-save-active nnfolder-group-alist nnfolder-active-file)
924
925           ;; Set the scantime for this group.
926           (setq newscantime (visited-file-modtime))
927           (if scantime
928               (setcdr scantime (list newscantime))
929             (push (list nnfolder-current-group newscantime)
930                   nnfolder-scantime-alist))
931           ;; Save nov.
932           (when novbuf
933             (nnfolder-save-nov))
934           (current-buffer))))))
935
936 ;;;###autoload
937 (defun nnfolder-generate-active-file ()
938   "Look for mbox folders in the nnfolder directory and make them into groups.
939 This command does not work if you use short group names."
940   (interactive)
941   (nnmail-activate 'nnfolder)
942   (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
943     (dolist (file (directory-files (or nnfolder-nov-directory 
944                                        nnfolder-directory)
945                                    t 
946                                    (concat 
947                                     (regexp-quote nnfolder-nov-file-suffix)
948                                     "$")))
949       (when (not (message-mail-file-mbox-p file))
950         (ignore-errors
951           (delete-file file)))))
952   (let ((files (directory-files nnfolder-directory))
953         file)
954     (while (setq file (pop files))
955       (when (and (not (backup-file-name-p file))
956                  (message-mail-file-mbox-p
957                   (nnheader-concat nnfolder-directory file)))
958         (let ((oldgroup (assoc file nnfolder-group-alist)))
959           (if oldgroup
960               (nnheader-message 5 "Refreshing group %s..." file)
961             (nnheader-message 5 "Adding group %s..." file))
962           (if oldgroup
963               (setq nnfolder-group-alist
964                     (delq oldgroup (copy-sequence nnfolder-group-alist))))
965           (push (list file (cons 1 0)) nnfolder-group-alist)
966           (nnfolder-possibly-change-folder file)
967           (nnfolder-possibly-change-group file)
968           (nnfolder-close-group file))))
969     (nnheader-message 5 "")))
970
971 (defun nnfolder-group-pathname (group)
972   "Make pathname for GROUP."
973   (setq group
974         (encode-coding-string group nnmail-pathname-coding-system))
975   (let ((dir (file-name-as-directory (expand-file-name nnfolder-directory))))
976     ;; If this file exists, we use it directly.
977     (if (or nnmail-use-long-file-names
978             (file-exists-p (concat dir group)))
979         (concat dir group)
980       ;; If not, we translate dots into slashes.
981       (concat dir (nnheader-replace-chars-in-string group ?. ?/)))))
982
983 (defun nnfolder-group-nov-pathname (group)
984   "Make pathname for GROUP NOV."
985   (let ((nnfolder-directory
986          (or nnfolder-nov-directory nnfolder-directory)))
987     (concat (nnfolder-group-pathname group) nnfolder-nov-file-suffix)))
988
989 (defun nnfolder-save-buffer ()
990   "Save the buffer."
991   (when (buffer-modified-p)
992     (run-hooks 'nnfolder-save-buffer-hook)
993     (gnus-make-directory (file-name-directory (buffer-file-name)))
994     (let* ((coding-system-for-write
995             (or nnfolder-file-coding-system-for-write
996                 nnfolder-file-coding-system))
997            (output-coding-system coding-system-for-write))
998       (save-buffer)))
999   (unless (or gnus-nov-is-evil nnfolder-nov-is-evil)
1000     (nnfolder-save-nov)))
1001
1002 (defun nnfolder-save-active (group-alist active-file)
1003   (let ((nnmail-active-file-coding-system
1004          (or nnfolder-active-file-coding-system-for-write
1005              nnfolder-active-file-coding-system)))
1006     (nnmail-save-active group-alist active-file)))
1007
1008 (defun nnfolder-open-nov (group)
1009   (or (cdr (assoc group nnfolder-nov-buffer-alist))
1010       (let ((buffer (get-buffer-create (format " *nnfolder overview %s*" group))))
1011         (save-excursion
1012           (set-buffer buffer)
1013           (set (make-local-variable 'nnfolder-nov-buffer-file-name)
1014                (nnfolder-group-nov-pathname group))
1015           (erase-buffer)
1016           (when (file-exists-p nnfolder-nov-buffer-file-name)
1017             (nnheader-insert-file-contents nnfolder-nov-buffer-file-name)))
1018         (push (cons group buffer) nnfolder-nov-buffer-alist)
1019         buffer)))
1020
1021 (defun nnfolder-save-nov ()
1022   (save-excursion
1023     (while nnfolder-nov-buffer-alist
1024       (when (buffer-name (cdar nnfolder-nov-buffer-alist))
1025         (set-buffer (cdar nnfolder-nov-buffer-alist))
1026         (when (buffer-modified-p)
1027           (gnus-make-directory (file-name-directory 
1028                                 nnfolder-nov-buffer-file-name))
1029           (nnmail-write-region 1 (point-max) nnfolder-nov-buffer-file-name
1030                                nil 'nomesg))
1031         (set-buffer-modified-p nil)
1032         (kill-buffer (current-buffer)))
1033       (setq nnfolder-nov-buffer-alist (cdr nnfolder-nov-buffer-alist)))))
1034
1035 (defun nnfolder-nov-delete-article (group article)
1036   (save-excursion
1037     (set-buffer (nnfolder-open-nov group))
1038     (when (nnheader-find-nov-line article)
1039       (delete-region (point) (progn (forward-line 1) (point))))
1040     t))
1041
1042 (defun nnfolder-retrieve-headers-with-nov (articles &optional fetch-old)
1043   (if (or gnus-nov-is-evil nnfolder-nov-is-evil)
1044       nil
1045     (let ((nov (nnfolder-group-nov-pathname nnfolder-current-group)))
1046       (when (file-exists-p nov)
1047         (save-excursion
1048           (set-buffer nntp-server-buffer)
1049           (erase-buffer)
1050           (nnheader-insert-file-contents nov)
1051           (if (and fetch-old
1052                    (not (numberp fetch-old)))
1053               t                         ; Don't remove anything.
1054             (nnheader-nov-delete-outside-range
1055              (if fetch-old (max 1 (- (car articles) fetch-old))
1056                (car articles))
1057              (car (last articles)))
1058             t))))))
1059
1060 (defun nnfolder-parse-head (&optional number b e)
1061   "Parse the head of the current buffer."
1062   (let ((buf (current-buffer))
1063         chars)
1064   (save-excursion
1065     (unless b
1066       (setq b (if (nnmail-search-unix-mail-delim-backward)
1067                   (point) (point-min)))
1068       (forward-line 1)
1069       (setq e (if (nnmail-search-unix-mail-delim)
1070                   (point) (point-max))))
1071     (setq chars (- e b))
1072     (unless (zerop chars)
1073       (goto-char b)
1074       (if (search-forward "\n\n" e t) (setq e (1- (point)))))
1075     (with-temp-buffer
1076       (insert-buffer-substring buf b e)
1077       ;; Fold continuation lines.
1078       (goto-char (point-min))
1079       (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1080         (replace-match " " t t))
1081       ;; Remove any tabs; they are too confusing.
1082       (subst-char-in-region (point-min) (point-max) ?\t ? )
1083       (let ((headers (nnheader-parse-head t)))
1084         (mail-header-set-chars headers chars)
1085         (mail-header-set-number headers number)
1086         headers)))))
1087
1088 (defun nnfolder-add-nov (group article headers)
1089   "Add a nov line for the GROUP base."
1090   (save-excursion
1091     (set-buffer (nnfolder-open-nov group))
1092     (goto-char (point-max))
1093     (mail-header-set-number headers article)
1094     (nnheader-insert-nov headers)))
1095
1096 (provide 'nnfolder)
1097
1098 ;;; nnfolder.el ends here