markdown.py 25 KB

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