Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/markdown_it/rules_inline/backticks.py: 96%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

46 statements  

1# Parse backticks 

2from .state_inline import StateInline 

3 

4 

5def _build_last_runs(src: str) -> dict[int, int]: 

6 """Map each backtick run length to its last position in the source.""" 

7 last_runs: dict[int, int] = {} 

8 pos = 0 

9 

10 while (start := src.find("`", pos)) != -1: 

11 pos = start + 1 

12 while pos < len(src) and src[pos] == "`": 

13 pos += 1 

14 last_runs[pos - start] = start 

15 

16 return last_runs 

17 

18 

19def backtick(state: StateInline, silent: bool) -> bool: 

20 """Parse an inline code span or consume an unmatched backtick run.""" 

21 start = state.pos 

22 

23 if state.src[start] != "`": 

24 return False 

25 

26 maximum = state.posMax 

27 pos = start + 1 

28 

29 # Scan marker length. 

30 while pos < maximum and state.src[pos] == "`": 

31 pos += 1 

32 

33 marker = state.src[start:pos] 

34 opener_length = len(marker) 

35 

36 if not state.backticksScanned: 

37 # Lookaheads may visit runs out of order, so build this cache from the 

38 # whole source independently of the parser's current position. 

39 state.backticks = _build_last_runs(state.src) 

40 state.backticksScanned = True 

41 

42 if state.backticks.get(opener_length, -1) >= pos: 

43 match_end = pos 

44 

45 while ( 

46 match_start := state.src.find("`", match_end) 

47 ) != -1 and match_start < maximum: 

48 match_end = match_start + 1 

49 # A run crossing posMax cannot be a closer in this parse range. 

50 while match_end < len(state.src) and state.src[match_end] == "`": 

51 match_end += 1 

52 if match_end > maximum: 

53 break 

54 

55 if match_end - match_start == opener_length: 

56 if not silent: 

57 token = state.push("code_inline", "code", 0) 

58 token.markup = marker 

59 content = state.src[pos:match_start].replace("\n", " ") 

60 # Strip one space from each side, unless the content is all spaces 

61 if ( 

62 content.startswith(" ") 

63 and content.endswith(" ") 

64 and any(c != " " for c in content) 

65 ): 

66 content = content[1:-1] 

67 token.content = content 

68 state.pos = match_end 

69 return True 

70 

71 if not silent: 

72 state.append_pending(marker) 

73 state.pos = pos 

74 return True