markdown.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. from __future__ import annotations
  2. import sys
  3. from typing import ClassVar, Dict, Iterable, List, Optional, Type, Union
  4. from markdown_it import MarkdownIt
  5. from markdown_it.token import Token
  6. if sys.version_info >= (3, 8):
  7. from typing import get_args
  8. else:
  9. from typing_extensions import get_args # pragma: no cover
  10. from rich.table import Table
  11. from . import box
  12. from ._loop import loop_first
  13. from ._stack import Stack
  14. from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
  15. from .containers import Renderables
  16. from .jupyter import JupyterMixin
  17. from .panel import Panel
  18. from .rule import Rule
  19. from .segment import Segment
  20. from .style import Style, StyleStack
  21. from .syntax import Syntax
  22. from .text import Text, TextType
  23. class MarkdownElement:
  24. new_line: ClassVar[bool] = True
  25. @classmethod
  26. def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement":
  27. """Factory to create markdown element,
  28. Args:
  29. markdown (Markdown): The parent Markdown object.
  30. token (Token): A node from markdown-it.
  31. Returns:
  32. MarkdownElement: A new markdown element
  33. """
  34. return cls()
  35. def on_enter(self, context: "MarkdownContext") -> None:
  36. """Called when the node is entered.
  37. Args:
  38. context (MarkdownContext): The markdown context.
  39. """
  40. def on_text(self, context: "MarkdownContext", text: TextType) -> None:
  41. """Called when text is parsed.
  42. Args:
  43. context (MarkdownContext): The markdown context.
  44. """
  45. def on_leave(self, context: "MarkdownContext") -> None:
  46. """Called when the parser leaves the element.
  47. Args:
  48. context (MarkdownContext): [description]
  49. """
  50. def on_child_close(
  51. self, context: "MarkdownContext", child: "MarkdownElement"
  52. ) -> bool:
  53. """Called when a child element is closed.
  54. This method allows a parent element to take over rendering of its children.
  55. Args:
  56. context (MarkdownContext): The markdown context.
  57. child (MarkdownElement): The child markdown element.
  58. Returns:
  59. bool: Return True to render the element, or False to not render the element.
  60. """
  61. return True
  62. def __rich_console__(
  63. self, console: "Console", options: "ConsoleOptions"
  64. ) -> "RenderResult":
  65. return ()
  66. class UnknownElement(MarkdownElement):
  67. """An unknown element.
  68. Hopefully there will be no unknown elements, and we will have a MarkdownElement for
  69. everything in the document.
  70. """
  71. class TextElement(MarkdownElement):
  72. """Base class for elements that render text."""
  73. style_name = "none"
  74. def on_enter(self, context: "MarkdownContext") -> None:
  75. self.style = context.enter_style(self.style_name)
  76. self.text = Text(justify="left")
  77. def on_text(self, context: "MarkdownContext", text: TextType) -> None:
  78. self.text.append(text, context.current_style if isinstance(text, str) else None)
  79. def on_leave(self, context: "MarkdownContext") -> None:
  80. context.leave_style()
  81. class Paragraph(TextElement):
  82. """A Paragraph."""
  83. style_name = "markdown.paragraph"
  84. justify: JustifyMethod
  85. @classmethod
  86. def create(cls, markdown: "Markdown", token: Token) -> "Paragraph":
  87. return cls(justify=markdown.justify or "left")
  88. def __init__(self, justify: JustifyMethod) -> None:
  89. self.justify = justify
  90. def __rich_console__(
  91. self, console: Console, options: ConsoleOptions
  92. ) -> RenderResult:
  93. self.text.justify = self.justify
  94. yield self.text
  95. class Heading(TextElement):
  96. """A heading."""
  97. @classmethod
  98. def create(cls, markdown: "Markdown", token: Token) -> "Heading":
  99. return cls(token.tag)
  100. def on_enter(self, context: "MarkdownContext") -> None:
  101. self.text = Text()
  102. context.enter_style(self.style_name)
  103. def __init__(self, tag: str) -> None:
  104. self.tag = tag
  105. self.style_name = f"markdown.{tag}"
  106. super().__init__()
  107. def __rich_console__(
  108. self, console: Console, options: ConsoleOptions
  109. ) -> RenderResult:
  110. text = self.text
  111. text.justify = "center"
  112. if self.tag == "h1":
  113. # Draw a border around h1s
  114. yield Panel(
  115. text,
  116. box=box.HEAVY,
  117. style="markdown.h1.border",
  118. )
  119. else:
  120. # Styled text for h2 and beyond
  121. if self.tag == "h2":
  122. yield Text("")
  123. yield text
  124. class CodeBlock(TextElement):
  125. """A code block with syntax highlighting."""
  126. style_name = "markdown.code_block"
  127. @classmethod
  128. def create(cls, markdown: "Markdown", token: Token) -> "CodeBlock":
  129. node_info = token.info or ""
  130. lexer_name = node_info.partition(" ")[0]
  131. return cls(lexer_name or "default", markdown.code_theme)
  132. def __init__(self, lexer_name: str, theme: str) -> None:
  133. self.lexer_name = lexer_name
  134. self.theme = theme
  135. def __rich_console__(
  136. self, console: Console, options: ConsoleOptions
  137. ) -> RenderResult:
  138. code = str(self.text).rstrip()
  139. syntax = Syntax(
  140. code, self.lexer_name, theme=self.theme, word_wrap=True, padding=1
  141. )
  142. yield syntax
  143. class BlockQuote(TextElement):
  144. """A block quote."""
  145. style_name = "markdown.block_quote"
  146. def __init__(self) -> None:
  147. self.elements: Renderables = Renderables()
  148. def on_child_close(
  149. self, context: "MarkdownContext", child: "MarkdownElement"
  150. ) -> bool:
  151. self.elements.append(child)
  152. return False
  153. def __rich_console__(
  154. self, console: Console, options: ConsoleOptions
  155. ) -> RenderResult:
  156. render_options = options.update(width=options.max_width - 4)
  157. lines = console.render_lines(self.elements, render_options, style=self.style)
  158. style = self.style
  159. new_line = Segment("\n")
  160. padding = Segment("▌ ", style)
  161. for line in lines:
  162. yield padding
  163. yield from line
  164. yield new_line
  165. class HorizontalRule(MarkdownElement):
  166. """A horizontal rule to divide sections."""
  167. new_line = False
  168. def __rich_console__(
  169. self, console: Console, options: ConsoleOptions
  170. ) -> RenderResult:
  171. style = console.get_style("markdown.hr", default="none")
  172. yield Rule(style=style)
  173. class TableElement(MarkdownElement):
  174. """MarkdownElement corresponding to `table_open`."""
  175. def __init__(self) -> None:
  176. self.header: TableHeaderElement | None = None
  177. self.body: TableBodyElement | None = None
  178. def on_child_close(
  179. self, context: "MarkdownContext", child: "MarkdownElement"
  180. ) -> bool:
  181. if isinstance(child, TableHeaderElement):
  182. self.header = child
  183. elif isinstance(child, TableBodyElement):
  184. self.body = child
  185. else:
  186. raise RuntimeError("Couldn't process markdown table.")
  187. return False
  188. def __rich_console__(
  189. self, console: Console, options: ConsoleOptions
  190. ) -> RenderResult:
  191. table = Table(box=box.SIMPLE_HEAVY)
  192. assert self.header is not None
  193. assert self.header.row is not None
  194. for column in self.header.row.cells:
  195. table.add_column(column.content)
  196. assert self.body is not None
  197. for row in self.body.rows:
  198. row_content = [element.content for element in row.cells]
  199. table.add_row(*row_content)
  200. yield table
  201. class TableHeaderElement(MarkdownElement):
  202. """MarkdownElement corresponding to `thead_open` and `thead_close`."""
  203. def __init__(self) -> None:
  204. self.row: TableRowElement | None = None
  205. def on_child_close(
  206. self, context: "MarkdownContext", child: "MarkdownElement"
  207. ) -> bool:
  208. assert isinstance(child, TableRowElement)
  209. self.row = child
  210. return False
  211. class TableBodyElement(MarkdownElement):
  212. """MarkdownElement corresponding to `tbody_open` and `tbody_close`."""
  213. def __init__(self) -> None:
  214. self.rows: list[TableRowElement] = []
  215. def on_child_close(
  216. self, context: "MarkdownContext", child: "MarkdownElement"
  217. ) -> bool:
  218. assert isinstance(child, TableRowElement)
  219. self.rows.append(child)
  220. return False
  221. class TableRowElement(MarkdownElement):
  222. """MarkdownElement corresponding to `tr_open` and `tr_close`."""
  223. def __init__(self) -> None:
  224. self.cells: List[TableDataElement] = []
  225. def on_child_close(
  226. self, context: "MarkdownContext", child: "MarkdownElement"
  227. ) -> bool:
  228. assert isinstance(child, TableDataElement)
  229. self.cells.append(child)
  230. return False
  231. class TableDataElement(MarkdownElement):
  232. """MarkdownElement corresponding to `td_open` and `td_close`
  233. and `th_open` and `th_close`."""
  234. @classmethod
  235. def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement":
  236. style = str(token.attrs.get("style" "")) or ""
  237. justify: JustifyMethod
  238. if "text-align:right" in style:
  239. justify = "right"
  240. elif "text-align:center" in style:
  241. justify = "center"
  242. elif "text-align:left" in style:
  243. justify = "left"
  244. else:
  245. justify = "default"
  246. assert justify in get_args(JustifyMethod)
  247. return cls(justify=justify)
  248. def __init__(self, justify: JustifyMethod) -> None:
  249. self.content: TextType = ""
  250. self.justify = justify
  251. def on_text(self, context: "MarkdownContext", text: TextType) -> None:
  252. plain = text.plain if isinstance(text, Text) else text
  253. style = text.style if isinstance(text, Text) else ""
  254. self.content = Text(
  255. plain, justify=self.justify, style=context.style_stack.current
  256. )
  257. class ListElement(MarkdownElement):
  258. """A list element."""
  259. @classmethod
  260. def create(cls, markdown: "Markdown", token: Token) -> "ListElement":
  261. return cls(token.type, int(token.attrs.get("start", 1)))
  262. def __init__(self, list_type: str, list_start: int | None) -> None:
  263. self.items: List[ListItem] = []
  264. self.list_type = list_type
  265. self.list_start = list_start
  266. def on_child_close(
  267. self, context: "MarkdownContext", child: "MarkdownElement"
  268. ) -> bool:
  269. assert isinstance(child, ListItem)
  270. self.items.append(child)
  271. return False
  272. def __rich_console__(
  273. self, console: Console, options: ConsoleOptions
  274. ) -> RenderResult:
  275. if self.list_type == "bullet_list_open":
  276. for item in self.items:
  277. yield from item.render_bullet(console, options)
  278. else:
  279. number = 1 if self.list_start is None else self.list_start
  280. last_number = number + len(self.items)
  281. for index, item in enumerate(self.items):
  282. yield from item.render_number(
  283. console, options, number + index, last_number
  284. )
  285. class ListItem(TextElement):
  286. """An item in a list."""
  287. style_name = "markdown.item"
  288. def __init__(self) -> None:
  289. self.elements: Renderables = Renderables()
  290. def on_child_close(
  291. self, context: "MarkdownContext", child: "MarkdownElement"
  292. ) -> bool:
  293. self.elements.append(child)
  294. return False
  295. def render_bullet(self, console: Console, options: ConsoleOptions) -> RenderResult:
  296. render_options = options.update(width=options.max_width - 3)
  297. lines = console.render_lines(self.elements, render_options, style=self.style)
  298. bullet_style = console.get_style("markdown.item.bullet", default="none")
  299. bullet = Segment(" • ", bullet_style)
  300. padding = Segment(" " * 3, bullet_style)
  301. new_line = Segment("\n")
  302. for first, line in loop_first(lines):
  303. yield bullet if first else padding
  304. yield from line
  305. yield new_line
  306. def render_number(
  307. self, console: Console, options: ConsoleOptions, number: int, last_number: int
  308. ) -> RenderResult:
  309. number_width = len(str(last_number)) + 2
  310. render_options = options.update(width=options.max_width - number_width)
  311. lines = console.render_lines(self.elements, render_options, style=self.style)
  312. number_style = console.get_style("markdown.item.number", default="none")
  313. new_line = Segment("\n")
  314. padding = Segment(" " * number_width, number_style)
  315. numeral = Segment(f"{number}".rjust(number_width - 1) + " ", number_style)
  316. for first, line in loop_first(lines):
  317. yield numeral if first else padding
  318. yield from line
  319. yield new_line
  320. class Link(TextElement):
  321. @classmethod
  322. def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement":
  323. url = token.attrs.get("href", "#")
  324. return cls(token.content, str(url))
  325. def __init__(self, text: str, href: str):
  326. self.text = Text(text)
  327. self.href = href
  328. class ImageItem(TextElement):
  329. """Renders a placeholder for an image."""
  330. new_line = False
  331. @classmethod
  332. def create(cls, markdown: "Markdown", token: Token) -> "MarkdownElement":
  333. """Factory to create markdown element,
  334. Args:
  335. markdown (Markdown): The parent Markdown object.
  336. token (Any): A token from markdown-it.
  337. Returns:
  338. MarkdownElement: A new markdown element
  339. """
  340. return cls(str(token.attrs.get("src", "")), markdown.hyperlinks)
  341. def __init__(self, destination: str, hyperlinks: bool) -> None:
  342. self.destination = destination
  343. self.hyperlinks = hyperlinks
  344. self.link: Optional[str] = None
  345. super().__init__()
  346. def on_enter(self, context: "MarkdownContext") -> None:
  347. self.link = context.current_style.link
  348. self.text = Text(justify="left")
  349. super().on_enter(context)
  350. def __rich_console__(
  351. self, console: Console, options: ConsoleOptions
  352. ) -> RenderResult:
  353. link_style = Style(link=self.link or self.destination or None)
  354. title = self.text or Text(self.destination.strip("/").rsplit("/", 1)[-1])
  355. if self.hyperlinks:
  356. title.stylize(link_style)
  357. text = Text.assemble("🌆 ", title, " ", end="")
  358. yield text
  359. class MarkdownContext:
  360. """Manages the console render state."""
  361. def __init__(
  362. self,
  363. console: Console,
  364. options: ConsoleOptions,
  365. style: Style,
  366. inline_code_lexer: Optional[str] = None,
  367. inline_code_theme: str = "monokai",
  368. ) -> None:
  369. self.console = console
  370. self.options = options
  371. self.style_stack: StyleStack = StyleStack(style)
  372. self.stack: Stack[MarkdownElement] = Stack()
  373. self._syntax: Optional[Syntax] = None
  374. if inline_code_lexer is not None:
  375. self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme)
  376. @property
  377. def current_style(self) -> Style:
  378. """Current style which is the product of all styles on the stack."""
  379. return self.style_stack.current
  380. def on_text(self, text: str, node_type: str) -> None:
  381. """Called when the parser visits text."""
  382. if node_type in {"fence", "code_inline"} and self._syntax is not None:
  383. highlight_text = self._syntax.highlight(text)
  384. highlight_text.rstrip()
  385. self.stack.top.on_text(
  386. self, Text.assemble(highlight_text, style=self.style_stack.current)
  387. )
  388. else:
  389. self.stack.top.on_text(self, text)
  390. def enter_style(self, style_name: Union[str, Style]) -> Style:
  391. """Enter a style context."""
  392. style = self.console.get_style(style_name, default="none")
  393. self.style_stack.push(style)
  394. return self.current_style
  395. def leave_style(self) -> Style:
  396. """Leave a style context."""
  397. style = self.style_stack.pop()
  398. return style
  399. class Markdown(JupyterMixin):
  400. """A Markdown renderable.
  401. Args:
  402. markup (str): A string containing markdown.
  403. code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai".
  404. justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None.
  405. style (Union[str, Style], optional): Optional style to apply to markdown.
  406. hyperlinks (bool, optional): Enable hyperlinks. Defaults to ``True``.
  407. inline_code_lexer: (str, optional): Lexer to use if inline code highlighting is
  408. enabled. Defaults to None.
  409. inline_code_theme: (Optional[str], optional): Pygments theme for inline code
  410. highlighting, or None for no highlighting. Defaults to None.
  411. """
  412. elements: ClassVar[Dict[str, Type[MarkdownElement]]] = {
  413. "paragraph_open": Paragraph,
  414. "heading_open": Heading,
  415. "fence": CodeBlock,
  416. "code_block": CodeBlock,
  417. "blockquote_open": BlockQuote,
  418. "hr": HorizontalRule,
  419. "bullet_list_open": ListElement,
  420. "ordered_list_open": ListElement,
  421. "list_item_open": ListItem,
  422. "image": ImageItem,
  423. "table_open": TableElement,
  424. "tbody_open": TableBodyElement,
  425. "thead_open": TableHeaderElement,
  426. "tr_open": TableRowElement,
  427. "td_open": TableDataElement,
  428. "th_open": TableDataElement,
  429. }
  430. inlines = {"em", "strong", "code", "s"}
  431. def __init__(
  432. self,
  433. markup: str,
  434. code_theme: str = "monokai",
  435. justify: Optional[JustifyMethod] = None,
  436. style: Union[str, Style] = "none",
  437. hyperlinks: bool = True,
  438. inline_code_lexer: Optional[str] = None,
  439. inline_code_theme: Optional[str] = None,
  440. ) -> None:
  441. parser = MarkdownIt().enable("strikethrough").enable("table")
  442. self.markup = markup
  443. self.parsed = parser.parse(markup)
  444. self.code_theme = code_theme
  445. self.justify: Optional[JustifyMethod] = justify
  446. self.style = style
  447. self.hyperlinks = hyperlinks
  448. self.inline_code_lexer = inline_code_lexer
  449. self.inline_code_theme = inline_code_theme or code_theme
  450. def _flatten_tokens(self, tokens: Iterable[Token]) -> Iterable[Token]:
  451. """Flattens the token stream."""
  452. for token in tokens:
  453. is_fence = token.type == "fence"
  454. is_image = token.tag == "img"
  455. if token.children and not (is_image or is_fence):
  456. yield from self._flatten_tokens(token.children)
  457. else:
  458. yield token
  459. def __rich_console__(
  460. self, console: Console, options: ConsoleOptions
  461. ) -> RenderResult:
  462. """Render markdown to the console."""
  463. style = console.get_style(self.style, default="none")
  464. options = options.update(height=None)
  465. context = MarkdownContext(
  466. console,
  467. options,
  468. style,
  469. inline_code_lexer=self.inline_code_lexer,
  470. inline_code_theme=self.inline_code_theme,
  471. )
  472. tokens = self.parsed
  473. inline_style_tags = self.inlines
  474. new_line = False
  475. _new_line_segment = Segment.line()
  476. for token in self._flatten_tokens(tokens):
  477. node_type = token.type
  478. tag = token.tag
  479. entering = token.nesting == 1
  480. exiting = token.nesting == -1
  481. self_closing = token.nesting == 0
  482. if node_type == "text":
  483. context.on_text(token.content, node_type)
  484. elif node_type == "hardbreak":
  485. context.on_text("\n", node_type)
  486. elif node_type == "softbreak":
  487. context.on_text(" ", node_type)
  488. elif node_type == "link_open":
  489. href = str(token.attrs.get("href", ""))
  490. if self.hyperlinks:
  491. link_style = console.get_style("markdown.link_url", default="none")
  492. link_style += Style(link=href)
  493. context.enter_style(link_style)
  494. else:
  495. context.stack.push(Link.create(self, token))
  496. elif node_type == "link_close":
  497. if self.hyperlinks:
  498. context.leave_style()
  499. else:
  500. element = context.stack.pop()
  501. assert isinstance(element, Link)
  502. link_style = console.get_style("markdown.link", default="none")
  503. context.enter_style(link_style)
  504. context.on_text(element.text.plain, node_type)
  505. context.leave_style()
  506. context.on_text(" (", node_type)
  507. link_url_style = console.get_style(
  508. "markdown.link_url", default="none"
  509. )
  510. context.enter_style(link_url_style)
  511. context.on_text(element.href, node_type)
  512. context.leave_style()
  513. context.on_text(")", node_type)
  514. elif (
  515. tag in inline_style_tags
  516. and node_type != "fence"
  517. and node_type != "code_block"
  518. ):
  519. if entering:
  520. # If it's an opening inline token e.g. strong, em, etc.
  521. # Then we move into a style context i.e. push to stack.
  522. context.enter_style(f"markdown.{tag}")
  523. elif exiting:
  524. # If it's a closing inline style, then we pop the style
  525. # off of the stack, to move out of the context of it...
  526. context.leave_style()
  527. else:
  528. # If it's a self-closing inline style e.g. `code_inline`
  529. context.enter_style(f"markdown.{tag}")
  530. if token.content:
  531. context.on_text(token.content, node_type)
  532. context.leave_style()
  533. else:
  534. # Map the markdown tag -> MarkdownElement renderable
  535. element_class = self.elements.get(token.type) or UnknownElement
  536. element = element_class.create(self, token)
  537. if entering or self_closing:
  538. context.stack.push(element)
  539. element.on_enter(context)
  540. if exiting: # CLOSING tag
  541. element = context.stack.pop()
  542. should_render = not context.stack or (
  543. context.stack
  544. and context.stack.top.on_child_close(context, element)
  545. )
  546. if should_render:
  547. if new_line:
  548. yield _new_line_segment
  549. yield from console.render(element, context.options)
  550. elif self_closing: # SELF-CLOSING tags (e.g. text, code, image)
  551. context.stack.pop()
  552. text = token.content
  553. if text is not None:
  554. element.on_text(context, text)
  555. should_render = (
  556. not context.stack
  557. or context.stack
  558. and context.stack.top.on_child_close(context, element)
  559. )
  560. if should_render:
  561. if new_line:
  562. yield _new_line_segment
  563. yield from console.render(element, context.options)
  564. if exiting or self_closing:
  565. element.on_leave(context)
  566. new_line = element.new_line
  567. if __name__ == "__main__": # pragma: no cover
  568. import argparse
  569. import sys
  570. parser = argparse.ArgumentParser(
  571. description="Render Markdown to the console with Rich"
  572. )
  573. parser.add_argument(
  574. "path",
  575. metavar="PATH",
  576. help="path to markdown file, or - for stdin",
  577. )
  578. parser.add_argument(
  579. "-c",
  580. "--force-color",
  581. dest="force_color",
  582. action="store_true",
  583. default=None,
  584. help="force color for non-terminals",
  585. )
  586. parser.add_argument(
  587. "-t",
  588. "--code-theme",
  589. dest="code_theme",
  590. default="monokai",
  591. help="pygments code theme",
  592. )
  593. parser.add_argument(
  594. "-i",
  595. "--inline-code-lexer",
  596. dest="inline_code_lexer",
  597. default=None,
  598. help="inline_code_lexer",
  599. )
  600. parser.add_argument(
  601. "-y",
  602. "--hyperlinks",
  603. dest="hyperlinks",
  604. action="store_true",
  605. help="enable hyperlinks",
  606. )
  607. parser.add_argument(
  608. "-w",
  609. "--width",
  610. type=int,
  611. dest="width",
  612. default=None,
  613. help="width of output (default will auto-detect)",
  614. )
  615. parser.add_argument(
  616. "-j",
  617. "--justify",
  618. dest="justify",
  619. action="store_true",
  620. help="enable full text justify",
  621. )
  622. parser.add_argument(
  623. "-p",
  624. "--page",
  625. dest="page",
  626. action="store_true",
  627. help="use pager to scroll output",
  628. )
  629. args = parser.parse_args()
  630. from rich.console import Console
  631. if args.path == "-":
  632. markdown_body = sys.stdin.read()
  633. else:
  634. with open(args.path, "rt", encoding="utf-8") as markdown_file:
  635. markdown_body = markdown_file.read()
  636. markdown = Markdown(
  637. markdown_body,
  638. justify="full" if args.justify else "left",
  639. code_theme=args.code_theme,
  640. hyperlinks=args.hyperlinks,
  641. inline_code_lexer=args.inline_code_lexer,
  642. )
  643. if args.page:
  644. import io
  645. import pydoc
  646. fileio = io.StringIO()
  647. console = Console(
  648. file=fileio, force_terminal=args.force_color, width=args.width
  649. )
  650. console.print(markdown)
  651. pydoc.pager(fileio.getvalue())
  652. else:
  653. console = Console(
  654. force_terminal=args.force_color, width=args.width, record=True
  655. )
  656. console.print(markdown)