wikiobj

A python parsing library for the personal wiki pages.
git clone git://r-36.net/wikiobj
Log | Files | Refs | README | LICENSE

page.py (1202B)


      1 #
      2 # See LICENSE for licensing details.
      3 #
      4 # Copy me if you can.
      5 # by 20h
      6 #
      7 
      8 import io
      9 
     10 def parse(mdstr, topic="", subtopic=""):
     11 	"""
     12 	Parse wiki markdown into an dict / array tree.
     13 	"""
     14 
     15 	page = {}
     16 	page["topic"] = None
     17 	page["tree"] = {}
     18 	page["description"] = []
     19 
     20 	lastlevel = 0
     21 	depthlist = [page["description"]]
     22 	for line in io.StringIO(mdstr):
     23 		line = line.rstrip()
     24 		if len(line) == 0:
     25 			continue
     26 
     27 		if line.startswith("# ") and page["topic"] == None:
     28 			page["topic"] = line[2:]
     29 			continue
     30 		elif line[0] == '#':
     31 			while line[0] == '#':
     32 				line = line[1:]
     33 			line = line.lstrip()
     34 
     35 			page["tree"][line] = []
     36 			depthlist = [page["tree"][line]]
     37 			continue
     38 		else:
     39 			level = 0
     40 			while line[0] == '\t':
     41 				level += 1
     42 				line = line[1:]
     43 			if line.startswith("* "):
     44 				line = line[2:]
     45 			line = line.lstrip()
     46 
     47 			if level == lastlevel:
     48 				depthlist[-1].append(line)
     49 			elif level < lastlevel:
     50 				leveljump = lastlevel - level
     51 				if len(depthlist) > leveljump:
     52 					depthlist = depthlist[:-leveljump]
     53 				depthlist[-1].append(line)
     54 			elif level > lastlevel:
     55 				linea = [line]
     56 				depthlist[-1].append(linea)
     57 				depthlist.append(linea)
     58 			lastlevel = level
     59 			continue
     60 	
     61 	return page
     62