72dd7b7cd4d87cd4452829db12cf4489988745ec
[elisp/gnus.git-] / lisp / nndiary.el
1 ;;; nndiary.el --- A diary backend for Gnus
2
3 ;; Copyright (C) 1999-2001 Didier Verna.
4
5 ;; Author:        Didier Verna <didier@xemacs.org>
6 ;; Maintainer:    Didier Verna <didier@xemacs.org>
7 ;; Created:       Fri Jul 16 18:55:42 1999
8 ;; Last Revision: Wed Aug  8 17:36:21 2001
9 ;; Keywords:      calendar mail news
10
11 ;; This file is part of NNDiary.
12
13 ;; NNDiary 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 of the License, or
16 ;; (at your option) any later version.
17
18 ;; NNDiary 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 this program; if not, write to the Free Software
25 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26
27
28 ;;; Commentary:
29
30 ;; Contents management by FCM version 0.1.
31
32 ;; Description:
33 ;; ===========
34
35 ;; This package implements NNDiary, a diary backend for Gnus.  NNDiary is a
36 ;; mail backend, pretty similar to nnml in its functionnning (it has all the
37 ;; features of nnml, actually), but in which messages are treated as event
38 ;; reminders.
39
40 ;; Here is a typical scenario:
41 ;; - You've got a date with Andy Mc Dowell or Bruce Willis (select according
42 ;;   to your sexual preference) in one month.  You don't want to forget it.
43 ;; - Send a (special) diary message to yourself (see below).
44 ;; - Forget all about it and keep on getting and reading new mail, as usual.
45 ;; - From time to time, as you type `g' in the group buffer and as the date
46 ;;   is getting closer, the message will pop up again, just like if it were
47 ;;   new and unread.
48 ;; - Read your "new" messages, this one included, and start dreaming of the
49 ;;   night you're gonna have.
50 ;; - Once the date is over (you actually fell asleep just after dinner), the
51 ;;   message will be automatically deleted if it is marked as expirable.
52
53 ;; Some more notes on the diary backend:
54 ;; - NNDiary is a *real* mail backend.  You *really* send real diary
55 ;;   messsages.  This means for instance that you can give appointements to
56 ;;   anybody (provided they use Gnus and NNDiary) by sending the diary message
57 ;;   to them as well.
58 ;; - However, since NNDiary also has a 'request-post method, you can also
59 ;;  `C-u a' instead of `C-u m' on a diary group and the message won't actually
60 ;;   be sent; just stored in the group.
61 ;; - The events you want to remember need not be punctual.  You can set up
62 ;;   reminders for regular dates (like once each week, each monday at 13:30
63 ;;   and so on).  Diary messages of this kind will never be deleted (unless
64 ;;   you do it explicitely).  But that, you guessed.
65
66
67 ;; Usage:
68 ;; =====
69
70 ;;  1/ NNDiary has two modes of operation: traditional (the default) and
71 ;;     autonomous.
72 ;;     a/ In traditional mode, NNDiary does not get new mail by itself.  You
73 ;;        have to move mails from your primary mail backend to nndiary
74 ;;        groups.
75 ;;     b/ In autonomous mode, NNDiary retrieves its own mail and handles it
76 ;;        independantly of your primary mail backend.  To use NNDiary in
77 ;;        autonomous mode, you have several things to do:
78 ;;           i/ Put (setq nndiary-get-new-mail t) in your gnusrc file.
79 ;;          ii/ Diary messages contain several `X-Diary-*' special headers.
80 ;;              You *must* arrange that these messages be split in a private
81 ;;              folder *before* Gnus treat them.  You need this because Gnus
82 ;;              is not able yet to manage multiple backends for mail
83 ;;              retrieval.  Getting them from a separate source will
84 ;;              compensate this misfeature to some extent, as we will see.
85 ;;              As an example, here's my procmailrc entry to store diary files
86 ;;              in ~/.nndiary (the default nndiary mail source file):
87 ;;
88 ;;              :0 HD :
89 ;;              * ^X-Diary
90 ;;              .nndiary
91 ;;         iii/ Customize the variables `nndiary-mail-sources' and
92 ;;              `nndiary-split-methods'.  These are replacements for the usual
93 ;;              mail sources and split methods which, and will be used in
94 ;;              autonomous mode.  `nndiary-mail-sources' defaults to
95 ;;              '(file :path "~/.nndiary").
96 ;;  2/ Install nndiary somewhere Emacs / Gnus can find it.  Normally, you
97 ;;     *don't* have to '(require 'nndiary) anywhere.  Gnus will do so when
98 ;;     appropriate as long as nndiary is somewhere in the load path.
99 ;;  3/ Now, customize the rest of nndiary.  In particular, you should
100 ;;     customize `nndiary-reminders', the list of times when you want to be
101 ;;     reminded of your appointements (e.g. 3 weeks before, then 2 days
102 ;;     before, then 1 hour before and that's it).
103 ;;  4/ You *must* use the group timestamp feature of Gnus.  This adds a
104 ;;     timestamp to each groups' parameters (please refer to the Gnus
105 ;;     documentation ("Group Timestamp" info node) to see how it's done.
106 ;;  5/ Once you have done this, you may add a permanent nndiary virtual server
107 ;;     (something like '(nndiary "")) to your `gnus-secondary-select-methods'.
108 ;;     Yes, this server will be able to retrieve mails and split them when you
109 ;;     type `g' in the group buffer, just as if it were your only mail backend.
110 ;;     This is the benefit of using a private folder.
111 ;;  6/ Hopefully, almost everything (see the TODO section below) will work as
112 ;;     expected when you restart Gnus: in the group buffer, `g' and `M-g' will
113 ;;     also get your new diary mails, `F' will find your new diary groups etc.
114
115
116 ;; How to send diary messages:
117 ;; ==========================
118
119 ;; There are 7 special headers in diary messages. These headers are of the
120 ;; form `X-Diary-<something>', the <something> being one of `Minute', `Hour',
121 ;; `Dom', `Month', `Year', `Time-Zone' and `Dow'. `Dom' means "Day of Month",
122 ;; and `dow' means "Day of Week".  These headers actually behave like crontab
123 ;; specifications and define the event date(s).
124
125 ;; For all headers but the `Time-Zone' one, a header value is either a
126 ;; star (meaning all possible values), or a list of fields (separated by a
127 ;; comma).  A field is either an integer, or a range.  A range is two integers
128 ;; separated by a dash.  Possible integer values are 0-59 for `Minute', 0-23
129 ;; for `Hour', 1-31 for `Dom', `1-12' for Month, above 1971 for `Year' and 0-6
130 ;; for `Dow' (0 = sunday).  As a special case, a star in either `Dom' or `Dow'
131 ;; doesn't mean "all possible values", but "use only the other field".  Note
132 ;; that if both are star'ed, the use of either one gives the same result :-),
133
134 ;; The `Time-Zone' header is special in that it can have only one value (you
135 ;; bet ;-).
136 ;; A star doesn't mean "all possible values" (because it has no sense), but
137 ;; "the current local time zone".
138
139 ;; As an example, here's how you would say "Each Monday and each 1st of month,
140 ;; at 12:00, 20:00, 21:00, 22:00, 23:00 and 24:00, from 1999 to 2010" (I let
141 ;; you find what to do then):
142 ;;
143 ;;   X-Diary-Minute: 0
144 ;;   X-Diary-Hour: 12, 20-24
145 ;;   X-Diary-Dom: 1
146 ;;   X-Diary-Month: *
147 ;;   X-Diary-Year: 1999-2010
148 ;;   X-Diary-Dow: 1
149 ;;   X-Diary-Time-Zone: *
150 ;;
151 ;;
152 ;; Sending a diary message is not different from sending any other kind of
153 ;; mail, except that such messages are identified by the presence of these
154 ;; special headers.
155
156
157
158 ;; Bugs / Todo:
159 ;; ===========
160
161 ;; * Respooling doesn't work because contrary to the request-scan function,
162 ;;   Gnus won't allow me to override the split methods when calling the
163 ;;   respooling backend functions.
164 ;; * There's a bug in the time zone mechanism with variable TZ locations.
165 ;; * We could allow a keyword like `ask' in X-Diary-* headers, that would mean
166 ;;   "ask for value upon reception of the message".
167 ;; * We could add an optional header X-Diary-Reminders to specify a special
168 ;;   reminders value for this message. Suggested by Jody Klymak.
169 ;; * We should check messages validity in other circumstances than just
170 ;;   moving an article from sonwhere else (request-accept). For instance, when
171 ;;   editing / saving and so on.
172
173
174 ;; Remarks:
175 ;; =======
176
177 ;; * nnoo.
178 ;;   NNDiary is very similar to nnml.  This makes the idea of using nnoo (to
179 ;;   derive nndiary from nnml) natural.  However, my experience with nnoo is
180 ;;   that for reasonably complex backends like this one, noo is a burden
181 ;;   rather than an help.  It's tricky to use, not everything can be
182 ;;   inherited, what can be inherited and when is not very clear, and you've
183 ;;   got to be very careful because a little mistake can fuck up your your
184 ;;   other backends, especially because their variables will be use instead of
185 ;;   your real ones.  Finally, I found it easier to just clone the needed
186 ;;   parts of nnml, and tracking nnml updates is not a big deal.
187
188 ;;   IMHO, nnoo is actually badly designed.  A much simpler, and yet more
189 ;;   powerful one would be to make *real* functions and variables for a new
190 ;;   backend based on another. Lisp is a reflexive language so that's a very
191 ;;   easy thing to do: inspect the function's form, replace occurences of
192 ;;   <nnfrom> (even in strings) with <nnto>, and you're done.
193
194 ;; * nndiary-get-new-mail, nndiary-mail-source and nndiary-split-methods:
195 ;;   NNDiary has some experimental parts, in the sense Gnus normally uses only
196 ;;   one mail backends for mail retreival and splitting.  This backend is also
197 ;;   an attempt to make it behave differently.  For Gnus developpers: as you
198 ;;   can see if you snarf into the code, that was not a very difficult thing
199 ;;   to do.  Something should be done about the respooling breakage though.
200
201
202 ;;; Code:
203
204 (require 'nnoo)
205 (require 'nnheader)
206 (require 'nnmail)
207 (eval-when-compile (require 'cl))
208
209 (require 'gnus-start)
210 (require 'gnus-sum)
211
212 ;; Compatibility Functions  =================================================
213
214 (if (fboundp 'signal-error)
215     (defun nndiary-error (&rest args)
216       (apply #'signal-error 'nndiary args))
217   (defun nndiary-error (&rest args)
218     (apply #'error args)))
219
220
221 ;; Backend behavior customization ===========================================
222
223 (defgroup nndiary nil
224   "The Gnus Diary backend."
225   :group 'gnus-diary)
226
227 (defcustom nndiary-mail-sources
228   `((file :path ,(expand-file-name "~/.nndiary")))
229   "*NNDiary specific mail sources.
230 This variable is used by nndiary in place of the standard `mail-sources'
231 variable when `nndiary-get-new-mail' is set to non-nil.  These sources
232 must contain diary messages ONLY."
233   :group 'nndiary
234   :group 'mail-source
235   :type 'sexp)
236
237 (defcustom nndiary-split-methods '(("diary" ""))
238   "*NNDiary specific split methods.
239 This variable is used by nndiary in place of the standard
240 `nnmail-split-methods' variable when `nndiary-get-new-mail' is set to
241 non-nil."
242   :group 'nndiary
243   :group 'nnmail-split
244   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
245                  (function-item nnmail-split-fancy)
246                  (function :tag "Other")))
247
248
249 (defcustom nndiary-reminders '((0 . day))
250   "*Different times when you want to be reminded of your appointements.
251 Diary articles will appear again, as if they'd been just received.
252
253 Entries look like (3 . day) which means something like \"Please
254 Hortense, would you be so kind as to remind me of my appointments 3 days
255 before the date, thank you very much. Anda, hmmm... by the way, are you
256 doing anything special tonight ?\".
257
258 The units of measure are 'minute 'hour 'day 'week 'month and 'year (no,
259 not 'century, sorry).
260
261 NOTE: the units of measure actually express dates, not durations: if you
262 use 'week, messages will pop up on Sundays at 00:00 (or Mondays if
263 `nndiary-week-starts-on-monday' is non nil) and *not* 7 days before the
264 appointement, if you use 'month, messages will pop up on the first day of
265 each months, at 00:00 and so on.
266
267 If you really want to specify a duration (like 24 hours exactly), you can
268 use the equivalent in minutes (the smallest unit).  A fuzz of 60 seconds
269 maximum in the reminder is not that painful, I think.  Although this
270 scheme might appear somewhat weird at a first glance, it is very powerful.
271 In order to make this clear, here are some examples:
272
273 - '(0 . day): this is the default value of `nndiary-reminders'.  It means
274   pop up the appointements of the day each morning at 00:00.
275
276 - '(1 . day): this means pop up the appointements the day before, at 00:00.
277
278 - '(6 . hour): for an appointement at 18:30, this would pop up the
279   appointement message at 12:00.
280
281 - '(360 . minute): for an appointement at 18:30 and 15 seconds, this would
282   pop up the appointement message at 12:30."
283   :group 'nndiary
284   :type '(repeat (cons :format "%v\n"
285                        (integer :format "%v")
286                        (choice :format "%[%v(s)%] before...\n"
287                                :value day
288                                (const :format "%v" minute)
289                                (const :format "%v" hour)
290                                (const :format "%v" day)
291                                (const :format "%v" week)
292                                (const :format "%v" month)
293                                (const :format "%v" year)))))
294
295 (defcustom nndiary-week-starts-on-monday nil
296   "*Whether a week starts on monday (otherwise, sunday)."
297   :type 'boolean
298   :group 'nndiary)
299
300
301 (defcustom nndiary-request-create-group-hooks nil
302   "*Hooks to run after `nndiary-request-create-group' is executed.
303 The hooks will be called with the full group name as argument."
304   :group 'nndiary
305   :type 'hook)
306
307 (defcustom nndiary-request-update-info-hooks nil
308   "*Hooks to run after `nndiary-request-update-info-group' is executed.
309 The hooks will be called with the full group name as argument."
310   :group 'nndiary
311   :type 'hook)
312
313 (defcustom nndiary-request-accept-article-hooks nil
314   "*Hooks to run before accepting an article.
315 Executed near the beginning of `nndiary-request-accept-article'.
316 The hooks will be called with the article in the current buffer."
317   :group 'nndiary
318   :type 'hook)
319
320 (defcustom nndiary-check-directory-twice t
321   "*If t, check directories twice to avoid NFS failures."
322   :group 'nndiary
323   :type 'boolean)
324
325
326 ;; Backend declaration ======================================================
327
328 ;; Well, most of this is nnml clonage.
329
330 (nnoo-declare nndiary)
331
332 (defvoo nndiary-directory (nnheader-concat gnus-directory "diary/")
333   "Spool directory for the nndiary backend.")
334
335 (defvoo nndiary-active-file
336     (expand-file-name "active" nndiary-directory)
337   "Active file for the nndiary backend.")
338
339 (defvoo nndiary-newsgroups-file
340     (expand-file-name "newsgroups" nndiary-directory)
341   "Newsgroups description file for the nndiary backend.")
342
343 (defvoo nndiary-get-new-mail nil
344   "Whether nndiary gets new mail and split it.
345 Contrary to traditional mail backends, this variable can be set to t
346 even if your primary mail backend also retreives mail. In such a case,
347 NDiary uses its own mail-sources and split-methods.")
348
349 (defvoo nndiary-nov-is-evil nil
350   "If non-nil, Gnus will never use nov databases for nndiary groups.
351 Using nov databases will speed up header fetching considerably.
352 This variable shouldn't be flipped much.  If you have, for some reason,
353 set this to t, and want to set it to nil again, you should always run
354 the `nndiary-generate-nov-databases' command.  The function will go
355 through all nnml directories and generate nov databases for them
356 all.  This may very well take some time.")
357
358 (defvoo nndiary-prepare-save-mail-hook nil
359   "*Hook run narrowed to an article before saving.")
360
361 (defvoo nndiary-inhibit-expiry nil
362   "If non-nil, inhibit expiry.")
363
364 \f
365
366 ;; $Format: "(defconst nndiary-prcs-major-version \"$ProjectMajorVersion$\")"$
367 (defconst nndiary-prcs-major-version "branch-0-2")
368 ;; $Format: "(defconst nndiary-prcs-minor-version \"$ProjectMinorVersion$\")"$
369 (defconst nndiary-prcs-minor-version "13")
370 (defconst nndiary-version
371   (let ((level nndiary-prcs-minor-version)
372         major minor status)
373     (string-match "\\(branch\\|version\\)-\\([0-9]+\\)-\\([0-9]+\\)"
374                   nndiary-prcs-major-version)
375     (setq major (match-string 2 nndiary-prcs-major-version)
376           minor (match-string 3 nndiary-prcs-major-version)
377           status (match-string 1 nndiary-prcs-major-version))
378     (cond ((string= status "version")
379            (setq level (int-to-string (1- (string-to-int level))))
380            (if (eq level 0)
381                (concat major "." minor)
382              (concat major "." minor "." level)))
383           ((string= status "branch")
384            (concat major "." minor "-b" level))))
385   "Current Diary backend version.")
386
387 (defun nndiary-version ()
388   "Current Diary backend version."
389   (interactive)
390   (message "NNDiary version %s" nndiary-version))
391
392
393 (defvoo nndiary-nov-file-name ".overview")
394
395 (defvoo nndiary-current-directory nil)
396 (defvoo nndiary-current-group nil)
397 (defvoo nndiary-status-string "" )
398 (defvoo nndiary-nov-buffer-alist nil)
399 (defvoo nndiary-group-alist nil)
400 (defvoo nndiary-active-timestamp nil)
401 (defvoo nndiary-article-file-alist nil)
402
403 (defvoo nndiary-generate-active-function 'nndiary-generate-active-info)
404 (defvoo nndiary-nov-buffer-file-name nil)
405 (defvoo nndiary-file-coding-system nnmail-file-coding-system)
406
407 (defconst nndiary-headers
408   '(("Minute" 0 59)
409     ("Hour" 0 23)
410     ("Dom" 1 31)
411     ("Month" 1 12)
412     ("Year" 1971)
413     ("Dow" 0 6)
414     ("Time-Zone" (("Y" -43200)
415
416                   ("X" -39600)
417
418                   ("W" -36000)
419
420                   ("V" -32400)
421
422                   ("U" -28800)
423                   ("PST" -28800)
424
425                   ("T"   -25200)
426                   ("MST" -25200)
427                   ("PDT" -25200)
428
429                   ("S"   -21600)
430                   ("CST" -21600)
431                   ("MDT" -21600)
432
433                   ("R"   -18000)
434                   ("EST" -18000)
435                   ("CDT" -18000)
436
437                   ("Q"   -14400)
438                   ("AST" -14400)
439                   ("EDT" -14400)
440
441                   ("P"   -10800)
442                   ("ADT" -10800)
443
444                   ("O" -7200)
445
446                   ("N" -3600)
447
448                   ("Z"   0)
449                   ("GMT" 0)
450                   ("UT"  0)
451                   ("UTC" 0)
452                   ("WET" 0)
453
454                   ("A"    3600)
455                   ("CET"  3600)
456                   ("MET"  3600)
457                   ("MEZ"  3600)
458                   ("BST"  3600)
459                   ("WEST" 3600)
460
461                   ("B"    7200)
462                   ("EET"  7200)
463                   ("CEST" 7200)
464                   ("MEST" 7200)
465                   ("MESZ" 7200)
466
467                   ("C" 10800)
468
469                   ("D" 14400)
470
471                   ("E" 18000)
472
473                   ("F" 21600)
474
475                   ("G" 25200)
476
477                   ("H" 28800)
478
479                   ("I"   32400)
480                   ("JST" 32400)
481
482                   ("K"   36000)
483                   ("GST" 36000)
484
485                   ("L" 39600)
486
487                   ("M"    43200)
488                   ("NZST" 43200)
489
490                   ("NZDT" 46800))))
491   ;; List of NNDiary headers that specify the time spec. Each header name is
492   ;; followed by either two integers (specifying a range of possible values
493   ;; for this header) or one list (specifying all the possible values for this
494   ;; header). In the latter case, the list does NOT include the unspecifyed
495   ;; spec (*).
496   ;; For time zone values, we have symbolic time zone names associated with
497   ;; the (relative) number of seconds ahead GMT.
498   )
499
500
501 ;;; Interface functions =====================================================
502
503 (nnoo-define-basics nndiary)
504
505 (deffoo nndiary-retrieve-headers (sequence &optional group server fetch-old)
506   (when (nndiary-possibly-change-directory group server)
507     (save-excursion
508       (set-buffer nntp-server-buffer)
509       (erase-buffer)
510       (let* ((file nil)
511              (number (length sequence))
512              (count 0)
513              (file-name-coding-system nnmail-pathname-coding-system)
514              beg article
515              (nndiary-check-directory-twice
516               (and nndiary-check-directory-twice
517                    ;; To speed up, disable it in some case.
518                    (or (not (numberp nnmail-large-newsgroup))
519                        (<= number nnmail-large-newsgroup)))))
520         (if (stringp (car sequence))
521             'headers
522           (if (nndiary-retrieve-headers-with-nov sequence fetch-old)
523               'nov
524             (while sequence
525               (setq article (car sequence))
526               (setq file (nndiary-article-to-file article))
527               (when (and file
528                          (file-exists-p file)
529                          (not (file-directory-p file)))
530                 (insert (format "221 %d Article retrieved.\n" article))
531                 (setq beg (point))
532                 (nnheader-insert-head file)
533                 (goto-char beg)
534                 (if (search-forward "\n\n" nil t)
535                     (forward-char -1)
536                   (goto-char (point-max))
537                   (insert "\n\n"))
538                 (insert ".\n")
539                 (delete-region (point) (point-max)))
540               (setq sequence (cdr sequence))
541               (setq count (1+ count))
542               (and (numberp nnmail-large-newsgroup)
543                    (> number nnmail-large-newsgroup)
544                    (zerop (% count 20))
545                    (nnheader-message 6 "nndiary: Receiving headers... %d%%"
546                                      (/ (* count 100) number))))
547
548             (and (numberp nnmail-large-newsgroup)
549                  (> number nnmail-large-newsgroup)
550                  (nnheader-message 6 "nndiary: Receiving headers...done"))
551
552             (nnheader-fold-continuation-lines)
553             'headers))))))
554
555 (deffoo nndiary-open-server (server &optional defs)
556   (nnoo-change-server 'nndiary server defs)
557   (when (not (file-exists-p nndiary-directory))
558     (ignore-errors (make-directory nndiary-directory t)))
559   (cond
560    ((not (file-exists-p nndiary-directory))
561     (nndiary-close-server)
562     (nnheader-report 'nndiary "Couldn't create directory: %s"
563                      nndiary-directory))
564    ((not (file-directory-p (file-truename nndiary-directory)))
565     (nndiary-close-server)
566     (nnheader-report 'nndiary "Not a directory: %s" nndiary-directory))
567    (t
568     (nnheader-report 'nndiary "Opened server %s using directory %s"
569                      server nndiary-directory)
570     t)))
571
572 (deffoo nndiary-request-regenerate (server)
573   (nndiary-possibly-change-directory nil server)
574   (nndiary-generate-nov-databases server)
575   t)
576
577 (deffoo nndiary-request-article (id &optional group server buffer)
578   (nndiary-possibly-change-directory group server)
579   (let* ((nntp-server-buffer (or buffer nntp-server-buffer))
580          (file-name-coding-system nnmail-pathname-coding-system)
581          path gpath group-num)
582     (if (stringp id)
583         (when (and (setq group-num (nndiary-find-group-number id))
584                    (cdr
585                     (assq (cdr group-num)
586                           (nnheader-article-to-file-alist
587                            (setq gpath
588                                  (nnmail-group-pathname
589                                   (car group-num)
590                                   nndiary-directory))))))
591           (setq path (concat gpath (int-to-string (cdr group-num)))))
592       (setq path (nndiary-article-to-file id)))
593     (cond
594      ((not path)
595       (nnheader-report 'nndiary "No such article: %s" id))
596      ((not (file-exists-p path))
597       (nnheader-report 'nndiary "No such file: %s" path))
598      ((file-directory-p path)
599       (nnheader-report 'nndiary "File is a directory: %s" path))
600      ((not (save-excursion (let ((nnmail-file-coding-system
601                                   nndiary-file-coding-system))
602                              (nnmail-find-file path))))
603       (nnheader-report 'nndiary "Couldn't read file: %s" path))
604      (t
605       (nnheader-report 'nndiary "Article %s retrieved" id)
606       ;; We return the article number.
607       (cons (if group-num (car group-num) group)
608             (string-to-int (file-name-nondirectory path)))))))
609
610 (deffoo nndiary-request-group (group &optional server dont-check)
611   (let ((file-name-coding-system nnmail-pathname-coding-system))
612     (cond
613      ((not (nndiary-possibly-change-directory group server))
614       (nnheader-report 'nndiary "Invalid group (no such directory)"))
615      ((not (file-exists-p nndiary-current-directory))
616       (nnheader-report 'nndiary "Directory %s does not exist"
617                        nndiary-current-directory))
618      ((not (file-directory-p nndiary-current-directory))
619       (nnheader-report 'nndiary "%s is not a directory"
620                        nndiary-current-directory))
621      (dont-check
622       (nnheader-report 'nndiary "Group %s selected" group)
623       t)
624      (t
625       (nnheader-re-read-dir nndiary-current-directory)
626       (nnmail-activate 'nndiary)
627       (let ((active (nth 1 (assoc group nndiary-group-alist))))
628         (if (not active)
629             (nnheader-report 'nndiary "No such group: %s" group)
630           (nnheader-report 'nndiary "Selected group %s" group)
631           (nnheader-insert "211 %d %d %d %s\n"
632                            (max (1+ (- (cdr active) (car active))) 0)
633                            (car active) (cdr active) group)))))))
634
635 (deffoo nndiary-request-scan (&optional group server)
636   ;; Use our own mail sources and split methods while Gnus doesn't let us have
637   ;; multiple backends for retrieving mail.
638   (let ((mail-sources nndiary-mail-sources)
639         (nnmail-split-methods nndiary-split-methods))
640     (setq nndiary-article-file-alist nil)
641     (nndiary-possibly-change-directory group server)
642     (nnmail-get-new-mail 'nndiary 'nndiary-save-nov nndiary-directory group)))
643
644 (deffoo nndiary-close-group (group &optional server)
645   (setq nndiary-article-file-alist nil)
646   t)
647
648 (deffoo nndiary-request-create-group (group &optional server args)
649   (nndiary-possibly-change-directory nil server)
650   (nnmail-activate 'nndiary)
651   (cond
652    ((assoc group nndiary-group-alist)
653     t)
654    ((and (file-exists-p (nnmail-group-pathname group nndiary-directory))
655          (not (file-directory-p (nnmail-group-pathname
656                                  group nndiary-directory))))
657     (nnheader-report 'nndiary "%s is a file"
658                      (nnmail-group-pathname group nndiary-directory)))
659    (t
660     (let (active)
661       (push (list group (setq active (cons 1 0)))
662             nndiary-group-alist)
663       (nndiary-possibly-create-directory group)
664       (nndiary-possibly-change-directory group server)
665       (let ((articles (nnheader-directory-articles nndiary-current-directory)))
666         (when articles
667           (setcar active (apply 'min articles))
668           (setcdr active (apply 'max articles))))
669       (nnmail-save-active nndiary-group-alist nndiary-active-file)
670       (run-hook-with-args 'nndiary-request-create-group-hooks
671                           (gnus-group-prefixed-name group
672                                                     (list "nndiary" server)))
673       t))
674    ))
675
676 (deffoo nndiary-request-list (&optional server)
677   (save-excursion
678     (let ((nnmail-file-coding-system nnmail-active-file-coding-system)
679           (file-name-coding-system nnmail-pathname-coding-system))
680       (nnmail-find-file nndiary-active-file))
681     (setq nndiary-group-alist (nnmail-get-active))
682     t))
683
684 (deffoo nndiary-request-newgroups (date &optional server)
685   (nndiary-request-list server))
686
687 (deffoo nndiary-request-list-newsgroups (&optional server)
688   (save-excursion
689     (nnmail-find-file nndiary-newsgroups-file)))
690
691 (deffoo nndiary-request-expire-articles (articles group &optional server force)
692   (nndiary-possibly-change-directory group server)
693   (let ((active-articles
694          (nnheader-directory-articles nndiary-current-directory))
695         article rest number)
696     (nnmail-activate 'nndiary)
697     ;; Articles not listed in active-articles are already gone,
698     ;; so don't try to expire them.
699     (setq articles (gnus-intersection articles active-articles))
700     (while articles
701       (setq article (nndiary-article-to-file (setq number (pop articles))))
702       (if (and (nndiary-deletable-article-p group number)
703                ;; Don't use nnmail-expired-article-p. Our notion of expiration
704                ;; is a bit peculiar ...
705                (or force (nndiary-expired-article-p article)))
706           (progn
707             ;; Allow a special target group.
708             (unless (eq nnmail-expiry-target 'delete)
709               (with-temp-buffer
710                 (nndiary-request-article number group server (current-buffer))
711                 (let ((nndiary-current-directory nil))
712                   (nnmail-expiry-target-group nnmail-expiry-target group))))
713             (nnheader-message 5 "Deleting article %s in %s" number group)
714             (condition-case ()
715                 (funcall nnmail-delete-file-function article)
716               (file-error (push number rest)))
717             (setq active-articles (delq number active-articles))
718             (nndiary-nov-delete-article group number))
719         (push number rest)))
720     (let ((active (nth 1 (assoc group nndiary-group-alist))))
721       (when active
722         (setcar active (or (and active-articles
723                                 (apply 'min active-articles))
724                            (1+ (cdr active)))))
725       (nnmail-save-active nndiary-group-alist nndiary-active-file))
726     (nndiary-save-nov)
727     (nconc rest articles)))
728
729 (deffoo nndiary-request-move-article
730     (article group server accept-form &optional last)
731   (let ((buf (get-buffer-create " *nndiary move*"))
732         result)
733     (nndiary-possibly-change-directory group server)
734     (nndiary-update-file-alist)
735     (and
736      (nndiary-deletable-article-p group article)
737      (nndiary-request-article article group server)
738      (let (nndiary-current-directory
739            nndiary-current-group
740            nndiary-article-file-alist)
741        (save-excursion
742          (set-buffer buf)
743          (insert-buffer-substring nntp-server-buffer)
744          (setq result (eval accept-form))
745          (kill-buffer (current-buffer))
746          result))
747      (progn
748        (nndiary-possibly-change-directory group server)
749        (condition-case ()
750            (funcall nnmail-delete-file-function
751                     (nndiary-article-to-file  article))
752          (file-error nil))
753        (nndiary-nov-delete-article group article)
754        (when last
755          (nndiary-save-nov)
756          (nnmail-save-active nndiary-group-alist nndiary-active-file))))
757     result))
758
759 (deffoo nndiary-request-accept-article (group &optional server last)
760   (nndiary-possibly-change-directory group server)
761   (nnmail-check-syntax)
762   (run-hooks 'nndiary-request-accept-article-hooks)
763   (when (nndiary-schedule)
764     (let (result)
765       (when nnmail-cache-accepted-message-ids
766         (nnmail-cache-insert (nnmail-fetch-field "message-id")))
767       (if (stringp group)
768           (and
769            (nnmail-activate 'nndiary)
770            (setq result
771                  (car (nndiary-save-mail
772                        (list (cons group (nndiary-active-number group))))))
773            (progn
774              (nnmail-save-active nndiary-group-alist nndiary-active-file)
775              (and last (nndiary-save-nov))))
776         (and
777          (nnmail-activate 'nndiary)
778          (if (and (not (setq result
779                              (nnmail-article-group 'nndiary-active-number)))
780                   (yes-or-no-p "Moved to `junk' group; delete article? "))
781              (setq result 'junk)
782            (setq result (car (nndiary-save-mail result))))
783          (when last
784            (nnmail-save-active nndiary-group-alist nndiary-active-file)
785            (when nnmail-cache-accepted-message-ids
786              (nnmail-cache-close))
787            (nndiary-save-nov))))
788       result))
789   )
790
791 (deffoo nndiary-request-post (&optional server)
792   (nnmail-do-request-post 'nndiary-request-accept-article server))
793
794 (deffoo nndiary-request-replace-article (article group buffer)
795   (nndiary-possibly-change-directory group)
796   (save-excursion
797     (set-buffer buffer)
798     (nndiary-possibly-create-directory group)
799     (let ((chars (nnmail-insert-lines))
800           (art (concat (int-to-string article) "\t"))
801           headers)
802       (when (ignore-errors
803               (nnmail-write-region
804                (point-min) (point-max)
805                (or (nndiary-article-to-file article)
806                    (expand-file-name (int-to-string article)
807                                      nndiary-current-directory))
808                nil (if (nnheader-be-verbose 5) nil 'nomesg))
809               t)
810         (setq headers (nndiary-parse-head chars article))
811         ;; Replace the NOV line in the NOV file.
812         (save-excursion
813           (set-buffer (nndiary-open-nov group))
814           (goto-char (point-min))
815           (if (or (looking-at art)
816                   (search-forward (concat "\n" art) nil t))
817               ;; Delete the old NOV line.
818               (delete-region (progn (beginning-of-line) (point))
819                              (progn (forward-line 1) (point)))
820             ;; The line isn't here, so we have to find out where
821             ;; we should insert it.  (This situation should never
822             ;; occur, but one likes to make sure...)
823             (while (and (looking-at "[0-9]+\t")
824                         (< (string-to-int
825                             (buffer-substring
826                              (match-beginning 0) (match-end 0)))
827                            article)
828                         (zerop (forward-line 1)))))
829           (beginning-of-line)
830           (nnheader-insert-nov headers)
831           (nndiary-save-nov)
832           t)))))
833
834 (deffoo nndiary-request-delete-group (group &optional force server)
835   (nndiary-possibly-change-directory group server)
836   (when force
837     ;; Delete all articles in GROUP.
838     (let ((articles
839            (directory-files
840             nndiary-current-directory t
841             (concat nnheader-numerical-short-files
842                     "\\|" (regexp-quote nndiary-nov-file-name) "$")))
843           article)
844       (while articles
845         (setq article (pop articles))
846         (when (file-writable-p article)
847           (nnheader-message 5 "Deleting article %s in %s..." article group)
848           (funcall nnmail-delete-file-function article))))
849     ;; Try to delete the directory itself.
850     (ignore-errors (delete-directory nndiary-current-directory)))
851   ;; Remove the group from all structures.
852   (setq nndiary-group-alist
853         (delq (assoc group nndiary-group-alist) nndiary-group-alist)
854         nndiary-current-group nil
855         nndiary-current-directory nil)
856   ;; Save the active file.
857   (nnmail-save-active nndiary-group-alist nndiary-active-file)
858   t)
859
860 (deffoo nndiary-request-rename-group (group new-name &optional server)
861   (nndiary-possibly-change-directory group server)
862   (let ((new-dir (nnmail-group-pathname new-name nndiary-directory))
863         (old-dir (nnmail-group-pathname group nndiary-directory)))
864     (when (ignore-errors
865             (make-directory new-dir t)
866             t)
867       ;; We move the articles file by file instead of renaming
868       ;; the directory -- there may be subgroups in this group.
869       ;; One might be more clever, I guess.
870       (let ((files (nnheader-article-to-file-alist old-dir)))
871         (while files
872           (rename-file
873            (concat old-dir (cdar files))
874            (concat new-dir (cdar files)))
875           (pop files)))
876       ;; Move .overview file.
877       (let ((overview (concat old-dir nndiary-nov-file-name)))
878         (when (file-exists-p overview)
879           (rename-file overview (concat new-dir nndiary-nov-file-name))))
880       (when (<= (length (directory-files old-dir)) 2)
881         (ignore-errors (delete-directory old-dir)))
882       ;; That went ok, so we change the internal structures.
883       (let ((entry (assoc group nndiary-group-alist)))
884         (when entry
885           (setcar entry new-name))
886         (setq nndiary-current-directory nil
887               nndiary-current-group nil)
888         ;; Save the new group alist.
889         (nnmail-save-active nndiary-group-alist nndiary-active-file)
890         t))))
891
892 (deffoo nndiary-set-status (article name value &optional group server)
893   (nndiary-possibly-change-directory group server)
894   (let ((file (nndiary-article-to-file article)))
895     (cond
896      ((not (file-exists-p file))
897       (nnheader-report 'nndiary "File %s does not exist" file))
898      (t
899       (with-temp-file file
900         (nnheader-insert-file-contents file)
901         (nnmail-replace-status name value))
902       t))))
903
904 \f
905 ;;; Interface optional functions ============================================
906
907 (deffoo nndiary-request-update-info (group info &optional server)
908   (nndiary-possibly-change-directory group)
909   (let ((timestamp (gnus-group-parameter-value (gnus-info-params info)
910                                                'timestamp t)))
911     (if (not timestamp)
912         (nnheader-report 'nndiary "Group %s doesn't have a timestamp" group)
913       ;; else
914       ;; Figure out which articles should be re-new'ed
915       (let ((articles (nndiary-flatten (gnus-info-read info) 0))
916             article file unread buf)
917         (save-excursion
918           (setq buf (nnheader-set-temp-buffer " *nndiary update*"))
919           (while (setq article (pop articles))
920             (setq file (concat nndiary-current-directory
921                                (int-to-string article)))
922             (and (file-exists-p file)
923                  (nndiary-renew-article-p file timestamp)
924                  (push article unread)))
925           ;;(message "unread: %s" unread)
926           (sit-for 1)
927           (kill-buffer buf))
928         (setq unread (sort unread '<))
929         (and unread
930              (gnus-info-set-read info (gnus-update-read-articles
931                                        (gnus-info-group info) unread t)))
932         ))
933     (run-hook-with-args 'nndiary-request-update-info-hooks
934                         (gnus-info-group info))
935     t))
936
937
938 \f
939 ;;; Internal functions ======================================================
940
941 (defun nndiary-article-to-file (article)
942   (nndiary-update-file-alist)
943   (let (file)
944     (if (setq file (cdr (assq article nndiary-article-file-alist)))
945         (expand-file-name file nndiary-current-directory)
946       ;; Just to make sure nothing went wrong when reading over NFS --
947       ;; check once more.
948       (if nndiary-check-directory-twice
949           (when (file-exists-p
950                  (setq file (expand-file-name (number-to-string article)
951                                               nndiary-current-directory)))
952             (nndiary-update-file-alist t)
953             file)))))
954
955 (defun nndiary-deletable-article-p (group article)
956   "Say whether ARTICLE in GROUP can be deleted."
957   (let (path)
958     (when (setq path (nndiary-article-to-file article))
959       (when (file-writable-p path)
960         (or (not nnmail-keep-last-article)
961             (not (eq (cdr (nth 1 (assoc group nndiary-group-alist)))
962                      article)))))))
963
964 ;; Find an article number in the current group given the Message-ID.
965 (defun nndiary-find-group-number (id)
966   (save-excursion
967     (set-buffer (get-buffer-create " *nndiary id*"))
968     (let ((alist nndiary-group-alist)
969           number)
970       ;; We want to look through all .overview files, but we want to
971       ;; start with the one in the current directory.  It seems most
972       ;; likely that the article we are looking for is in that group.
973       (if (setq number (nndiary-find-id nndiary-current-group id))
974           (cons nndiary-current-group number)
975         ;; It wasn't there, so we look through the other groups as well.
976         (while (and (not number)
977                     alist)
978           (or (string= (caar alist) nndiary-current-group)
979               (setq number (nndiary-find-id (caar alist) id)))
980           (or number
981               (setq alist (cdr alist))))
982         (and number
983              (cons (caar alist) number))))))
984
985 (defun nndiary-find-id (group id)
986   (erase-buffer)
987   (let ((nov (expand-file-name nndiary-nov-file-name
988                                (nnmail-group-pathname group
989                                                       nndiary-directory)))
990         number found)
991     (when (file-exists-p nov)
992       (nnheader-insert-file-contents nov)
993       (while (and (not found)
994                   (search-forward id nil t)) ; We find the ID.
995         ;; And the id is in the fourth field.
996         (if (not (and (search-backward "\t" nil t 4)
997                       (not (search-backward"\t" (gnus-point-at-bol) t))))
998             (forward-line 1)
999           (beginning-of-line)
1000           (setq found t)
1001           ;; We return the article number.
1002           (setq number
1003                 (ignore-errors (read (current-buffer))))))
1004       number)))
1005
1006 (defun nndiary-retrieve-headers-with-nov (articles &optional fetch-old)
1007   (if (or gnus-nov-is-evil nndiary-nov-is-evil)
1008       nil
1009     (let ((nov (expand-file-name nndiary-nov-file-name
1010                                  nndiary-current-directory)))
1011       (when (file-exists-p nov)
1012         (save-excursion
1013           (set-buffer nntp-server-buffer)
1014           (erase-buffer)
1015           (nnheader-insert-file-contents nov)
1016           (if (and fetch-old
1017                    (not (numberp fetch-old)))
1018               t                         ; Don't remove anything.
1019             (nnheader-nov-delete-outside-range
1020              (if fetch-old (max 1 (- (car articles) fetch-old))
1021                (car articles))
1022              (car (last articles)))
1023             t))))))
1024
1025 (defun nndiary-possibly-change-directory (group &optional server)
1026   (when (and server
1027              (not (nndiary-server-opened server)))
1028     (nndiary-open-server server))
1029   (if (not group)
1030       t
1031     (let ((pathname (nnmail-group-pathname group nndiary-directory))
1032           (file-name-coding-system nnmail-pathname-coding-system))
1033       (when (not (equal pathname nndiary-current-directory))
1034         (setq nndiary-current-directory pathname
1035               nndiary-current-group group
1036               nndiary-article-file-alist nil))
1037       (file-exists-p nndiary-current-directory))))
1038
1039 (defun nndiary-possibly-create-directory (group)
1040   (let ((dir (nnmail-group-pathname group nndiary-directory)))
1041     (unless (file-exists-p dir)
1042       (make-directory (directory-file-name dir) t)
1043       (nnheader-message 5 "Creating mail directory %s" dir))))
1044
1045 (defun nndiary-save-mail (group-art)
1046   "Called narrowed to an article."
1047   (let (chars headers)
1048     (setq chars (nnmail-insert-lines))
1049     (nnmail-insert-xref group-art)
1050     (run-hooks 'nnmail-prepare-save-mail-hook)
1051     (run-hooks 'nndiary-prepare-save-mail-hook)
1052     (goto-char (point-min))
1053     (while (looking-at "From ")
1054       (replace-match "X-From-Line: ")
1055       (forward-line 1))
1056     ;; We save the article in all the groups it belongs in.
1057     (let ((ga group-art)
1058           first)
1059       (while ga
1060         (nndiary-possibly-create-directory (caar ga))
1061         (let ((file (concat (nnmail-group-pathname
1062                              (caar ga) nndiary-directory)
1063                             (int-to-string (cdar ga)))))
1064           (if first
1065               ;; It was already saved, so we just make a hard link.
1066               (funcall nnmail-crosspost-link-function first file t)
1067             ;; Save the article.
1068             (nnmail-write-region (point-min) (point-max) file nil
1069                                  (if (nnheader-be-verbose 5) nil 'nomesg))
1070             (setq first file)))
1071         (setq ga (cdr ga))))
1072     ;; Generate a nov line for this article.  We generate the nov
1073     ;; line after saving, because nov generation destroys the
1074     ;; header.
1075     (setq headers (nndiary-parse-head chars))
1076     ;; Output the nov line to all nov databases that should have it.
1077     (let ((ga group-art))
1078       (while ga
1079         (nndiary-add-nov (caar ga) (cdar ga) headers)
1080         (setq ga (cdr ga))))
1081     group-art))
1082
1083 (defun nndiary-active-number (group)
1084   "Compute the next article number in GROUP."
1085   (let ((active (cadr (assoc group nndiary-group-alist))))
1086     ;; The group wasn't known to nndiary, so we just create an active
1087     ;; entry for it.
1088     (unless active
1089       ;; Perhaps the active file was corrupt?  See whether
1090       ;; there are any articles in this group.
1091       (nndiary-possibly-create-directory group)
1092       (nndiary-possibly-change-directory group)
1093       (unless nndiary-article-file-alist
1094         (setq nndiary-article-file-alist
1095               (sort
1096                (nnheader-article-to-file-alist nndiary-current-directory)
1097                'car-less-than-car)))
1098       (setq active
1099             (if nndiary-article-file-alist
1100                 (cons (caar nndiary-article-file-alist)
1101                       (caar (last nndiary-article-file-alist)))
1102               (cons 1 0)))
1103       (push (list group active) nndiary-group-alist))
1104     (setcdr active (1+ (cdr active)))
1105     (while (file-exists-p
1106             (expand-file-name (int-to-string (cdr active))
1107                               (nnmail-group-pathname group nndiary-directory)))
1108       (setcdr active (1+ (cdr active))))
1109     (cdr active)))
1110
1111 (defun nndiary-add-nov (group article headers)
1112   "Add a nov line for the GROUP base."
1113   (save-excursion
1114     (set-buffer (nndiary-open-nov group))
1115     (goto-char (point-max))
1116     (mail-header-set-number headers article)
1117     (nnheader-insert-nov headers)))
1118
1119 (defsubst nndiary-header-value ()
1120   (buffer-substring (match-end 0) (progn (end-of-line) (point))))
1121
1122 (defun nndiary-parse-head (chars &optional number)
1123   "Parse the head of the current buffer."
1124   (save-excursion
1125     (save-restriction
1126       (unless (zerop (buffer-size))
1127         (narrow-to-region
1128          (goto-char (point-min))
1129          (if (search-forward "\n\n" nil t) (1- (point)) (point-max))))
1130       ;; Fold continuation lines.
1131       (goto-char (point-min))
1132       (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1133         (replace-match " " t t))
1134       ;; Remove any tabs; they are too confusing.
1135       (subst-char-in-region (point-min) (point-max) ?\t ? )
1136       (let ((headers (nnheader-parse-head t)))
1137         (mail-header-set-chars headers chars)
1138         (mail-header-set-number headers number)
1139         headers))))
1140
1141 (defun nndiary-open-nov (group)
1142   (or (cdr (assoc group nndiary-nov-buffer-alist))
1143       (let ((buffer (get-buffer-create (format " *nndiary overview %s*"
1144                                                group))))
1145         (save-excursion
1146           (set-buffer buffer)
1147           (set (make-local-variable 'nndiary-nov-buffer-file-name)
1148                (expand-file-name
1149                 nndiary-nov-file-name
1150                 (nnmail-group-pathname group nndiary-directory)))
1151           (erase-buffer)
1152           (when (file-exists-p nndiary-nov-buffer-file-name)
1153             (nnheader-insert-file-contents nndiary-nov-buffer-file-name)))
1154         (push (cons group buffer) nndiary-nov-buffer-alist)
1155         buffer)))
1156
1157 (defun nndiary-save-nov ()
1158   (save-excursion
1159     (while nndiary-nov-buffer-alist
1160       (when (buffer-name (cdar nndiary-nov-buffer-alist))
1161         (set-buffer (cdar nndiary-nov-buffer-alist))
1162         (when (buffer-modified-p)
1163           (nnmail-write-region 1 (point-max) nndiary-nov-buffer-file-name
1164                                nil 'nomesg))
1165         (set-buffer-modified-p nil)
1166         (kill-buffer (current-buffer)))
1167       (setq nndiary-nov-buffer-alist (cdr nndiary-nov-buffer-alist)))))
1168
1169 ;;;###autoload
1170 (defun nndiary-generate-nov-databases (&optional server)
1171   "Generate NOV databases in all nndiary directories."
1172   (interactive (list (or (nnoo-current-server 'nndiary) "")))
1173   ;; Read the active file to make sure we don't re-use articles
1174   ;; numbers in empty groups.
1175   (nnmail-activate 'nndiary)
1176   (unless (nndiary-server-opened server)
1177     (nndiary-open-server server))
1178   (setq nndiary-directory (expand-file-name nndiary-directory))
1179   ;; Recurse down the directories.
1180   (nndiary-generate-nov-databases-1 nndiary-directory nil t)
1181   ;; Save the active file.
1182   (nnmail-save-active nndiary-group-alist nndiary-active-file))
1183
1184 (defun nndiary-generate-nov-databases-1 (dir &optional seen no-active)
1185   "Regenerate the NOV database in DIR."
1186   (interactive "DRegenerate NOV in: ")
1187   (setq dir (file-name-as-directory dir))
1188   ;; Only scan this sub-tree if we haven't been here yet.
1189   (unless (member (file-truename dir) seen)
1190     (push (file-truename dir) seen)
1191     ;; We descend recursively
1192     (let ((dirs (directory-files dir t nil t))
1193           dir)
1194       (while (setq dir (pop dirs))
1195         (when (and (not (string-match "^\\." (file-name-nondirectory dir)))
1196                    (file-directory-p dir))
1197           (nndiary-generate-nov-databases-1 dir seen))))
1198     ;; Do this directory.
1199     (let ((files (sort (nnheader-article-to-file-alist dir)
1200                        'car-less-than-car)))
1201       (if (not files)
1202           (let* ((group (nnheader-file-to-group
1203                          (directory-file-name dir) nndiary-directory))
1204                  (info (cadr (assoc group nndiary-group-alist))))
1205             (when info
1206               (setcar info (1+ (cdr info)))))
1207         (funcall nndiary-generate-active-function dir)
1208         ;; Generate the nov file.
1209         (nndiary-generate-nov-file dir files)
1210         (unless no-active
1211           (nnmail-save-active nndiary-group-alist nndiary-active-file))))))
1212
1213 (eval-when-compile (defvar files))
1214 (defun nndiary-generate-active-info (dir)
1215   ;; Update the active info for this group.
1216   (let* ((group (nnheader-file-to-group
1217                  (directory-file-name dir) nndiary-directory))
1218          (entry (assoc group nndiary-group-alist))
1219          (last (or (caadr entry) 0)))
1220     (setq nndiary-group-alist (delq entry nndiary-group-alist))
1221     (push (list group
1222                 (cons (or (caar files) (1+ last))
1223                       (max last
1224                            (or (let ((f files))
1225                                  (while (cdr f) (setq f (cdr f)))
1226                                  (caar f))
1227                                0))))
1228           nndiary-group-alist)))
1229
1230 (defun nndiary-generate-nov-file (dir files)
1231   (let* ((dir (file-name-as-directory dir))
1232          (nov (concat dir nndiary-nov-file-name))
1233          (nov-buffer (get-buffer-create " *nov*"))
1234          chars file headers)
1235     (save-excursion
1236       ;; Init the nov buffer.
1237       (set-buffer nov-buffer)
1238       (buffer-disable-undo)
1239       (erase-buffer)
1240       (set-buffer nntp-server-buffer)
1241       ;; Delete the old NOV file.
1242       (when (file-exists-p nov)
1243         (funcall nnmail-delete-file-function nov))
1244       (while files
1245         (unless (file-directory-p (setq file (concat dir (cdar files))))
1246           (erase-buffer)
1247           (nnheader-insert-file-contents file)
1248           (narrow-to-region
1249            (goto-char (point-min))
1250            (progn
1251              (search-forward "\n\n" nil t)
1252              (setq chars (- (point-max) (point)))
1253              (max 1 (1- (point)))))
1254           (unless (zerop (buffer-size))
1255             (goto-char (point-min))
1256             (setq headers (nndiary-parse-head chars (caar files)))
1257             (save-excursion
1258               (set-buffer nov-buffer)
1259               (goto-char (point-max))
1260               (nnheader-insert-nov headers)))
1261           (widen))
1262         (setq files (cdr files)))
1263       (save-excursion
1264         (set-buffer nov-buffer)
1265         (nnmail-write-region 1 (point-max) nov nil 'nomesg)
1266         (kill-buffer (current-buffer))))))
1267
1268 (defun nndiary-nov-delete-article (group article)
1269   (save-excursion
1270     (set-buffer (nndiary-open-nov group))
1271     (when (nnheader-find-nov-line article)
1272       (delete-region (point) (progn (forward-line 1) (point)))
1273       (when (bobp)
1274         (let ((active (cadr (assoc group nndiary-group-alist)))
1275               num)
1276           (when active
1277             (if (eobp)
1278                 (setf (car active) (1+ (cdr active)))
1279               (when (and (setq num (ignore-errors (read (current-buffer))))
1280                          (numberp num))
1281                 (setf (car active) num)))))))
1282     t))
1283
1284 (defun nndiary-update-file-alist (&optional force)
1285   (when (or (not nndiary-article-file-alist)
1286             force)
1287     (setq nndiary-article-file-alist
1288           (nnheader-article-to-file-alist nndiary-current-directory))))
1289
1290
1291 (defun nndiary-string-to-int (str min &optional max)
1292   ;; Like `string-to-int' but barf if STR is not exactly an integer, and not
1293   ;; within the specified bounds.
1294   ;; Signals are caught by `nndiary-schedule'.
1295   (if (not (string-match "^[ \t]*[0-9]+[ \t]*$" str))
1296       (nndiary-error "not an integer value")
1297     ;; else
1298     (let ((val (string-to-int str)))
1299       (and (or (< val min)
1300                (and max (> val max)))
1301            (nndiary-error "value out of range"))
1302       val)))
1303
1304 (defun nndiary-parse-schedule-value (str min-or-values max)
1305   ;; Parse the schedule string STR, or signal an error.
1306   ;; Signals are caught by `nndary-schedule'.
1307   (if (string-match "[ \t]*\\*[ \t]*" str)
1308       ;; unspecifyed
1309       nil
1310     ;; specifyed
1311     (if (listp min-or-values)
1312         ;; min-or-values is values
1313         ;; #### NOTE: this is actually only a hack for time zones.
1314         (let ((val (and (string-match "[ \t]*\\([^ \t]+\\)[ \t]*" str)
1315                         (match-string 1 str))))
1316           (if (and val (setq val (assoc val min-or-values)))
1317               (list (cadr val))
1318             (nndiary-error "invalid syntax")))
1319       ;; min-or-values is min
1320       (mapcar
1321        (lambda (val)
1322          (let ((res (split-string val "-")))
1323            (cond
1324             ((= (length res) 1)
1325              (nndiary-string-to-int (car res) min-or-values max))
1326             ((= (length res) 2)
1327              ;; don't know if crontab accepts this, but ensure
1328              ;; that BEG is <= END
1329              (let ((beg (nndiary-string-to-int (car res) min-or-values max))
1330                    (end (nndiary-string-to-int (cadr res) min-or-values max)))
1331                (cond ((< beg end)
1332                       (cons beg end))
1333                      ((= beg end)
1334                       beg)
1335                      (t
1336                       (cons end beg)))))
1337             (t
1338              (nndiary-error "invalid syntax")))
1339            ))
1340        (split-string str ",")))
1341     ))
1342
1343 ;; ### FIXME: remove this function if it's used only once.
1344 (defun nndiary-parse-schedule (head min-or-values max)
1345   ;; Parse the cron-like value of header X-Diary-HEAD in current buffer.
1346   ;; - Returns nil if `*'
1347   ;; - Otherwise returns a list of integers and/or ranges (BEG . END)
1348   ;; The exception is the Timze-Zone value which is always of the form (STR).
1349   ;; Signals are caught by `nndary-schedule'.
1350   (let ((header (format "^X-Diary-%s: \\(.*\\)$" head)))
1351     (goto-char (point-min))
1352     (if (not (re-search-forward header nil t))
1353         (nndiary-error "header missing")
1354       ;; else
1355       (nndiary-parse-schedule-value (match-string 1) min-or-values max))
1356     ))
1357
1358 (defsubst nndiary-schedule ()
1359   (let (head)
1360     (condition-case arg
1361         (mapcar
1362          (lambda (elt)
1363            (setq head (nth 0 elt))
1364            (nndiary-parse-schedule (nth 0 elt) (nth 1 elt) (nth 2 elt)))
1365          nndiary-headers)
1366       (t
1367        (nnheader-report 'nndiary "X-Diary-%s header parse error: %s."
1368                         head (cdr arg))
1369        nil))
1370     ))
1371
1372 (defun nndiary-max (spec)
1373   ;; Returns the max of specification SPEC, or nil for permanent schedules.
1374   (unless (null spec)
1375     (let ((elts spec)
1376           (max 0)
1377           elt)
1378       (while (setq elt (pop elts))
1379         (if (integerp elt)
1380             (and (> elt max) (setq max elt))
1381           (and (> (cdr elt) max) (setq max (cdr elt)))))
1382       max)))
1383
1384 (defun nndiary-flatten (spec min &optional max)
1385   ;; flatten the spec by expanding ranges to all possible values.
1386   (let (flat n)
1387     (cond ((null spec)
1388            ;; this happens when I flatten something else than one of my
1389            ;; schedules (a list of read articles for instance).
1390            (unless (null max)
1391              (setq n min)
1392              (while (<= n max)
1393                (push n flat)
1394                (setq n (1+ n)))))
1395           (t
1396            (let ((elts spec)
1397                  elt)
1398              (while (setq elt (pop elts))
1399                (if (integerp elt)
1400                    (push elt flat)
1401                  ;; else
1402                  (setq n (car elt))
1403                  (while (<= n (cdr elt))
1404                    (push n flat)
1405                    (setq n (1+ n))))))))
1406     flat))
1407
1408 (defun nndiary-unflatten (spec)
1409   ;; opposite of flatten: build ranges if possible
1410   (setq spec (sort spec '<))
1411   (let (min max res)
1412     (while (setq min (pop spec))
1413       (setq max min)
1414       (while (and (car spec) (= (car spec) (1+ max)))
1415         (setq max (1+ max))
1416         (pop spec))
1417       (if (= max min)
1418           (setq res (append res (list min)))
1419         (setq res (append res (list (cons min max))))))
1420     res))
1421
1422 (defun nndiary-compute-reminders (date)
1423   ;; Returns a list of times corresponding to the reminders of date DATE.
1424   ;; See the comment in `nndiary-reminders' about rounding.
1425   (let* ((reminders nndiary-reminders)
1426          (date-elts (decode-time date))
1427          ;; ### NOTE: out-of-range values are accepted by encode-time. This
1428          ;; makes our life easier.
1429          (monday (- (nth 3 date-elts)
1430                     (if nndiary-week-starts-on-monday
1431                         (if (zerop (nth 6 date-elts))
1432                             6
1433                           (- (nth 6 date-elts) 1))
1434                       (nth 6 date-elts))))
1435          reminder res)
1436     ;; remove the DOW and DST entries
1437     (setf (nthcdr 6 date-elts) (nthcdr 8 date-elts))
1438     (while (setq reminder (pop reminders))
1439       (push
1440        (cond ((eq (cdr reminder) 'minute)
1441               (subtract-time
1442                (apply 'encode-time 0 (nthcdr 1 date-elts))
1443                (seconds-to-time (* (car reminder) 60.0))))
1444              ((eq (cdr reminder) 'hour)
1445               (subtract-time
1446                (apply 'encode-time 0 0 (nthcdr 2 date-elts))
1447                (seconds-to-time (* (car reminder) 3600.0))))
1448              ((eq (cdr reminder) 'day)
1449               (subtract-time
1450                (apply 'encode-time 0 0 0 (nthcdr 3 date-elts))
1451                (seconds-to-time (* (car reminder) 86400.0))))
1452              ((eq (cdr reminder) 'week)
1453               (subtract-time
1454                (apply 'encode-time 0 0 0 monday (nthcdr 4 date-elts))
1455                (seconds-to-time (* (car reminder) 604800.0))))
1456              ((eq (cdr reminder) 'month)
1457               (subtract-time
1458                (apply 'encode-time 0 0 0 1 (nthcdr 4 date-elts))
1459                (seconds-to-time (* (car reminder) 18748800.0))))
1460              ((eq (cdr reminder) 'year)
1461               (subtract-time
1462                (apply 'encode-time 0 0 0 1 1 (nthcdr 5 date-elts))
1463                (seconds-to-time (* (car reminder) 400861056.0)))))
1464        res))
1465     (sort res 'time-less-p)))
1466
1467 (defun nndiary-last-occurence (sched)
1468   ;; Returns the last occurence of schedule SCHED as an Emacs time struct, or
1469   ;; nil for permanent schedule or errors.
1470   (let ((minute (nndiary-max (nth 0 sched)))
1471         (hour (nndiary-max (nth 1 sched)))
1472         (year (nndiary-max (nth 4 sched)))
1473         (time-zone (or (and (nth 6 sched) (car (nth 6 sched)))
1474                        (current-time-zone))))
1475     (when year
1476       (or minute (setq minute 59))
1477       (or hour (setq hour 23))
1478       ;; I'll just compute all possible values and test them by decreasing
1479       ;; order until one succeeds. This is probably quide rude, but I got
1480       ;; bored in finding a good algorithm for doing that ;-)
1481       ;; ### FIXME: remove identical entries.
1482       (let ((dom-list (nth 2 sched))
1483             (month-list (sort (nndiary-flatten (nth 3 sched) 1 12) '>))
1484             (year-list (sort (nndiary-flatten (nth 4 sched) 1971) '>))
1485             (dow-list (nth 5 sched)))
1486         ;; Special case: an asterisk in one of the days specifications means
1487         ;; that only the other should be taken into account. If both are
1488         ;; unspecified, you would get all possible days in both.
1489         (cond ((null dow-list)
1490                ;; this gets all days if dom-list is nil
1491                (setq dom-list (nndiary-flatten dom-list 1 31)))
1492               ((null dom-list)
1493                ;; this also gets all days if dow-list is nil
1494                (setq dow-list (nndiary-flatten dow-list 0 6)))
1495               (t
1496                (setq dom-list (nndiary-flatten dom-list 1 31))
1497                (setq dow-list (nndiary-flatten dow-list 0 6))))
1498         (or
1499          (catch 'found
1500            (while (setq year (pop year-list))
1501              (let ((months month-list)
1502                    month)
1503                (while (setq month (pop months))
1504                  ;; Now we must merge the Dows with the Doms. To do that, we
1505                  ;; have to know which day is the 1st one for this month.
1506                  ;; Maybe there's simpler, but decode-time(encode-time) will
1507                  ;; give us the answer.
1508                  (let ((first (nth 6 (decode-time
1509                                       (encode-time 0 0 0 1 month year
1510                                                    time-zone))))
1511                        (max (cond ((= month 2)
1512                                    (if (date-leap-year-p year) 29 28))
1513                                   ((<= month 7)
1514                                    (if (zerop (% month 2)) 30 31))
1515                                   (t
1516                                    (if (zerop (% month 2)) 31 30))))
1517                        (doms dom-list)
1518                        (dows dow-list)
1519                        day days)
1520                    ;; first, review the doms to see if they are valid.
1521                    (while (setq day (pop doms))
1522                      (and (<= day max)
1523                           (push day days)))
1524                    ;; second add all possible dows
1525                    (while (setq day (pop dows))
1526                      ;; days start at 1.
1527                      (setq day (1+ (- day first)))
1528                      (and (< day 0) (setq day (+ 7 day)))
1529                      (while (<= day max)
1530                        (push day days)
1531                        (setq day (+ 7 day))))
1532                    ;; Finally, if we have some days, they are valid
1533                    (when days
1534                      (sort days '>)
1535                      (throw 'found
1536                             (encode-time 0 minute hour
1537                                          (car days) month year time-zone)))
1538                    )))))
1539          ;; There's an upper limit, but we didn't find any last occurence.
1540          ;; This means that the schedule is undecidable. This can happen if
1541          ;; you happen to say something like "each Feb 31 until 2038".
1542          (progn
1543            (nnheader-report 'nndiary "Undecidable schedule")
1544            nil))
1545         ))))
1546
1547 (defun nndiary-next-occurence (sched now)
1548   ;; Returns the next occurence of schedule SCHED, starting from time NOW.
1549   ;; If there's no next occurence, returns the last one (if any) which is then
1550   ;; in the past.
1551   (let* ((today (decode-time now))
1552          (this-minute (nth 1 today))
1553          (this-hour (nth 2 today))
1554          (this-day (nth 3 today))
1555          (this-month (nth 4 today))
1556          (this-year (nth 5 today))
1557          (minute-list (sort (nndiary-flatten (nth 0 sched) 0 59) '<))
1558          (hour-list (sort (nndiary-flatten (nth 1 sched) 0 23) '<))
1559          (dom-list (nth 2 sched))
1560          (month-list (sort (nndiary-flatten (nth 3 sched) 1 12) '<))
1561          (years (if (nth 4 sched)
1562                     (sort (nndiary-flatten (nth 4 sched) 1971) '<)
1563                   t))
1564          (dow-list (nth 5 sched))
1565          (year (1- this-year))
1566          (time-zone (or (and (nth 6 sched) (car (nth 6 sched)))
1567                         (current-time-zone))))
1568     ;; Special case: an asterisk in one of the days specifications means that
1569     ;; only the other should be taken into account. If both are unspecified,
1570     ;; you would get all possible days in both.
1571     (cond ((null dow-list)
1572            ;; this gets all days if dom-list is nil
1573            (setq dom-list (nndiary-flatten dom-list 1 31)))
1574           ((null dom-list)
1575            ;; this also gets all days if dow-list is nil
1576            (setq dow-list (nndiary-flatten dow-list 0 6)))
1577           (t
1578            (setq dom-list (nndiary-flatten dom-list 1 31))
1579            (setq dow-list (nndiary-flatten dow-list 0 6))))
1580     ;; Remove past years.
1581     (unless (eq years t)
1582       (while (and (car years) (< (car years) this-year))
1583         (pop years)))
1584     (if years
1585         ;; Because we might not be limited in years, we must guard against
1586         ;; infinite loops. Appart from cases like Feb 31, there are probably
1587         ;; other ones, (no monday XXX 2nd etc). I don't know any algorithm to
1588         ;; decide this, so I assume that if we reach 10 years later, the
1589         ;; schedule is undecidable.
1590         (or
1591          (catch 'found
1592            (while (if (eq years t)
1593                       (and (setq year (1+ year))
1594                            (<= year (+ 10 this-year)))
1595                     (setq year (pop years)))
1596              (let ((months month-list)
1597                    month)
1598                ;; Remove past months for this year.
1599                (and (= year this-year)
1600                     (while (and (car months) (< (car months) this-month))
1601                       (pop months)))
1602                (while (setq month (pop months))
1603                  ;; Now we must merge the Dows with the Doms. To do that, we
1604                  ;; have to know which day is the 1st one for this month.
1605                  ;; Maybe there's simpler, but decode-time(encode-time) will
1606                  ;; give us the answer.
1607                  (let ((first (nth 6 (decode-time
1608                                       (encode-time 0 0 0 1 month year
1609                                                    time-zone))))
1610                        (max (cond ((= month 2)
1611                                    (if (date-leap-year-p year) 29 28))
1612                                   ((<= month 7)
1613                                    (if (zerop (% month 2)) 30 31))
1614                                   (t
1615                                    (if (zerop (% month 2)) 31 30))))
1616                        (doms dom-list)
1617                        (dows dow-list)
1618                        day days)
1619                    ;; first, review the doms to see if they are valid.
1620                    (while (setq day (pop doms))
1621                      (and (<= day max)
1622                           (push day days)))
1623                    ;; second add all possible dows
1624                    (while (setq day (pop dows))
1625                      ;; days start at 1.
1626                      (setq day (1+ (- day first)))
1627                      (and (< day 0) (setq day (+ 7 day)))
1628                      (while (<= day max)
1629                        (push day days)
1630                        (setq day (+ 7 day))))
1631                    ;; Aaaaaaall right. Now we have a valid list of DAYS for
1632                    ;; this month and this year.
1633                    (when days
1634                      (setq days (sort days '<))
1635                      ;; Remove past days for this year and this month.
1636                      (and (= year this-year)
1637                           (= month this-month)
1638                           (while (and (car days) (< (car days) this-day))
1639                             (pop days)))
1640                      (while (setq day (pop days))
1641                        (let ((hours hour-list)
1642                              hour)
1643                          ;; Remove past hours for this year, this month and
1644                          ;; this day.
1645                          (and (= year this-year)
1646                               (= month this-month)
1647                               (= day this-day)
1648                               (while (and (car hours)
1649                                           (< (car hours) this-hour))
1650                                 (pop hours)))
1651                          (while (setq hour (pop hours))
1652                            (let ((minutes minute-list)
1653                                  minute)
1654                              ;; Remove past hours for this year, this month,
1655                              ;; this day and this hour.
1656                              (and (= year this-year)
1657                                   (= month this-month)
1658                                   (= day this-day)
1659                                   (= hour this-hour)
1660                                   (while (and (car minutes)
1661                                               (< (car minutes) this-minute))
1662                                     (pop minutes)))
1663                              (while (setq minute (pop minutes))
1664                                ;; Ouch! Here, we've got a complete valid
1665                                ;; schedule. It's a good one if it's in the
1666                                ;; future.
1667                                (let ((time (encode-time 0 minute hour day
1668                                                         month year
1669                                                         time-zone)))
1670                                  (and (time-less-p now time)
1671                                       (throw 'found time)))
1672                                ))))
1673                        ))
1674                    )))
1675              ))
1676          (nndiary-last-occurence sched))
1677       ;; else
1678       (nndiary-last-occurence sched))
1679     ))
1680
1681 (defun nndiary-expired-article-p (file)
1682   (with-temp-buffer
1683     (if (nnheader-insert-head file)
1684         (let ((sched (nndiary-schedule)))
1685           ;; An article has expired if its last schedule (if any) is in the
1686           ;; past. A permanent schedule never expires.
1687           (and sched
1688                (setq sched (nndiary-last-occurence sched))
1689                (time-less-p sched (current-time))))
1690       ;; else
1691       (nnheader-report 'nndiary "Could not read file %s" file)
1692       nil)
1693     ))
1694
1695 (defun nndiary-renew-article-p (file timestamp)
1696   (erase-buffer)
1697   (if (nnheader-insert-head file)
1698       (let ((now (current-time))
1699             (sched (nndiary-schedule)))
1700         ;; The article should be re-considered as unread if there's a reminder
1701         ;; between the group timestamp and the current time.
1702         (when (and sched (setq sched (nndiary-next-occurence sched now)))
1703           (let ((reminders ;; add the next occurence itself at the end.
1704                  (append (nndiary-compute-reminders sched) (list sched))))
1705             (while (and reminders (time-less-p (car reminders) timestamp))
1706               (pop reminders))
1707             ;; The reminders might be empty if the last date is in the past,
1708             ;; or we've got at least the next occurence itself left. All past
1709             ;; dates are renewed.
1710             (or (not reminders)
1711                 (time-less-p (car reminders) now)))
1712           ))
1713     ;; else
1714     (nnheader-report 'nndiary "Could not read file %s" file)
1715     nil))
1716
1717 ;; The end... ===============================================================
1718
1719 (mapcar
1720  (lambda (elt)
1721    (let ((header (intern (format "X-Diary-%s" (car elt)))))
1722      ;; Required for building NOV databases and some other stuff
1723      (add-to-list 'gnus-extra-headers header)
1724      (add-to-list 'nnmail-extra-headers header)))
1725  nndiary-headers)
1726
1727 (unless (assoc "nndiary" gnus-valid-select-methods)
1728   (gnus-declare-backend "nndiary" 'post-mail 'respool 'address))
1729
1730 (provide 'nndiary)
1731
1732
1733 ;;; nndiary.el ends here