diff --git a/IPython/nbconvert/filters/latex.py b/IPython/nbconvert/filters/latex.py index 8936a72..a43c7f3 100755 --- a/IPython/nbconvert/filters/latex.py +++ b/IPython/nbconvert/filters/latex.py @@ -19,40 +19,39 @@ import re # Globals and constants #----------------------------------------------------------------------------- -#Latex substitutions for escaping latex. -LATEX_SUBS = ( - (re.compile('\033\[[0-9;]+m'),''), # handle console escapes - (re.compile(r'\\'), r'{\\textbackslash}'), - (re.compile(r'([{}_#%&$])'), r'\\\1'), - (re.compile(r'~'), r'\~{}'), - (re.compile(r'\^'), r'\^{}'), - (re.compile(r'"'), r"''"), - (re.compile(r'\.\.\.+'), r'\\ldots'), -) +# Latex substitutions for escaping latex. +# see: http://stackoverflow.com/questions/16259923/how-can-i-escape-latex-special-characters-inside-django-templates +LATEX_SUBS = { + '&': r'\&', + '%': r'\%', + '$': r'\$', + '#': r'\#', + '_': r'\letterunderscore{}', + '{': r'\letteropenbrace{}', + '}': r'\letterclosebrace{}', + '~': r'\lettertilde{}', + '^': r'\letterhat{}', + '\\': r'\letterbackslash{}'} + #----------------------------------------------------------------------------- # Functions #----------------------------------------------------------------------------- -__all__ = [ - 'escape_latex', - 'strip_math_space' -] - +__all__ = ['escape_latex', + 'strip_math_space'] def escape_latex(text): """ Escape characters that may conflict with latex. - + Parameters ---------- text : str Text containing characters that may conflict with Latex """ - return_text = text - for pattern, replacement in LATEX_SUBS: - return_text = pattern.sub(replacement, return_text) - return return_text + + return ''.join([LATEX_SUBS.get(c, c) for c in text]) def strip_math_space(text): diff --git a/IPython/nbconvert/filters/tests/test_latex.py b/IPython/nbconvert/filters/tests/test_latex.py index 14909c6..b77d1bd 100644 --- a/IPython/nbconvert/filters/tests/test_latex.py +++ b/IPython/nbconvert/filters/tests/test_latex.py @@ -28,9 +28,9 @@ class TestLatex(TestsBase): def test_escape_latex(self): """escape_latex test""" tests = [ - (r'How are \you doing today?', r'How are \textbackslashyou doing today?'), - (r'\escapechar=`\A\catcode`\|=0 |string|foo', r'\textbackslashescapechar=`\textbackslashA\textbackslashcatcode`\textbackslash|=0 |string|foo'), - (r'# $ % & ~ _ ^ \ { }',r'\# \$ \% \& \~{} \_ \^{} \textbackslash \{ \}'), + (r'How are \you doing today?', r'How are \letterbackslash{}you doing today?'), + (r'\escapechar=`\A\catcode`\|=0 |string|foo', r'\letterbackslash{}escapechar=`\letterbackslash{}A\letterbackslash{}catcode`\letterbackslash{}|=0 |string|foo'), + (r'# $ % & ~ _ ^ \ { }', r'\# \$ \% \& \lettertilde{} \letterunderscore{} \letterhat{} \letterbackslash{} \letteropenbrace{} \letterclosebrace{}'), ('','')] for test in tests: