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