Skip to content

Instantly share code, notes, and snippets.

@yuvve
Last active March 31, 2023 09:31
Show Gist options
  • Save yuvve/00ac5a208d54cc6d88b68c489d99f7f7 to your computer and use it in GitHub Desktop.
Save yuvve/00ac5a208d54cc6d88b68c489d99f7f7 to your computer and use it in GitHub Desktop.
Takes Obsidian formatted string from clipboard and replaces it with Anki formatted string
import re, pyperclip
# Changes
# $...$ to \(...\)
# $$...$$ to \[...\]
# [[a|b]] to b
# }} to } }
# *abcd* to <i>abcd</i>
# **abcd** to <b>abcd</b>
# markdown bulleted lists (using -) to html <ul>...</ul>
# markdown numbered lists (1. ...) to html <ol>...</ol>
def main():
s = pyperclip.paste()
pyperclip.copy(replace(s))
def replace(s):
# Math
s = re.sub(r"\${2}(.*?)\${2}",r"\\[\g<1>\\]",s,flags=re.DOTALL)
s = re.sub(r"\${1}(.*?)\${1}",r"\\(\g<1>\\)",s)
# Links
s = re.sub(r"\[{2}(.*?)\|(.*?)\]{2}",r"\g<2>",s)
s = re.sub(r"\}{2}",r"} }",s)
# HTML
## Bold & italic
s = re.sub(r"\*{2}(.*?)\*{2}",r"<b>\g<1></b>",s,flags=re.DOTALL)
s = re.sub(r"\*{1}(.*?)\*{1}",r"<i>\g<1></i>",s,flags=re.DOTALL)
## Lists
### Bullet
s = re.sub(r"\n\-\s(.*)?",r"\n<li>\g<1></li>",s,flags=re.MULTILINE)
s = re.sub(r"(?<!</li>\n)<li>",r"<ul>\n<li>",s,flags=re.DOTALL)
s = re.sub(r"</li>\n(?!<li>)",r"</li>\n</ul>\n",s,flags=re.DOTALL)
### Numbered
s = re.sub(r"\n[\d]{1}\.\s(.*)?",r"\n<oli>\g<1></oli>",s,flags=re.MULTILINE)
s = re.sub(r"(?<!</oli>\n)<oli>",r"<ol>\n<oli>",s,flags=re.DOTALL)
s = re.sub(r"</oli>\n(?!<oli>)",r"</oli>\n</ol>\n",s,flags=re.DOTALL)
s = re.sub(r"<oli>",r"<li>",s,flags=re.DOTALL)
s = re.sub(r"</oli>",r"</li>",s,flags=re.DOTALL)
return s
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment