Manages the console render state.
| 463 | |
| 464 | |
| 465 | class MarkdownContext: |
| 466 | """Manages the console render state.""" |
| 467 | |
| 468 | def __init__( |
| 469 | self, |
| 470 | console: Console, |
| 471 | options: ConsoleOptions, |
| 472 | style: Style, |
| 473 | inline_code_lexer: str | None = None, |
| 474 | inline_code_theme: str = "monokai", |
| 475 | ) -> None: |
| 476 | self.console = console |
| 477 | self.options = options |
| 478 | self.style_stack: StyleStack = StyleStack(style) |
| 479 | self.stack: Stack[MarkdownElement] = Stack() |
| 480 | |
| 481 | self._syntax: Syntax | None = None |
| 482 | if inline_code_lexer is not None: |
| 483 | self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme) |
| 484 | |
| 485 | @property |
| 486 | def current_style(self) -> Style: |
| 487 | """Current style which is the product of all styles on the stack.""" |
| 488 | return self.style_stack.current |
| 489 | |
| 490 | def on_text(self, text: str, node_type: str) -> None: |
| 491 | """Called when the parser visits text.""" |
| 492 | if node_type in {"fence", "code_inline"} and self._syntax is not None: |
| 493 | highlight_text = self._syntax.highlight(text) |
| 494 | highlight_text.rstrip() |
| 495 | self.stack.top.on_text( |
| 496 | self, Text.assemble(highlight_text, style=self.style_stack.current) |
| 497 | ) |
| 498 | else: |
| 499 | self.stack.top.on_text(self, text) |
| 500 | |
| 501 | def enter_style(self, style_name: str | Style) -> Style: |
| 502 | """Enter a style context.""" |
| 503 | style = self.console.get_style(style_name, default="none") |
| 504 | self.style_stack.push(style) |
| 505 | return self.current_style |
| 506 | |
| 507 | def leave_style(self) -> Style: |
| 508 | """Leave a style context.""" |
| 509 | style = self.style_stack.pop() |
| 510 | return style |
| 511 | |
| 512 | |
| 513 | class Markdown(JupyterMixin): |