#!/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 '
' + escape_text(html) + '
\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 = '\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 += '\n- %s' % (cnt, el["header"] )
# if last level smaller then open one more
elif last_level == l - 1:
last_level = l
html_toc += '
\n- %s' % (cnt, el["header"])
elif last_level > l:
# close indention
html_toc += '
'
while last_level > l:
html_toc += '
\n \n'
last_level -= 1
html_toc += '- %s' % (cnt, el["header"])
cnt += 1
html_toc += '
\n'
while last_level > first_level:
html_toc += '
\n\n'
last_level -= 1
html_toc += ''
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()