You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

88 lines
2.7 KiB

#!/usr/bin/env python3
# Import local files
from whitespace import *
from command import *
from util import *
import builtin_commands
from panflute import *
import re
import sys
from mj_show import show
flags = ["dog"]
def transform(e: Element):
"""Transform the AST, making format-agnostic changes."""
if isinstance(e, Whitespace) and bavlna(e):
e = replaceEl(e, NBSP())
if hasattr(e, "attributes"):
# `if` attribute. Only show this element if flag is set.
if "if" in e.attributes:
if not e.attributes["if"] in flags:
deleteEl(e)
return
# `ifn` attribute. Only show this element if flag is NOT set
if "ifn" in e.attributes:
if e.attributes["ifn"] in flags:
deleteEl(e)
return
# `c` attribute. Execute a command with the name saved in this attribute.
if (isinstance(e, Div) or isinstance(e, Span)) and "c" in e.attributes:
if isinstance(e, Div):
e = replaceEl(e, MultilineCommand(*e.content, identifier=e.identifier, classes=e.classes, attributes=e.attributes))
else:
e = replaceEl(e, InlineCommand(*e.content, identifier=e.identifier, classes=e.classes, attributes=e.attributes))
if isinstance(e, CodeBlock) and hasattr(e, "classes") and "python" in e.classes and "run" in e.classes:
exec(e.text)
deleteEl(e)
return
# Handle special command shorthand [!commandname]{}
if isinstance(e, Span) and len(e.content) == 1 and isinstance(e.content[0], Str) and re.match(r"^![\w.]+$", e.content[0].text):
e = replaceEl(e, InlineCommand(identifier=e.identifier, classes=e.classes, attributes={**e.attributes, "c": e.content[0].text[1:]}))
# The command is executed first and then its contents are transformed. TODO: Is this what we want?
if isinstance(e, Command):
if re.match(r"^[\w.]+$", e.attributes["c"]):
try:
e = e.call(eval(e.attributes["c"]))
except NameError:
raise NameError(f"Command not found: '{e.attributes['c']}'.")
else:
raise SyntaxError(f"Invalid command syntax: '{e.attributes['c']}'.")
# Recursively transform all contents.
if hasattr(e, "content"):
for c in e.content:
# Deleted elements are only marked to be deleted with a class, because otherwise
# it would mess up this for cycle.
transform(c)
# Delete elements marked to be deleted. This is somewhat inelegant.
ci = 0
while ci < len(e.content):
c = e.content[ci]
if hasattr(c, "classes") and "deleted" in c.classes:
del e.content[ci]
else:
ci+=1
doc = convert_text(open(sys.argv[1], "r").read(), standalone=True, extra_args=["-f", "markdown+fenced_code_attributes"])
print(show(doc))
transform(doc)
print("---------------------")
print(convert_text(doc, input_format="panflute", output_format="markdown"))