export class LatexProcessor { private singleLine = /\$(.*?)\$/g ; process ( markdown ) { const withoutEscapedCharaters = this . markEscapedCharacters ( markdown ) ; const processedMultiline = this . processMultiLine ( withoutEscapedCharaters ) ; const multiWithoutEscapedCharaters = this . markEscapedCharacters ( processedMultiline ) ; const processedSingleLine = this . processSingleLine ( multiWithoutEscapedCharaters ) ; const finalResult = this . unmarkEscapedCharacters ( processedSingleLine ) ; return finalResult ; } private markEscapedCharacters ( markdown ) { return markdown . replaceAll ( '\\$' , '~~d~~' ) . replaceAll ( /`\$\$/gm , '~~s~~' ) . replaceAll ( /\$\$`/gm , '~~e~~' ) . replaceAll ( /`\$/gm , '~~ss~~' ) . replaceAll ( /\$`/gm , '~~se~~' ) ; } private unmarkEscapedCharacters ( markdown ) { return markdown . replaceAll ( '~~d~~' , '\\$' ) . replaceAll ( '~~e~~' , '$$$$`' ) . replaceAll ( '~~s~~' , '`$$$$' ) . replaceAll ( '~~ss~~' , '`$' ) . replaceAll ( '~~se~~' , '$$`' ) ; } private processSingleLine ( markdown ) { return markdown . split ( '\n' ) . map ( ( line ) => { if ( line . includes ( '$' ) ) { line = line . replaceAll ( this . singleLine , '`$$$1$$`' ) ; } return line ; } ) . join ( '\n' ) ; } private processMultiLine ( markdown ) { if ( markdown . includes ( '$$' ) ) { return markdown . split ( '$$' ) . map ( ( line , index ) => { if ( this . isOdd ( index ) ) { return line ; } else { return '`' + line + '`' ; } } ) . map ( ( line ) => { return line . replaceAll ( /^\s*[\r\n]/gm , '' ) ; } ) . join ( '$$' ) . slice ( 1 , - 1 ) ; } return markdown ; } private isOdd ( number ) { return number & 1 ; } }