summaryrefslogtreecommitdiff
path: root/src/md.py
blob: 4ab9aa1a5da38a338b582091d405edf479f85f00 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/python3
import os
import os.path
import sys


#from jinja2 import Environment, PackageLoader, Template, FileSystemLoader
from jinja2 import Environment, PackageLoader, Template, FileSystemLoader

import mistune
from mistune.util import escape as escape_text

#global name for templates
article = {}#

class TocAnchorRenderer(mistune.HTMLRenderer):
	count = 1
	def heading(self, text, level, **attrs):
		tag = 'h' + str(level)
		html = '<' + tag
		_id = attrs.get('id')
		#if _id:
		#	html += ' id="toc-' + _id + '"'
		html += ' id="toc-' + str(self.count) + '"'
		self.count += 1
		return html + '>' + text + '</' + tag + '>\n'
	def block_html(self, html: str) -> str:
        #if self._escape:
        #    return '<p>' + escape_text(html) + '</p>\n'
        #return html + '\n'
		return html

################################################################################
#get first tags and use them to configure some bits
def get_tags(data):
	text = ""
	tag_section = True
	for line in data.split("\n"):
		if tag_section:
			tag = line.split(":")
			l = len(tag)
			if l != 2:
				tag_section = False
				text += line+"\n"
			else:
				article[tag[0]] = tag[1]
		else:
			text += line+"\n"
	return text

################################################################################
#
def generate_toc(tags):
	cnt = 3
	headers_list = []
	for tag in tags:
		if tag["type"] == "heading":
			attrs = tag["attrs"]
			#attrs["id"] = "toc-none"
			headers_list.append({"header":tag["children"][0]["raw"], "level":attrs["level"]})
	#print(headers_list)
	############################
	#generate toc
	html_toc = '<ul id="table-of-content">\n'
	first_level = None
	last_level = None
	cnt = 1
	for el in headers_list:
		l = int(el["level"])
		
		if first_level is None:
			first_level = l
			last_level = l
		#same level
		elif last_level == l:
			html_toc += '</li>\n<li><a href="#toc-%d">%s</a>' % (cnt, el["header"] )
		# if last level smaller then open one more
		elif last_level == l - 1:
			last_level = l
			html_toc += '<ul>\n<li><a href="#toc-%d">%s</a>' % (cnt, el["header"])
		elif last_level > l:
			# close indention
			html_toc += '</li>'
			while last_level > l:
				html_toc += '</ul>\n</li>\n'
				last_level -= 1
			html_toc += '<li><a href="#toc-%d">%s</a>' % (cnt, el["header"])
		cnt += 1

	html_toc += '</li>\n'
	while last_level > first_level:
		html_toc += '</ul>\n<!--</li>-->\n'
		last_level -= 1

	html_toc += '</ul>'
	return html_toc

################################################################################
#check if there is input file
if len(sys.argv) < 2:
	print("ERROR: Exit . Need more arguments")
	sys.exit(0)

md_fn = sys.argv[1]

#template loader
loader = FileSystemLoader( "/home/fam/downloads/source/repos/md-site/src/templ" )
templ_env = Environment( loader = loader )

t = templ_env.get_template("main.thtml")

##get md file
f = open( md_fn, "r" )
data = f.read()
data = get_tags(data)
#toc = TocRenderer()
## Create AST rendered
markdown_raw = mistune.create_markdown(renderer=None)
raw_tags = markdown_raw(data)
html_toc = generate_toc(raw_tags)

###########################
## Create AST -> Markdown renderer
#markdown_ast = mistune.create_markdown(renderer='ast')
#print(markdown_ast(raw_tags))

custom_render = True
if not custom_render:
	## Mistune generate MTL
	md_rend = html_toc + mistune.html(data)
else:
	## Mistune with custom renderer
	#markdown = mistune.create_markdown(renderer=TocAnchorRenderer(),escape=False,plugins=['strikethrough', 'footnotes', 'table', 'speedup'])
	markdown = mistune.create_markdown(
		escape=False,
		#plugins=['strikethrough', 'footnotes', 'table', 'speedup'],
		plugins=['url','table'],
		renderer=TocAnchorRenderer()
	)
	md_rend = html_toc + markdown(data)

#print t.render( article=article, block = md_rend )
print(t.render( article=article, block = md_rend ))
#print(raw_tags)

f.close()