55escape_html_text = markup_escape # unify api for test of project
66
77
8- def escape_html_comment (text ):
9- """Escape text injected into an HTML comment."""
10- GT = ">"
11- LT = "<"
8+ GT = ">"
9+ LT = "<"
10+
1211
12+ def escape_html_comment (text : str ) -> str :
13+ """Escape text injected into an HTML comment."""
1314 if not text :
1415 return text
1516 # - text must not start with the string ">"
@@ -21,15 +22,9 @@ def escape_html_comment(text):
2122 text = "-" + GT + text [2 :]
2223
2324 # - nor contain the strings "<!--", "-->", or "--!>"
24- index = text .find ("<!--" )
25- if index != - 1 :
26- text = text [:index ] + LT + text [index + 1 ]
27- index = text .find ("-->" )
28- if index != - 1 :
29- text = text [: index + 2 ] + GT + text [index + 3 ]
30- index = text .find ("--!>" )
31- if index != - 1 :
32- text = text [: index + 3 ] + GT + text [index + 4 ]
25+ text = text .replace ("<!--" , LT + "!--" )
26+ text = text .replace ("-->" , "--" + GT )
27+ text = text .replace ("--!>" , "--!" + GT )
3328
3429 # - nor end with the string "<!-".
3530 if text [- 3 :] == "<!-" :
@@ -38,16 +33,27 @@ def escape_html_comment(text):
3833 return text
3934
4035
41- def escape_html_style (text ):
42- LT = "<"
43- close_str = "</style>"
44- close_str_re = re .compile (close_str , re .I | re .A )
45- replace_str = LT + close_str [1 :]
46- return re .sub (close_str_re , replace_str , text )
36+ STYLE_RES = ((re .compile ("</style>" , re .I | re .A ), LT + "/style>" ),)
4737
4838
49- def escape_html_script (text ):
39+ def escape_html_style (text : str ) -> str :
40+ """Escape text injected into an HTML style element."""
41+ for matche_re , replace_text in STYLE_RES :
42+ text = re .sub (matche_re , replace_text , text )
43+ return text
44+
45+
46+ SCRIPT_RES = (
47+ (re .compile ("<!--" , re .I | re .A ), "\x3c !--" ),
48+ (re .compile ("<script" , re .I | re .A ), "\x3c script" ),
49+ (re .compile ("</script" , re .I | re .A ), "\x3c /script" ),
50+ )
51+
52+
53+ def escape_html_script (text : str ) -> str :
5054 """
55+ Escape text injected into an HTML script element.
56+
5157 https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
5258
5359 (from link) The easiest and safest way to avoid the rather strange restrictions
@@ -57,11 +63,6 @@ def escape_html_script(text):
5763 - "<script" as "\x3c script"
5864 - "</script" as "\x3c /script"`
5965 """
60- match_to_replace = (
61- (re .compile ("<!--" , re .I | re .A ), "\x3c !--" ),
62- (re .compile ("<script" , re .I | re .A ), "\x3c script" ),
63- (re .compile ("</script" , re .I | re .A ), "\x3c /script" ),
64- )
65- for match_re , replace_text in match_to_replace :
66+ for match_re , replace_text in SCRIPT_RES :
6667 text = re .sub (match_re , replace_text , text )
6768 return text
0 commit comments