Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/markdown_it/rules_block/state_block.py: 87%

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

166 statements  

1from __future__ import annotations 

2 

3from typing import TYPE_CHECKING, Literal 

4 

5from ..common.utils import isStrSpace 

6from ..ruler import StateBase 

7from ..token import Token 

8from ..utils import EnvType 

9 

10if TYPE_CHECKING: 

11 from markdown_it.main import MarkdownIt 

12 

13 

14class StateBlock(StateBase): 

15 def __init__( 

16 self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token] 

17 ) -> None: 

18 self.src = src 

19 

20 # link to parser instance 

21 self.md = md 

22 

23 self.env = env 

24 

25 # 

26 # Internal state variables 

27 # 

28 

29 self.tokens = tokens 

30 

31 self.bMarks: list[int] = [] # line begin offsets for fast jumps 

32 self.eMarks: list[int] = [] # line end offsets for fast jumps 

33 # offsets of the first non-space characters (tabs not expanded) 

34 self.tShift: list[int] = [] 

35 self.sCount: list[int] = [] # indents for each line (tabs expanded) 

36 

37 # An amount of virtual spaces (tabs expanded) between beginning 

38 # of each line (bMarks) and real beginning of that line. 

39 # 

40 # It exists only as a hack because blockquotes override bMarks 

41 # losing information in the process. 

42 # 

43 # It's used only when expanding tabs, you can think about it as 

44 # an initial tab length, e.g. bsCount=21 applied to string `\t123` 

45 # means first tab should be expanded to 4-21%4 === 3 spaces. 

46 # 

47 self.bsCount: list[int] = [] 

48 

49 # block parser variables 

50 self.blkIndent = 0 # required block content indent (for example, if we are 

51 # inside a list, it would be positioned after list marker) 

52 self.line = 0 # line index in src 

53 self.lineMax = 0 # lines count 

54 self.tight = False # loose/tight mode for lists 

55 self.ddIndent = -1 # indent of the current dd block (-1 if there isn't any) 

56 self.listIndent = -1 # indent of the current list block (-1 if there isn't any) 

57 

58 # can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' 

59 # used in lists to determine if they interrupt a paragraph 

60 self.parentType = "root" 

61 

62 self.level = 0 

63 

64 # renderer 

65 self.result = "" 

66 

67 # Create caches 

68 # Generate markers. 

69 # NOTE: this loop runs once per line, not once per character: 

70 # `str.find` locates each line break at C speed and only leading 

71 # whitespace is scanned (usually zero iterations), instead of 

72 # dispatching every character through `isStrSpace`. The recorded 

73 # markers are identical to the previous per-character scan. 

74 start = 0 

75 length = len(self.src) 

76 find = self.src.find 

77 

78 while start < length: 

79 end = find("\n", start) 

80 if end < 0: 

81 end = length 

82 indent = offset = 0 

83 pos = start 

84 while pos < end: 

85 character = self.src[pos] 

86 if not isStrSpace(character): 

87 break 

88 indent += 1 

89 if character == "\t": 

90 offset += 4 - offset % 4 

91 else: 

92 offset += 1 

93 pos += 1 

94 if pos == end == length: 

95 # A final line of only spaces/tabs with no "\n" gets no marker, 

96 # matching upstream markdown-it's per-character scan. 

97 break 

98 self.bMarks.append(start) 

99 self.eMarks.append(end) 

100 self.tShift.append(indent) 

101 self.sCount.append(offset) 

102 self.bsCount.append(0) 

103 start = end + 1 if end < length else length 

104 

105 # Push fake entry to simplify cache bounds checks 

106 self.bMarks.append(length) 

107 self.eMarks.append(length) 

108 self.tShift.append(0) 

109 self.sCount.append(0) 

110 self.bsCount.append(0) 

111 

112 self.lineMax = len(self.bMarks) - 1 # don't count last fake line 

113 

114 # pre-check if code blocks are enabled, to speed up is_code_block method 

115 self._code_enabled = "code" in self.md["block"].ruler.get_active_rules() 

116 

117 def __repr__(self) -> str: 

118 return ( 

119 f"{self.__class__.__name__}" 

120 f"(line={self.line},level={self.level},tokens={len(self.tokens)})" 

121 ) 

122 

123 def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token: 

124 """Push new token to "stream".""" 

125 token = Token(ttype, tag, nesting) 

126 token.block = True 

127 if nesting < 0: 

128 self.level -= 1 # closing tag 

129 token.level = self.level 

130 if nesting > 0: 

131 self.level += 1 # opening tag 

132 self.tokens.append(token) 

133 return token 

134 

135 def isEmpty(self, line: int) -> bool: 

136 """.""" 

137 return (self.bMarks[line] + self.tShift[line]) >= self.eMarks[line] 

138 

139 def skipEmptyLines(self, from_pos: int) -> int: 

140 """.""" 

141 while from_pos < self.lineMax: 

142 try: 

143 if (self.bMarks[from_pos] + self.tShift[from_pos]) < self.eMarks[ 

144 from_pos 

145 ]: 

146 break 

147 except IndexError: 

148 pass 

149 from_pos += 1 

150 return from_pos 

151 

152 def skipSpaces(self, pos: int) -> int: 

153 """Skip spaces from given position.""" 

154 while True: 

155 try: 

156 current = self.src[pos] 

157 except IndexError: 

158 break 

159 if not isStrSpace(current): 

160 break 

161 pos += 1 

162 return pos 

163 

164 def skipSpacesBack(self, pos: int, minimum: int) -> int: 

165 """Skip spaces from given position in reverse.""" 

166 if pos <= minimum: 

167 return pos 

168 while pos > minimum: 

169 pos -= 1 

170 if not isStrSpace(self.src[pos]): 

171 return pos + 1 

172 return pos 

173 

174 def skipChars(self, pos: int, code: int) -> int: 

175 """Skip character code from given position.""" 

176 while True: 

177 try: 

178 current = self.srcCharCode[pos] 

179 except IndexError: 

180 break 

181 if current != code: 

182 break 

183 pos += 1 

184 return pos 

185 

186 def skipCharsStr(self, pos: int, ch: str) -> int: 

187 """Skip character string from given position.""" 

188 while True: 

189 try: 

190 current = self.src[pos] 

191 except IndexError: 

192 break 

193 if current != ch: 

194 break 

195 pos += 1 

196 return pos 

197 

198 def skipCharsBack(self, pos: int, code: int, minimum: int) -> int: 

199 """Skip character code reverse from given position - 1.""" 

200 if pos <= minimum: 

201 return pos 

202 while pos > minimum: 

203 pos -= 1 

204 if code != self.srcCharCode[pos]: 

205 return pos + 1 

206 return pos 

207 

208 def skipCharsStrBack(self, pos: int, ch: str, minimum: int) -> int: 

209 """Skip character string reverse from given position - 1.""" 

210 if pos <= minimum: 

211 return pos 

212 while pos > minimum: 

213 pos -= 1 

214 if ch != self.src[pos]: 

215 return pos + 1 

216 return pos 

217 

218 def getLines(self, begin: int, end: int, indent: int, keepLastLF: bool) -> str: 

219 """Cut lines range from source.""" 

220 line = begin 

221 if begin >= end: 

222 return "" 

223 

224 queue = [""] * (end - begin) 

225 

226 i = 1 

227 while line < end: 

228 lineIndent = 0 

229 lineStart = first = self.bMarks[line] 

230 last = ( 

231 self.eMarks[line] + 1 

232 if line + 1 < end or keepLastLF 

233 else self.eMarks[line] 

234 ) 

235 

236 while (first < last) and (lineIndent < indent): 

237 ch = self.src[first] 

238 if isStrSpace(ch): 

239 if ch == "\t": 

240 lineIndent += 4 - (lineIndent + self.bsCount[line]) % 4 

241 else: 

242 lineIndent += 1 

243 elif first - lineStart < self.tShift[line]: 

244 lineIndent += 1 

245 else: 

246 break 

247 first += 1 

248 

249 if lineIndent > indent: 

250 # partially expanding tabs in code blocks, e.g '\t\tfoobar' 

251 # with indent=2 becomes ' \tfoobar' 

252 queue[i - 1] = (" " * (lineIndent - indent)) + self.src[first:last] 

253 else: 

254 queue[i - 1] = self.src[first:last] 

255 

256 line += 1 

257 i += 1 

258 

259 return "".join(queue) 

260 

261 def is_code_block(self, line: int) -> bool: 

262 """Check if line is a code block, 

263 i.e. the code block rule is enabled and text is indented by more than 3 spaces. 

264 """ 

265 return self._code_enabled and (self.sCount[line] - self.blkIndent) >= 4