Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/mistune/util.py: 100%

38 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

1import re 

2from urllib.parse import quote 

3from html import _replace_charref 

4 

5 

6_expand_tab_re = re.compile(r'^( {0,3})\t', flags=re.M) 

7 

8 

9def expand_leading_tab(text: str, width=4): 

10 def repl(m): 

11 s = m.group(1) 

12 return s + ' ' * (width - len(s)) 

13 return _expand_tab_re.sub(repl, text) 

14 

15 

16def expand_tab(text: str, space: str=' '): 

17 repl = r'\1' + space 

18 return _expand_tab_re.sub(repl, text) 

19 

20 

21def escape(s: str, quote: bool=True): 

22 """Escape characters of ``&<>``. If quote=True, ``"`` will be 

23 converted to ``&quote;``.""" 

24 s = s.replace("&", "&amp;") 

25 s = s.replace("<", "&lt;") 

26 s = s.replace(">", "&gt;") 

27 if quote: 

28 s = s.replace('"', "&quot;") 

29 return s 

30 

31 

32def escape_url(link: str): 

33 """Escape URL for safety.""" 

34 safe = ( 

35 ':/?#@' # gen-delims - '[]' (rfc3986) 

36 '!$&()*+,;=' # sub-delims - "'" (rfc3986) 

37 '%' # leave already-encoded octets alone 

38 ) 

39 return escape(quote(unescape(link), safe=safe)) 

40 

41 

42def safe_entity(s: str): 

43 """Escape characters for safety.""" 

44 return escape(unescape(s)) 

45 

46 

47def unikey(s: str): 

48 """Generate a unique key for links and footnotes.""" 

49 key = ' '.join(s.split()).strip() 

50 return key.lower().upper() 

51 

52 

53_charref_re = re.compile( 

54 r'&(#[0-9]{1,7};' 

55 r'|#[xX][0-9a-fA-F]+;' 

56 r'|[^\t\n\f <&#;]{1,32};)' 

57) 

58 

59 

60def unescape(s: str): 

61 """ 

62 Copy from `html.unescape`, but `_charref` is different. CommonMark 

63 does not accept entity references without a trailing semicolon 

64 """ 

65 if '&' not in s: 

66 return s 

67 return _charref_re.sub(_replace_charref, s) 

68 

69 

70_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)') 

71 

72 

73def striptags(s: str): 

74 return _striptags_re.sub('', s) 

75 

76 

77_strip_end_re = re.compile(r'\n\s+$') 

78 

79 

80def strip_end(src: str): 

81 return _strip_end_re.sub('\n', src)