2 # parse a org-mode file and convert it to JSON
4 __author__
= "Sridhar Ratnakumar <http://nearfar.org/>"
7 from itertools
import count
9 from simplejson
import dumps
14 >>> print list(rindexed(l))
15 [(2, 9), (1, 7), (0, 5)]
18 range(len(seq
))[::-1],
28 """Parse the given org file text and return the Python data structure
30 >>> j = org2py(open('sample.org').read())
43 lines
= orgtext
.splitlines()
45 return '\n'.join(lines
[i1
:i2
])
48 last_index
= len(lines
)
49 for index
, line
in rindexed(lines
):
50 if line
.startswith("*"):
51 yield [index
, e(index
, last_index
)]
55 STARS_PAT
= re
.compile(r
"^(\**) ")
58 >>> nstars("*** Foo Bar")
61 return len(STARS_PAT
.match(line
).group(1))
63 def node(text
, children
):
64 return (text
, children
)
66 items
= list(items
) # exhaust the iterator, if any.
68 # Create [[], [], [], ...] to hold stack values
69 # for level=k at index k.
70 # hence, we need a stack of length 1+max(k)
71 max_level
= max([nstars(t
) for i
,t
in items
])
72 istack
= [[] for x
in range(1+max_level
)]
74 pn
= nstars(items
[0][1]) # last item
75 for index
, text
in items
:
80 istack
[pn
].append(node(text
, []))
83 istack
[n
].append(node(text
, reverse(istack
[pn
])))
86 # children of one of the top nodes
87 istack
[n
].append(node(text
, []))
90 return reverse(istack
[1])
92 return hier(by_star())
94 def org2json(orgtext
):
96 >>> org2py(open('sample.org').read())
98 return dumps(org2py(orgtext
))
101 if __name__
== '__main__':
102 from doctest
import testmod