Debian Codegraph @

rich_rst/__init__.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 reStructuredText parser for rich
5
6 Initial few lines gotten from: https://github.com/willmcgugan/rich/discussions/1263#discussioncomment-808898
7 There are a lot of improvements are added by me
8 """
9 from io import StringIO
10 from html.parser import HTMLParser
11 from typing import Optional, Union
12
13 # Imports from docutils package for the parsing
14 import docutils.io
15 import docutils.nodes
16 import docutils.parsers.rst
17 import docutils.utils
18
19 # Imports from the rich package for the printing
20 import rich
21 from rich import box
22 from rich.align import Align
23 from rich.console import Console, ConsoleOptions, RenderResult, NewLine
24 from rich.jupyter import JupyterMixin
25 from rich.panel import Panel
26 from rich.style import Style
27 from rich.syntax import Syntax, SyntaxTheme
28 from rich.text import Text
29 from rich.table import Table
30 from rich.traceback import install
31 from rich.rule import Rule
32
33 from pygments.lexers import guess_lexer
34 from pygments.util import ClassNotFound
35
36 try:
37 from ._version import __version__
38 except ImportError:
39 __version__ = "0.0.0"
40
41 __all__ = ("RST", "ReStructuredText", "reStructuredText", "RestructuredText")
42 __author__ = "Arian Mollik Wasi (aka. Wasi Master)"
43 __version__ = "1.3.2"
44
45 install()
46
47
48 class MLStripper(HTMLParser):
49 """Utility class to strip out html for raw html source"""
50 def __init__(self):
51 super().__init__()
52 self.reset()
53 self.strict = False
54 self.convert_charrefs = True
55 self.text = StringIO()
56
57 def handle_data(self, d):
58 self.text.write(d)
59
60 def get_data(self):
61 return self.text.getvalue()
62
63
64 def strip_tags(html):
65 s = MLStripper()
66 s.feed(html)
67 return s.get_data()
68
69
70 def _register_sphinx_roles():
71 """
72 Register common Sphinx roles to gracefully handle Sphinx-specific markup.
73
74 Sphinx roles like :func:, :class:, :meth: are very common in Python docstrings
75 but are not available in standard docutils. This function registers them to
76 render as inline code/literal text instead of showing errors.
77 """
78 import docutils.parsers.rst.roles
79 import docutils.parsers.rst.languages.en
80
81 def sphinx_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
82 """
83 Generic Sphinx role handler that renders as inline literal text.
84
85 Parameters
86 ----------
87 name : str
88 The role name
89 rawtext : str
90 The entire role text including role markup
91 text : str
92 The interpreted text content
93 lineno : int
94 The line number where the interpreted text begins
95 inliner : Inliner
96 The inliner instance that called this role function
97 options : dict
98 Directive options for customization
99 content : list
100 The directive content for customization
101
102 Returns
103 -------
104 tuple
105 A tuple of (nodes, messages)
106 """
107 display_text = text
108 if '<' in text and text.endswith('>'):
109 bracket_pos = text.rfind('<')
110 potential_display = text[:bracket_pos].strip()
111 if potential_display:
112 display_text = potential_display
113
114 node = docutils.nodes.literal(rawtext, display_text)
115 return [node], []
116
117 sphinx_roles = [
118 'func', 'function',
119 'meth', 'method',
120 'class',
121 'mod', 'module',
122 'attr', 'attribute',
123 'obj', 'object',
124 'data',
125 'const', 'constant',
126 'exc', 'exception',
127 'var', 'variable',
128 'type',
129 'py:func', 'py:meth', 'py:class', 'py:mod', 'py:attr',
130 'py:obj', 'py:data', 'py:const', 'py:exc',
131 ]
132
133 for role in sphinx_roles:
134 docutils.parsers.rst.roles.register_canonical_role(role, sphinx_role)
135 # Also register in language module to avoid INFO messages
136 if hasattr(docutils.parsers.rst.languages.en, 'roles'):
137 docutils.parsers.rst.languages.en.roles[role] = role
138
139
140 # pylama:ignore=D,C0116
141 class RSTVisitor(docutils.nodes.SparseNodeVisitor):
142 """A visitor that produces rich renderables"""
143
144 def __init__(
145 self,
146 document: docutils.nodes.document,
147 console: Console,
148 code_theme: Union[str, SyntaxTheme] = "monokai",
149 guess_lexer: Optional[bool] = True,
150 default_lexer: Optional[str] = "python",
151 ) -> None:
152 super().__init__(document)
153 self.console = console
154 self.code_theme = code_theme
155 self.renderables = []
156 self.supercript = str.maketrans(
157 "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=+-*/×÷",
158 "¹²³⁴⁵⁶⁷⁸⁹⁰ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖᑫʳˢᵗᵘᵛʷˣʸᶻᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾQᴿˢᵀᵁⱽᵂˣʸᶻ⁼⁺⁻*/×÷",
159 )
160 self.subscript = str.maketrans(
161 "1234567890abcdefghijklmnopqrstuvwxyz=+-*/×÷", "₁₂₃₄₅₆₇₈₉₀abcdₑfgₕᵢⱼₖₗₘₙₒₚqᵣₛₜᵤᵥwₓyz₌₊₋*/×÷"
162 )
163 self.errors = []
164 self.footer = []
165 self.guess_lexer = guess_lexer
166 self.default_lexer = default_lexer
167 self.refname_to_renderable = {}
168
169 def _find_lexer(self, node):
170 lexer = (
171 node["classes"][1] if len(node.get("classes")) >= 2 else (node["format"] if node.get("format") else None)
172 )
173 if lexer is None and self.guess_lexer:
174 try:
175 lexer = guess_lexer(node.astext())
176 except ClassNotFound:
177 lexer = self.default_lexer
178 else:
179 lexer = lexer.aliases[0] if lexer.aliases else self.default_lexer
180 if lexer == "text":
181 return self.default_lexer
182 return lexer
183 elif lexer is None and not self.guess_lexer:
184 lexer = self.default_lexer
185 return lexer
186 return lexer
187
188 def visit_reference(self, node):
189 refuri = node.attributes.get("refuri")
190 style = self.console.get_style("restructuredtext.reference", default="blue underline on default")
191 if refuri:
192 style = style.update_link(refuri)
193 renderable = Text(node.astext().replace("\n", " "), style=style, end="")
194 if self.renderables and isinstance(self.renderables[-1], Text):
195 renderable.end = " "
196 start = len(self.renderables[-1])
197 self.renderables[-1].append_text(renderable)
198 else:
199 start = 0
200 self.renderables.append(renderable)
201 end = len(self.renderables[-1])
202
203 if not refuri:
204 # We'll get the URL reference later in visit_target.
205 refname = node.attributes.get("refname")
206 if refname:
207 self.refname_to_renderable[refname] = (self.renderables[-1], start, end)
208 raise docutils.nodes.SkipChildren()
209
210 def visit_target(self, node):
211 uri = node.get("refuri")
212 if uri:
213 for name in node["names"]:
214 try:
215 renderable, start, end = self.refname_to_renderable[name]
216 except KeyError:
217 continue
218 style = renderable.get_style_at_offset(self.console, start)
219 style = style.update_link(uri)
220 renderable.stylize(style, start, end)
221 raise docutils.nodes.SkipChildren()
222
223 def visit_paragraph(self, node):
224 if hasattr(node, "parent") and isinstance(node.parent, docutils.nodes.system_message):
225 self.visit_system_message(node.parent)
226
227 def depart_paragraph(self, node): # pylint: disable=unused-argument
228 if self.renderables and isinstance(self.renderables[-1], Text):
229 if len(self.renderables[-1].end) == 0:
230 self.renderables[-1].append("\n\n")
231
232 def visit_title(self, node):
233 style = self.console.get_style("restructuredtext.title", default="bold")
234 self.renderables.append(Panel(Align(node.astext(), "center"), box=box.DOUBLE, style=style))
235 raise docutils.nodes.SkipChildren()
236
237 def visit_Text(self, node):
238 style = self.console.get_style("restructuredtext.text", default="default on default not underline")
239 if self.renderables and isinstance(self.renderables[-1], Text):
240 self.renderables[-1].append_text(Text(node.astext().replace("\n", " "), style=style, end=" "))
241 return
242 self.renderables.append(Text(node.astext().replace("\n", " "), end="", style=style))
243
244 def visit_comment(self, node):
245 raise docutils.nodes.SkipChildren()
246
247 def visit_admonition(self, node):
248 style = self.console.get_style("restructuredtext.admonition", default="bold white")
249 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Admonition: ", style=style, border_style=style))
250 raise docutils.nodes.SkipChildren()
251
252 def visit_attention(self, node):
253 style = self.console.get_style("restructuredtext.attention", default="bold black on yellow")
254 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Attention: ", style=style, border_style=style))
255 raise docutils.nodes.SkipChildren()
256
257 def visit_caution(self, node):
258 style = self.console.get_style("restructuredtext.caution", default="red")
259 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Caution: ", style=style, border_style=style))
260 raise docutils.nodes.SkipChildren()
261
262 def visit_danger(self, node):
263 style = self.console.get_style("restructuredtext.danger", default="bold white on red")
264 self.renderables.append(Panel(node.astext().replace("\n", " "), title="DANGER: ", style=style, border_style=style))
265 raise docutils.nodes.SkipChildren()
266
267 def visit_error(self, node):
268 style = self.console.get_style("restructuredtext.error", default="bold red")
269 self.renderables.append(Panel(node.astext().replace("\n", " "), title="ERROR: ", style=style, border_style=style))
270 raise docutils.nodes.SkipChildren()
271
272 def visit_hint(self, node):
273 style = self.console.get_style("restructuredtext.hint", default="yellow")
274 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Hint: ", style=style, border_style=style))
275 raise docutils.nodes.SkipChildren()
276
277 def visit_important(self, node):
278 style = self.console.get_style("restructuredtext.important", default="bold blue")
279 self.renderables.append(Panel(node.astext().replace("\n", " "), title="IMPORTANT: ", style=style, border_style=style))
280 raise docutils.nodes.SkipChildren()
281
282 def visit_note(self, node):
283 style = self.console.get_style("restructuredtext.note", default="bold white")
284 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Note: ", style=style, border_style=style))
285 raise docutils.nodes.SkipChildren()
286
287 def visit_tip(self, node):
288 style = self.console.get_style("restructuredtext.tip", default="bold green")
289 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Tip: ", style=style, border_style=style))
290 raise docutils.nodes.SkipChildren()
291
292 def visit_warning(self, node):
293 style = self.console.get_style("restructuredtext.warning", default="bold yellow")
294 self.renderables.append(Panel(node.astext().replace("\n", " "), title="Warning: ", style=style, border_style=style))
295 raise docutils.nodes.SkipChildren()
296
297 def visit_subscript(self, node):
298 style = self.console.get_style("restructuredtext.subscript", default="none")
299 if self.renderables and isinstance(self.renderables[-1], Text):
300 self.renderables[-1].append_text(Text(node.astext().translate(self.subscript), style=style, end=" "))
301 raise docutils.nodes.SkipChildren()
302 self.renderables.append(Text(node.astext().translate(self.subscript), end="", style=style))
303 raise docutils.nodes.SkipChildren()
304
305 def visit_superscript(self, node):
306 style = self.console.get_style("restructuredtext.superscript", default="none")
307 if self.renderables and isinstance(self.renderables[-1], Text):
308 self.renderables[-1].append_text(Text(node.astext().translate(self.supercript), style=style, end=" "))
309 raise docutils.nodes.SkipChildren()
310 self.renderables.append(Text(node.astext().translate(self.supercript), end="", style=style))
311 raise docutils.nodes.SkipChildren()
312
313 def visit_emphasis(self, node):
314 style = self.console.get_style("restructuredtext.emphasis", default="italic")
315 if self.renderables and isinstance(self.renderables[-1], Text):
316 self.renderables[-1].append_text(Text(node.astext().replace("\n", " "), style=style, end=" "))
317 raise docutils.nodes.SkipChildren()
318 self.renderables.append(Text(node.astext().replace("\n", " "), style=style, end=""))
319 raise docutils.nodes.SkipChildren()
320
321 def visit_strong(self, node):
322 style = self.console.get_style("restructuredtext.strong", default="bold")
323 if self.renderables and isinstance(self.renderables[-1], Text):
324 self.renderables[-1].append_text(Text(node.astext().replace("\n", " "), style=style, end=" "))
325 raise docutils.nodes.SkipChildren()
326 self.renderables.append(Text(node.astext().replace("\n", " "), style=style, end=""))
327 raise docutils.nodes.SkipChildren()
328
329 def visit_image(self, node):
330 alt, target = None, None
331 if ":target:" in node.rawsource:
332 target = node.rawsource.split(":target:")[-1].strip()
333 if ":alt:" in node.rawsource:
334 alt = node.rawsource.split(":alt:")[-1].strip()
335 self.renderables.append(
336 Text("🌆 ")
337 + Text(
338 node.get("alt", alt or "Image"),
339 style=Style(
340 link=node.get("target", target or "Image") or node.get("uri"),
341 color="#6088ff",
342 ),
343 )
344 )
345 raise docutils.nodes.SkipChildren()
346
347 def visit_bullet_list(self, node):
348 # Currently as it stands, this isn't gonna work with more than 3 nested levels
349 # TODO: I need to figure out some way to handle nested lists recursively
350 marker_style = self.console.get_style("restructuredtext.bullet_list_marker", default="bold yellow")
351 text_style = self.console.get_style("restructuredtext.bullet_list_text", default="none")
352 for list_item in node.children:
353 nested_list = [i for i in list_item.children if isinstance(i, docutils.nodes.bullet_list)]
354 if nested_list:
355 for list_item in list_item.children:
356 self.renderables.append(Text(" ", end="") + Text(" ∘ ", end="", style=marker_style))
357 self.renderables.append(Text(list_item.astext().replace("\n", " "), style=text_style))
358 if isinstance(list_item, docutils.nodes.bullet_list):
359 for list_item in list_item.children:
360 self.renderables.append(Text(" ", end="") + Text(" ▪ ", end="", style=marker_style))
361 self.renderables.append(Text(list_item.astext().replace("\n", " "), style=text_style))
362 self.renderables.append(Text(" • ", end="", style=marker_style))
363 self.renderables.append(Text(list_item.astext().replace("\n", " "), style=text_style))
364 self.renderables.append(NewLine())
365 raise docutils.nodes.SkipChildren()
366
367 def visit_enumerated_list(self, node):
368 marker_style = self.console.get_style("restructuredtext.enumerated_list_marker", default="bold yellow")
369 text_style = self.console.get_style("restructuredtext.enumerated_text", default="none")
370 for i, list_item in enumerate(node.children, 1):
371 self.renderables.append(Text(f" {i}", end=" ", style=marker_style))
372 self.renderables.append(Text(list_item.astext().replace("\n", " "), style=text_style))
373
374 self.renderables.append(NewLine())
375 raise docutils.nodes.SkipChildren()
376
377 def visit_literal(self, node):
378 style = self.console.get_style("restructuredtext.inline_codeblock", default="grey78 on grey7")
379 if self.renderables and isinstance(self.renderables[-1], Text):
380 self.renderables[-1].append_text(Text(node.astext().replace("\n", " "), style=style, end=" "))
381 raise docutils.nodes.SkipChildren()
382 self.renderables.append(Text(node.astext().replace("\n", " "), style=style, end=""))
383 raise docutils.nodes.SkipChildren()
384
385 def visit_literal_block(self, node):
386 style = self.console.get_style("restructuredtext.literal_block_border", default="grey58")
387 if self.renderables and isinstance(self.renderables[-1], Text):
388 self.renderables[-1].rstrip()
389 self.renderables[-1].append_text(Text("\n"))
390 lexer = self._find_lexer(node)
391 self.renderables.append(
392 Panel(Syntax(node.astext(), lexer, theme=self.code_theme), border_style=style, box=box.SQUARE, title=lexer)
393 )
394 raise docutils.nodes.SkipChildren()
395
396 def visit_system_message(self, node):
397 self.errors.append(
398 Panel(
399 self.console.render_str(node.astext()),
400 title=f"System Message: {node.attributes.get('type', '?')}/{node.attributes.get('level', '?')} ({node.attributes.get('source', '?')}, line {node.attributes.get('line', '?')});",
401 border_style={None: "none", "INFO": "bold cyan", "WARNING": "bold yellow", "ERROR": "bold red"}[
402 node.attributes.get("type")
403 ],
404 ),
405 )
406 raise docutils.nodes.SkipChildren()
407
408 def visit_field(self, node):
409 field_name_style = self.console.get_style("restructuredtext.field_name", default="bold")
410 field_value_style = self.console.get_style("restructuredtext.field_value", default="none")
411 previous_table = None
412 if isinstance(self.renderables[-1], Table):
413 possible_table = self.renderables[-1]
414 if (possible_table.columns[0].header == "Field Name") and (possible_table.columns[1].header == "Field Value"):
415 table = possible_table
416 previous_table = True
417 else:
418 table = Table("Field Name", "Field Value", show_lines=True)
419 previous_table = False
420 else:
421 previous_table = False
422 if previous_table is False:
423 table = Table("Field Name", "Field Value", show_lines=True)
424 table.add_row(Text(node.children[0].astext(), style=field_name_style), Text(node.children[1].astext(), style=field_value_style))
425 self.renderables.append(table)
426 else:
427 table.add_row(Text(node.children[0].astext(), style=field_name_style), Text(node.children[1].astext(), style=field_value_style))
428 raise docutils.nodes.SkipChildren()
429
430 def visit_definition_list(self, node):
431 term_style = self.console.get_style("restructuredtext.term_style", default="none")
432 classifier_style = self.console.get_style("restructuredtext.classifier_style", default="cyan")
433 definitions_style = self.console.get_style("restructuredtext.definitions_style", default="none")
434 for child in node.children:
435 try:
436 term, classifier, definitions = child.children
437 except ValueError:
438 term, classifier = child.children[0], child.children[1]
439 if len(child.children) > 2:
440 for children in child.children[2:]:
441 if isinstance(children, docutils.nodes.bullet_list):
442 self.visit_bullet_list(children)
443 elif isinstance(children, docutils.nodes.literal_block):
444 self.visit_literal_block(children)
445 elif isinstance(children, docutils.nodes.literal):
446 self.visit_literal(children)
447 elif isinstance(children, docutils.nodes.block_quote):
448 self.visit_block_quote(children)
449 else:
450
451 self.renderables.append(
452 Text.from_markup(f"[{classifier_style}]{term.astext()}[/{classifier_style}]")
453 + Text("\n ", end="")
454 + Text(classifier.astext().replace("\n", " "), style=definitions_style)
455 + Text("\n ", end="")
456 )
457 else:
458 self.renderables.append(
459 Text(" ")
460 + Text(term.astext(), style=term_style, end="")
461 + Text(" : ", end="")
462 + Text(classifier.astext(), style=classifier_style)
463 + Text("\n ", end="")
464 + Text(definitions.astext().replace("\n", " "), style=definitions_style)
465 + Text("\n", end="")
466 )
467 raise docutils.nodes.SkipChildren()
468
469 def visit_option_list(self, node):
470 option_string_style = self.console.get_style("restructuredtext.option_string", default="none")
471 option_argument_style = self.console.get_style("restructuredtext.option_argument", default="none")
472 option_child_text_separator_style = self.console.get_style(
473 "restructuredtext.option_child_text_separator", default="none"
474 )
475 option_description_style = self.console.get_style("restructuredtext.option_description", default="none")
476 for option_list_item in node.children:
477 option_group, description = option_list_item.children
478 # option_group.child_text_separator.join(map(lambda x: x.astext(), option_group.children)))
479 option_text = Text(end="")
480 for option in option_group.children:
481 try:
482 option_string, option_argument = option.children
483 except ValueError:
484 option_string, option_argument = option.children[0], None
485 option_text += (
486 Text(option_string.astext(), style=option_string_style)
487 + (Text(option_argument.astext(), style=option_argument_style) if option_argument else Text())
488 + (
489 Text(option_group.child_text_separator, style=option_child_text_separator_style)
490 if len(option_group.children) > 1
491 else ""
492 )
493 )
494 if description:
495 option_text += Text("\n ")
496 option_text += Text(description.astext(), style=option_description_style)
497 self.renderables.append(option_text + Text("\n"))
498 raise docutils.nodes.SkipChildren()
499
500 def visit_doctest_block(self, node):
501 style = self.console.get_style("restructuredtext.literal_block_border", default="grey58")
502 self.renderables.append(
503 Panel(
504 Syntax(node.astext(), "pycon", theme=self.code_theme),
505 border_style=style,
506 box=box.SQUARE,
507 )
508 )
509 raise docutils.nodes.SkipChildren()
510
511 def visit_block_quote(self, node):
512 text_style = self.console.get_style("restructuredtext.blockquote_text", default="white")
513 marker_style = self.console.get_style(
514 "restructuredtext.blockquote_attribution_marker", default="bright_magenta"
515 )
516 author_style = self.console.get_style("restructuredtext.blockquote_attribution_text", default="grey89")
517 try:
518 paragraph, attribution = node.children
519 except ValueError:
520 paragraph = node.children[0]
521 self.renderables.append(
522 Text(" ")
523 + Text(paragraph.astext().replace('\n', ' '), style=text_style)
524 + Text("\n\n")
525 )
526 else:
527 self.renderables.append(
528 Text("▌ ", style=marker_style)
529 + Text(paragraph.astext(), style=text_style)
530 + Text("\n")
531 + Text(" - " + attribution.astext(), style=author_style)
532 )
533 raise docutils.nodes.SkipChildren()
534
535 def visit_line_block(self, node):
536 for line in node.children:
537 self.renderables.append(Text(line.astext()))
538 raise docutils.nodes.SkipChildren()
539
540 def visit_sidebar(self, node):
541 if len(node.children) > 2:
542 title, subtitle, paragraph = node.children
543 else:
544 title, subtitle, paragraph = node.children[0], "", node.children[1]
545
546 self.renderables.append(
547 Panel(paragraph.astext(), title=title.astext(), subtitle=subtitle.astext(), expand=False)
548 )
549
550 raise docutils.nodes.SkipChildren()
551
552 def visit_transition(self, node):
553 style = self.console.get_style("restructuredtext.hr", default="yellow")
554 self.renderables.append(Rule(style=style))
555
556 def visit_rubric(self, node):
557 self.visit_title(node)
558
559 def visit_math_block(self, node):
560 if self.renderables and isinstance(self.renderables[-1], Text):
561 self.renderables[-1].append(Text(node.astext(), end=" "))
562 raise docutils.nodes.SkipChildren()
563 self.renderables.append(Text(node.astext()))
564 raise docutils.nodes.SkipChildren()
565
566 def visit_citation(self, node):
567 border_style = self.console.get_style("restructuredtext.citation_border", default="grey74")
568 self.renderables.append(Panel(node.astext(), title="citation", border_style=border_style))
569 raise docutils.nodes.SkipChildren()
570
571 def visit_citation_reference(self, node):
572 style = self.console.get_style("restructuredtext.citation_reference", default="grey74")
573 if self.renderables and isinstance(self.renderables[-1], Text):
574 self.renderables[-1].append(node.astext().replace("\n", " "), style=style)
575 raise docutils.nodes.SkipChildren()
576 self.renderables.append(Text(node.astext().replace("\n", " "), style=style, end=""))
577 raise docutils.nodes.SkipChildren()
578
579 def visit_header(self, node):
580 style = self.console.get_style("restructuredtext.caption", default="bold")
581 self.renderables.insert(0, Panel(Align(node.astext(), "center"), title="caption", box=box.DOUBLE, style=style))
582 raise docutils.nodes.SkipChildren()
583
584 def visit_footer(self, node):
585 self.footer.append(Align(node.astext(), "center"))
586 raise docutils.nodes.SkipChildren()
587
588 def visit_footnote(self, node):
589 self.footer.append(Align(node.astext(), "center"))
590 raise docutils.nodes.SkipChildren()
591
592 def visit_generated(self, node):
593 self.footer.append(Align(node.astext(), "center"))
594 raise docutils.nodes.SkipChildren()
595
596 def visit_pendings(self, node):
597 raise docutils.nodes.SkipChildren()
598
599 def visit_problematic(self, node):
600 self.errors.append(
601 Panel(
602 Syntax(node.astext(), lexer="rst", theme=self.code_theme),
603 title=f"System Message: Problematic Element",
604 border_style="bold red",
605 ),
606 )
607
608 def visit_raw(self, node):
609 style = self.console.get_style("restructuredtext.literal_block_border", default="grey58")
610 lexer = self._find_lexer(node)
611 text = node.astext()
612 title = "raw " + ("stripped raw html" if lexer == "html" else lexer)
613
614 if lexer == "html":
615 text = strip_tags(text)
616 lexer = guess_lexer(text).aliases[0] if self.guess_lexer else self.default_lexer
617
618 self.renderables.append(
619 Panel(Syntax(text, lexer, theme=self.code_theme), border_style=style, box=box.SQUARE, title=title)
620 )
621 raise docutils.nodes.SkipChildren()
622
623
624 class RestructuredText(JupyterMixin):
625 """A reStructuredText renderable for rich.
626
627 Parameters
628 ----------
629 markup : str
630 A string containing reStructuredText markup.
631 code_theme : Optional[Union[str, SyntaxTheme]]
632 Pygments theme for code blocks. Defaults to "monokai".
633 show_errors : Optional[bool]
634 Whether to show system_messages aka errors and warnings.
635 guess_lexer : Optional[bool]
636 Whether to guess lexers for code blocks without specified language.
637 default_lexer : Optional[str]
638 Which lexer to use if no lexer is guessed or found. Defaults to "python"
639 sphinx_compat : Optional[bool]
640 Enable compatibility with Sphinx roles (func, meth, class, etc.) commonly used in
641 Python docstrings. When enabled, these roles render as inline code instead of errors.
642 Defaults to True for better compatibility with Python documentation.
643 filename : Optional[str]
644 A file name to use for error messages, useful for debugging purposes. Defaults to "<rst-document>"
645 """
646
647 def __init__(
648 self,
649 markup: str,
650 code_theme: Optional[Union[str, SyntaxTheme]] = "monokai",
651 show_errors: Optional[bool] = True,
652 guess_lexer: Optional[bool] = False,
653 default_lexer: Optional[str] = "python",
654 sphinx_compat: Optional[bool] = True,
655 filename: Optional[str] = "<rst-document>"
656 ) -> None:
657 self.markup = markup
658 self.code_theme = code_theme
659 self.log_errors = show_errors
660 self.guess_lexer = guess_lexer
661 self.default_lexer = default_lexer
662 self.sphinx_compat = sphinx_compat
663 self.filename = filename
664
665 def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
666 if self.sphinx_compat:
667 _register_sphinx_roles()
668
669 # Docutils version compatability; from https://stackoverflow.com/a/75996218
670 if hasattr(docutils.frontend, 'get_default_settings'):
671 # docutils >= 0.18
672 settings = docutils.frontend.get_default_settings(docutils.parsers.rst.Parser)
673 else:
674 # docutils < 0.18
675 settings = docutils.frontend.OptionParser(components=(docutils.parsers.rst.Parser,)).get_default_values()
676 settings.report_level = 69
677 source = docutils.io.StringInput(self.markup)
678 document = docutils.utils.new_document(self.filename, settings)
679 rst_parser = docutils.parsers.rst.Parser()
680 rst_parser.parse(source.read(), document)
681
682 # Render the RST `document` using Rich.
683 visitor = RSTVisitor(
684 document,
685 console=console,
686 code_theme=self.code_theme,
687 guess_lexer=self.guess_lexer,
688 default_lexer=self.default_lexer,
689 )
690 document.walkabout(visitor)
691
692 # Strip all trailing newlines and newline-like rich objects
693 while visitor.renderables:
694 if isinstance(visitor.renderables[-1], Text):
695 visitor.renderables[-1].rstrip()
696 visitor.renderables[-1].end = "\n"
697 if visitor.renderables[-1]: # The Text object still contains data.
698 break
699 else:
700 visitor.renderables.pop()
701 elif isinstance(visitor.renderables[-1], NewLine):
702 visitor.renderables.pop()
703 else:
704 break
705
706 for renderable in visitor.renderables:
707 yield from console.render(renderable, options)
708 if self.log_errors and visitor.errors:
709 for error in visitor.errors:
710 yield from console.render(error, options)
711 style = console.get_style("restructuredtext.footer", default="none")
712 border_style = console.get_style("restructuredtext.footer_border", default="grey74")
713 footer_text = ""
714 for element in visitor.footer:
715 footer_text = element
716 if footer_text:
717 yield from console.render(
718 Panel(footer_text, title="Footer", box=box.SQUARE, border_style=border_style, style=style)
719 )
720
721
722 RST = reST = ReStructuredText = reStructuredText = RestructuredText