Skip to content

Instantly share code, notes, and snippets.

@erezsh
Created May 7, 2019 21:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erezsh/1f834f7d203cb1ac89b5b3aa877fa634 to your computer and use it in GitHub Desktop.
Save erezsh/1f834f7d203cb1ac89b5b3aa877fa634 to your computer and use it in GitHub Desktop.
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