From 9b253f93d82e1eda0b0b558a64e4a10e58b21f85 Mon Sep 17 00:00:00 2001 From: Sina Atalay Date: Fri, 27 Oct 2023 22:06:07 +0200 Subject: [PATCH] escape LaTeX characters #2 --- rendercv/data_model.py | 13 +++++++++---- tests/test_data_model.py | 6 +++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/rendercv/data_model.py b/rendercv/data_model.py index b4e9925..7270c50 100644 --- a/rendercv/data_model.py +++ b/rendercv/data_model.py @@ -138,14 +138,19 @@ def escape_latex_characters(sentence: str) -> str: "~": r"\textasciitilde{}", "_": r"\_", "^": r"\textasciicircum{}", - "{": r"\{", - "}": r"\}", - "\\": r"\textbackslash{}", } + # Handle backslash and curly braces separately because the other characters are + # escaped with backslash and curly braces: + sentence = sentence.replace("{", ">>{") + sentence = sentence.replace("}", ">>}") + sentence = sentence.replace("\\", "\\textbackslash{}") + sentence = sentence.replace(">>{", "\\{") + sentence = sentence.replace(">>}", "\\}") # Loop through the letters of the sentence and if you find an escape character, # replace it with its LaTeX equivalent: - for character in sentence: + copy_of_the_sentence = sentence + for character in copy_of_the_sentence: if character in escape_characters: sentence = sentence.replace(character, escape_characters[character]) diff --git a/tests/test_data_model.py b/tests/test_data_model.py index 53a74a0..c26b36b 100644 --- a/tests/test_data_model.py +++ b/tests/test_data_model.py @@ -27,10 +27,10 @@ class TestDataModel(unittest.TestCase): result = data_model.escape_latex_characters(str_without_latex_characters) self.assertEqual(result, expected) - str_with_latex_characers = r"asdf#asdf$asdf%asdf& ~ fd_ \ ^aa aa{ bb} " + str_with_latex_characers = r"asdf#asdf$asdf%asdf& ~ fd_ \ ^aa aa{ bb}" expected = ( - r"asdf\#asdf\$asdf\%asdf\& \textasciitilde{}\ fd\_ \textbackslash{}" - r" \textasciicircum{}aa aa\{ bb\} " + r"asdf\#asdf\$asdf\%asdf\& \textasciitilde{} fd\_ \textbackslash{}" + r" \textasciicircum{}aa aa\{ bb\}" ) with self.subTest(msg="string with LaTeX characters"): result = data_model.escape_latex_characters(str_with_latex_characers)