From 75a98a7bf40301e33dd4de63af79eaeee2e9e66a Mon Sep 17 00:00:00 2001 From: =?utf8?q?Andr=C3=A9=20Wobst?= Date: Wed, 24 Aug 2005 08:44:35 +0000 Subject: [PATCH] improve escapestring to handle all ascii characters git-svn-id: https://pyx.svn.sourceforge.net/svnroot/pyx/trunk/pyx@2343 069f4177-920e-0410-937b-c2a4a81bcd90 --- pyx/text.py | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/pyx/text.py b/pyx/text.py index 4ee43740..88dc316f 100644 --- a/pyx/text.py +++ b/pyx/text.py @@ -1322,26 +1322,31 @@ preamble = defaulttexrunner.preamble text = defaulttexrunner.text text_pt = defaulttexrunner.text_pt -def escapestring(s): - """escape special TeX/LaTeX characters - - Returns a string, where some special characters of standard - TeX/LaTeX are replaced by appropriate escaped versions. Note - that we cannot handle the three ASCII characters '{', '}', - and '\' that way, since they do not occure in the TeX default - encoding and thus are more likely to need some special handling. - All other ASCII characters should usually (but not always) - work.""" - - # ASCII strings only - s = str(s) +def escapestring(s, replace={" ": "~", + "$": "\\$", + "&": "\\&", + "#": "\\#", + "_": "\\_", + "%": "\\%", + "^": "\\string^", + "~": "\\string~", + "<": "{$<$}", + ">": "{$>$}", + "{": "{$\{$}", + "}": "{$\}$}", + "\\": "{$\setminus$}", + "|": "{$\mid$}"}): + "escape all ascii characters such that they are printable by TeX/LaTeX" i = 0 while i < len(s): - if s[i] in "$&#_%": - s = s[:i] + "\\" + s[i:] + if not 32 <= ord(s[i]) < 127: + raise ValueError("escapestring function handles ascii strings only") + c = s[i] + try: + r = replace[c] + except KeyError: i += 1 - elif s[i] in "^~": - s = s[:i] + r"\string" + s[i:] - i += 7 - i += 1 + else: + s = s[:i] + r + s[i+1:] + i += len(r) return s -- 2.11.4.GIT