Skip to content

Instantly share code, notes, and snippets.

@MineRobber9000

MineRobber9000/gemini2pandocjson.py Secret

Last active Jan 12, 2021
Embed
What would you like to do?
gemini2pandocjson
def codeblock(lines,alt=None):
text = "\n".join(lines)
return {"t": "CodeBlock", "c": [["",([alt] if alt is not None else []),[]],text]}
def link(url,caption=None):
caption = url if caption is None else caption
return {"t": "Para", "c": [{"t": "Link", "c": [["",[],[]],para(caption)['c'],[url,""]]}]}
def header(c,text):
return {"t": "Header", "c": [c,["",[],[]],para(text)['c']]}
def listitem(blocks,text):
parsed = para(text)
parsed['t']="Plain"
parsed = [parsed]
if blocks[-1]['t']=="BulletList":
blocks[-1]['c'].append(parsed)
else:
blocks.append({"t": "BulletList", "c": [parsed]})
def quote(text):
return {"t": "BlockQuote", "c": [para(text)]}
def para(text):
text = text if text else " "
o=""
c=[]
for ch in text:
if ch==" ":
if o: c.append(dict(t="Str",c=o))
c.append(dict(t="Space"))
o=""
else:
o+=ch
if o: c.append(dict(t="Str",c=o))
return {"t": "Para", "c": c}
def gemtext2pandoc(gemtext):
lines = gemtext.rstrip("\r\n").splitlines()
in_pre = False
pre_alt = None
buffer = []
blocks = []
for line in lines:
if in_pre:
if line[:3]=="```":
in_pre=False
blocks.append(codeblock(buffer,pre_alt))
buffer=[]
pre_alt=None
else:
buffer.append(line)
else:
if line[:3]=="```":
pre_alt = line[3:]
pre_alt = pre_alt if pre_alt else None
in_pre=True
elif line[:2]=="=>":
parts = line[2:].strip().split(None,1)
blocks.append(link(*parts))
elif "#" in line[:3]:
text = line
c = 0
while text[0]=="#" and c<3:
c+=1
text=text[1:]
text=text.lstrip()
blocks.append(header(c,text))
elif line and line[0]=="*":
listitem(blocks,line[1:].strip())
elif line and line[0]==">":
blocks.append(quote(line[1:].strip()))
else:
blocks.append(para(line))
return {"pandoc-api-version":[1,22],"meta":{},"blocks":blocks}
import sys, json
if __name__=="__main__":
_, infile, outfile = sys.argv
with open(infile) as f: gemtext=f.read()
pandoc = gemtext2pandoc(gemtext)
with open(outfile,"w") as f: json.dump(pandoc,f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment