Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
tex-convert-delimiters, rewrite by Erez
# 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
You can’t perform that action at this time.