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