Last active
May 28, 2019 14:40
-
-
Save hayashikun/f1d31a13d324338b2387670f798d68ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import os | |
import re | |
import sys | |
import pyperclip | |
BraKetDefinition = r""" | |
[tex: | |
\def\bra#1{\mathinner{\left\langle{#1}\right|}} | |
\def\ket#1{\mathinner{\left|{#1}\right\rangle}} | |
\def\braket#1#2{\mathinner{\left\langle{#1}\middle|#2\right\rangle}} | |
] | |
""" | |
def app(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-p", "--path", help="Markdown file path. If empty, the text on clipboard is used.") | |
parser.add_argument("-d", "--dump", action="store_true", help="Dump converted result.") | |
parser.add_argument("-bk", "--braket", action="store_true", help="Add bra ket definition.") | |
args = parser.parse_args() | |
if args.path is None: | |
md_text = pyperclip.paste() | |
else: | |
if os.path.exists(args.path): | |
with open(args.path) as f: | |
md_text = f.read() | |
else: | |
print("No such markdown file.") | |
return 2 | |
display_math = "<div align=\"center\">\n[tex:\\begin{{aligned}}\n{}\n\\end{{aligned}}]\n</div>" | |
for m in re.findall(r"(\$\$\n(.+?)\n\$\$)", md_text, flags=(re.MULTILINE | re.DOTALL)): | |
dm = m[1].replace("[", r"\[").replace("]", r"\]") | |
md_text = md_text.replace(m[0], display_math.format(dm)) | |
inline_math = "[tex: {} ]" | |
for m in re.findall(r"(\$(.+?)\$)", md_text, flags=(re.MULTILINE | re.DOTALL)): | |
im = m[1].replace("_", " _ ").replace("^", " ^ ").replace("[", r"\\[").replace("]", r"\\]") | |
md_text = md_text.replace(m[0], inline_math.format(im)) | |
if args.braket: | |
md_text = BraKetDefinition + md_text | |
pyperclip.copy(md_text) | |
if args.dump: | |
print(md_text) | |
return 0 | |
if __name__ == "__main__": | |
res = app() | |
sys.exit(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment