Created
May 7, 2019 21:04
-
-
Save erezsh/1f834f7d203cb1ac89b5b3aa877fa634 to your computer and use it in GitHub Desktop.
tex-convert-delimiters, rewrite by Erez
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
# Based on https://github.com/j2kun/tex-convert-delimiters/blob/master/convert-delimiters.py | |
# A response to https://jeremykun.com/2019/04/20/a-working-mathematicians-guide-to-parsing/ | |
import sys | |
from lark import Lark, Transformer | |
lark = Lark(r''' | |
tex: (mathmode_offset | mathmode_inline | TEXT)+ | |
mathmode_offset: OFFSETDOLLAR TEXT+ OFFSETDOLLAR | OFFSETOPEN TEXT+ OFFSETCLOSE | |
mathmode_inline: INLINEOPEN TEXT+ INLINECLOSE | INLINE TEXT+ INLINE | |
INLINE: "$" | |
INLINEOPEN: "\\(" | |
INLINECLOSE: "\\)" | |
OFFSETDOLLAR: "$$" | |
OFFSETOPEN: "\\[" | |
OFFSETCLOSE: "\\]" | |
TEXT: /[^\)\]$]+/s | |
''', start='tex', parser='lalr') | |
class T(Transformer): | |
def mathmode_offset(self, children): | |
return '\\[' + ''.join(children[1:-1]) + '\\]' | |
def mathmode_inline(self, children): | |
return '\\(' + ''.join(children[1:-1]) + '\\)' | |
def tex(self, children): | |
return ''.join(children) | |
input_text = sys.stdin.read() | |
parsed_doc = lark.parse(input_text) | |
print( T().transform(parsed_doc) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment