Highlight source code in code blocks.
| 251 | |
| 252 | |
| 253 | class HiliteTreeprocessor(Treeprocessor): |
| 254 | """ Highlight source code in code blocks. """ |
| 255 | |
| 256 | config: dict[str, Any] |
| 257 | |
| 258 | def code_unescape(self, text: str) -> str: |
| 259 | """Unescape code.""" |
| 260 | text = text.replace("<", "<") |
| 261 | text = text.replace(">", ">") |
| 262 | # Escaped '&' should be replaced at the end to avoid |
| 263 | # conflicting with < and >. |
| 264 | text = text.replace("&", "&") |
| 265 | return text |
| 266 | |
| 267 | def run(self, root: etree.Element) -> None: |
| 268 | """ Find code blocks and store in `htmlStash`. """ |
| 269 | blocks = root.iter('pre') |
| 270 | for block in blocks: |
| 271 | if len(block) == 1 and block[0].tag == 'code': |
| 272 | local_config = self.config.copy() |
| 273 | text = block[0].text |
| 274 | if text is None: |
| 275 | continue |
| 276 | code = CodeHilite( |
| 277 | self.code_unescape(text), |
| 278 | tab_length=self.md.tab_length, |
| 279 | style=local_config.pop('pygments_style', 'default'), |
| 280 | **local_config |
| 281 | ) |
| 282 | placeholder = self.md.htmlStash.store(code.hilite()) |
| 283 | # Clear code block in `etree` instance |
| 284 | block.clear() |
| 285 | # Change to `p` element which will later |
| 286 | # be removed when inserting raw html |
| 287 | block.tag = 'p' |
| 288 | block.text = placeholder |
| 289 | |
| 290 | |
| 291 | class CodeHiliteExtension(Extension): |