"""Latex parsing functionality

This module provides functions to parse latex text
"""

import re

######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
ESCAPE_CHARS_OR = '[{}]'.format('|'.join(ESCAPE_CHARS))
REGEX_ESCAPE_CHARS = [
        (re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
        for i in ESCAPE_CHARS
        ]
REGEX_BACKSLASH = re.compile(r'\\(?!{})'.format(ESCAPE_CHARS_OR))

######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
    '''Escape a latex string'''
    for regex, replace_text in REGEX_ESCAPE_CHARS:
        string_text = re.sub(regex, replace_text, string_text)
    string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
    return string_text

@@ -269,267 +269,1044 @@
 ###%0A
-ESCAPE_CHARS = %5Br'%5C&', '%25', r'%5C$', '#', '_', r'%5C%7B', r'%5C%7D', '~', r'%5C%5E', %5D%0AESCAPE_CHARS_OR = '%5B%7B%7D%5D'.format('%7C'.join(ESCAPE_CHARS))%0AREGEX_ESCAPE_CHARS = %5B%0A        (re.compile(r%22(?=%5B%5E%5C%5C%5D)%22 + i), r%22%5C%5C%22 + i.replace('%5C%5C', ''))%0A        for i in ESCAPE_CHARS%0A        %5D
+%0A# Organize all latex escape characters in one list%0A# (EXCEPT FOR ( %22%5C%22 ), which is handled separately)%0A# escaping those which are special characters in%0A# PERL regular expressions%0AESCAPE_CHARS = %5Br'%5C&', '%25', r'%5C$', '#', '_', r'%5C%7B', r'%5C%7D', '~', r'%5C%5E', %5D%0A%0A# For each latex escape character, create a regular expression%0A# that matches all of the following criteria%0A# 1) two characters%0A# 2) the first character is NOT a backslash ( %22%5C%22 )%0A# 3) the second character is one of the latex escape characters%0AREGEX_ESCAPE_CHARS = %5B%0A        (re.compile(r%22(?=%5B%5E%5C%5C%5D)%22 + i), r%22%5C%5C%22 + i.replace('%5C%5C', ''))%0A        for i in ESCAPE_CHARS%0A        %5D%0A%0A# Place escape characters in %5B%5D for %22match any character%22 regex%0AESCAPE_CHARS_OR = r'%5B%7B%7D%5C%5C%5D'.format(ESCAPE_CHARS)%0A%0A# For the back slash, create a regular expression%0A# that matches all of the following criteria%0A# 1) three characters%0A# 2) the first character is not a backslash%0A# 3) the second characters is a backslash%0A# 4) the third character is none of the ESCAPE_CHARS,%0A#       and is also not a backslash
 %0AREG
@@ -1333,16 +1333,22 @@
 mpile(r'
+(?!%5C%5C)
 %5C%5C(?!%7B%7D)

Update latex parser to better-handle edge cases