termrender 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
termrender/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """termrender — render Markdown to ANSI terminal output."""
2
+
3
+ import os
4
+ import shutil
5
+ from termrender.parser import parse
6
+ from termrender.layout import layout
7
+ from termrender.emit import emit
8
+
9
+
10
+ class TerminalError(Exception):
11
+ """Raised when the terminal does not support required capabilities."""
12
+
13
+
14
+ def render(source: str, width: int | None = None, color: bool = True) -> str:
15
+ """Render directive-flavored markdown to ANSI terminal output.
16
+
17
+ Args:
18
+ source: Markdown string with optional directives
19
+ width: Terminal width in columns (auto-detected if None)
20
+ color: Enable ANSI color codes (respects NO_COLOR env var)
21
+
22
+ Returns:
23
+ Rendered string with ANSI escape sequences
24
+
25
+ Raises:
26
+ TerminalError: If terminal is unsupported (TERM=dumb)
27
+ """
28
+ # REQ-011: Check terminal capability
29
+ if os.environ.get("TERM") == "dumb":
30
+ raise TerminalError("Terminal type 'dumb' does not support Unicode rendering")
31
+
32
+ # Respect NO_COLOR convention (https://no-color.org/)
33
+ if os.environ.get("NO_COLOR") is not None:
34
+ color = False
35
+
36
+ # Auto-detect width
37
+ if width is None:
38
+ width = shutil.get_terminal_size().columns
39
+
40
+ # Pipeline: parse → layout → emit
41
+ doc = parse(source)
42
+ layout(doc, width)
43
+ return emit(doc, color)
termrender/__main__.py ADDED
@@ -0,0 +1,46 @@
1
+ """CLI entry point for termrender."""
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from termrender import render, TerminalError
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(
11
+ prog="termrender",
12
+ description="Render Markdown to ANSI terminal output",
13
+ )
14
+ parser.add_argument(
15
+ "file",
16
+ nargs="?",
17
+ type=argparse.FileType("r"),
18
+ default=sys.stdin,
19
+ help="Markdown file to render (reads stdin if omitted)",
20
+ )
21
+ parser.add_argument(
22
+ "--width",
23
+ type=int,
24
+ default=None,
25
+ help="Terminal width in columns (auto-detected if omitted)",
26
+ )
27
+ parser.add_argument(
28
+ "--no-color",
29
+ action="store_true",
30
+ help="Disable ANSI color output",
31
+ )
32
+ args = parser.parse_args()
33
+
34
+ source = args.file.read()
35
+
36
+ try:
37
+ output = render(source, width=args.width, color=not args.no_color)
38
+ except TerminalError as e:
39
+ print(f"termrender: {e}", file=sys.stderr)
40
+ sys.exit(1)
41
+
42
+ sys.stdout.write(output)
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
termrender/blocks.py ADDED
@@ -0,0 +1,48 @@
1
+ """Core block data model for termrender."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import Enum
7
+ from typing import Any
8
+
9
+
10
+ class BlockType(Enum):
11
+ """Types of renderable blocks."""
12
+
13
+ DOCUMENT = "document"
14
+ PARAGRAPH = "paragraph"
15
+ HEADING = "heading"
16
+ PANEL = "panel"
17
+ COLUMNS = "columns"
18
+ COL = "col"
19
+ TREE = "tree"
20
+ CALLOUT = "callout"
21
+ QUOTE = "quote"
22
+ CODE = "code"
23
+ DIVIDER = "divider"
24
+ MERMAID = "mermaid"
25
+ LIST = "list"
26
+ LIST_ITEM = "list_item"
27
+
28
+
29
+ @dataclass
30
+ class InlineSpan:
31
+ """A span of inline text with optional formatting."""
32
+
33
+ text: str
34
+ bold: bool = False
35
+ italic: bool = False
36
+ code: bool = False
37
+
38
+
39
+ @dataclass
40
+ class Block:
41
+ """A renderable block element with optional children and inline text."""
42
+
43
+ type: BlockType
44
+ children: list[Block] = field(default_factory=list)
45
+ text: list[InlineSpan] = field(default_factory=list)
46
+ attrs: dict[str, Any] = field(default_factory=dict)
47
+ width: int | None = None
48
+ height: int | None = None
termrender/emit.py ADDED
@@ -0,0 +1,52 @@
1
+ """AST walker that dispatches laid-out blocks to renderers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from termrender.blocks import Block, BlockType
6
+ from termrender.renderers import panel, columns, tree, code, text, divider, quote, mermaid
7
+
8
+
9
+ def emit_block(block: Block, color: bool) -> list[str]:
10
+ """Render a single block and its children, returning output lines."""
11
+ match block.type:
12
+ case BlockType.DOCUMENT | BlockType.COL:
13
+ lines: list[str] = []
14
+ for child in block.children:
15
+ lines.extend(emit_block(child, color))
16
+ return lines
17
+
18
+ case BlockType.PANEL:
19
+ return panel.render(block, color, render_child=emit_block)
20
+
21
+ case BlockType.CALLOUT:
22
+ return panel.render_callout(block, color, render_child=emit_block)
23
+
24
+ case BlockType.COLUMNS:
25
+ return columns.render(block, color, render_child=emit_block)
26
+
27
+ case BlockType.QUOTE:
28
+ return quote.render(block, color, render_child=emit_block)
29
+
30
+ case BlockType.CODE:
31
+ return code.render(block, color, render_child=emit_block)
32
+
33
+ case BlockType.PARAGRAPH | BlockType.HEADING | BlockType.LIST | BlockType.LIST_ITEM:
34
+ return text.render(block, color)
35
+
36
+ case BlockType.TREE:
37
+ return tree.render(block, color)
38
+
39
+ case BlockType.MERMAID:
40
+ return mermaid.render(block, color)
41
+
42
+ case BlockType.DIVIDER:
43
+ return divider.render(block, color)
44
+
45
+ case _:
46
+ return []
47
+
48
+
49
+ def emit(doc: Block, color: bool) -> str:
50
+ """Walk the block tree and return the fully rendered string."""
51
+ lines = emit_block(doc, color)
52
+ return "\n".join(lines)
termrender/layout.py ADDED
@@ -0,0 +1,134 @@
1
+ """Two-pass layout engine: resolve widths top-down, heights bottom-up."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+
7
+ from termrender.blocks import Block, BlockType
8
+ from termrender.style import wrap_text
9
+
10
+
11
+ def _plain_text(spans: list) -> str:
12
+ return "".join(s.text for s in spans)
13
+
14
+
15
+ def resolve_width(block: Block, available: int) -> None:
16
+ block.width = available
17
+
18
+ bt = block.type
19
+ if bt in (BlockType.PANEL, BlockType.CALLOUT, BlockType.CODE, BlockType.QUOTE):
20
+ inner = max(available - 4, 1)
21
+ for child in block.children:
22
+ resolve_width(child, inner)
23
+
24
+ elif bt == BlockType.COLUMNS:
25
+ n = len(block.children)
26
+ if n == 0:
27
+ return
28
+ gaps = n - 1
29
+ inner = available
30
+
31
+ # Separate children into explicit-width and auto-width
32
+ explicit: dict[int, int] = {}
33
+ for i, col in enumerate(block.children):
34
+ w = col.attrs.get("width")
35
+ if w is not None:
36
+ w_str = str(w)
37
+ try:
38
+ if w_str.endswith("%"):
39
+ explicit[i] = max(int(inner * float(w_str[:-1]) / 100), 1)
40
+ else:
41
+ explicit[i] = max(int(w_str), 1)
42
+ except ValueError:
43
+ pass
44
+
45
+ used = sum(explicit.values()) + gaps
46
+ remaining = max(inner - used, 0)
47
+ auto_count = n - len(explicit)
48
+
49
+ for i, col in enumerate(block.children):
50
+ if i in explicit:
51
+ col_w = explicit[i]
52
+ elif auto_count > 0:
53
+ col_w = max(remaining // auto_count, 1)
54
+ else:
55
+ col_w = 1
56
+ resolve_width(col, col_w)
57
+
58
+ else:
59
+ for child in block.children:
60
+ resolve_width(child, available)
61
+
62
+
63
+ def resolve_height(block: Block) -> None:
64
+ # Recurse children first (bottom-up)
65
+ for child in block.children:
66
+ resolve_height(child)
67
+
68
+ bt = block.type
69
+ width = block.width or 1
70
+
71
+ if bt == BlockType.PARAGRAPH:
72
+ text = _plain_text(block.text)
73
+ lines = wrap_text(text, width)
74
+ block.height = len(lines)
75
+
76
+ elif bt == BlockType.HEADING:
77
+ block.height = 1
78
+
79
+ elif bt == BlockType.DIVIDER:
80
+ block.height = 1
81
+
82
+ elif bt in (BlockType.PANEL, BlockType.CALLOUT):
83
+ block.height = sum(c.height or 0 for c in block.children) + 2
84
+
85
+ elif bt == BlockType.CODE:
86
+ source = block.attrs.get("source") or _plain_text(block.text)
87
+ code_lines = source.split("\n") if source else [""]
88
+ block.height = len(code_lines) + 2
89
+
90
+ elif bt == BlockType.COLUMNS:
91
+ block.height = max((c.height or 0 for c in block.children), default=0)
92
+
93
+ elif bt in (BlockType.COL, BlockType.DOCUMENT, BlockType.LIST):
94
+ block.height = sum(c.height or 0 for c in block.children)
95
+
96
+ elif bt == BlockType.LIST_ITEM:
97
+ text_height = 0
98
+ if block.text:
99
+ text_lines = wrap_text(_plain_text(block.text), max(width - 2, 1))
100
+ text_height = len(text_lines)
101
+ block.height = text_height + sum(c.height or 0 for c in block.children)
102
+
103
+ elif bt == BlockType.TREE:
104
+ source = block.attrs.get("source", "")
105
+ block.height = len(source.split("\n")) if source else 1
106
+
107
+ elif bt == BlockType.MERMAID:
108
+ source = block.attrs.get("source", "") or _plain_text(block.text)
109
+ rendered = source # fallback
110
+ try:
111
+ result = subprocess.run(
112
+ ["mermaid-ascii", "-f", "-"],
113
+ input=source,
114
+ capture_output=True,
115
+ text=True,
116
+ check=True,
117
+ timeout=30,
118
+ )
119
+ rendered = result.stdout
120
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
121
+ pass
122
+ block.attrs["_rendered"] = rendered
123
+ block.height = len(rendered.split("\n")) if rendered else 1
124
+
125
+ elif bt == BlockType.QUOTE:
126
+ block.height = sum(c.height or 0 for c in block.children) + (1 if block.attrs.get("by") else 0)
127
+
128
+ else:
129
+ block.height = sum(c.height or 0 for c in block.children)
130
+
131
+
132
+ def layout(doc: Block, width: int) -> None:
133
+ resolve_width(doc, width)
134
+ resolve_height(doc)
termrender/parser.py ADDED
@@ -0,0 +1,322 @@
1
+ """Two-pass markdown+directive parser for termrender.
2
+
3
+ Pass 1 (directive pass): Scans raw source for :::name{attrs} directives using
4
+ a stack-based depth tracker. Segments between directives are plain markdown.
5
+
6
+ Pass 2 (mistune pass): Parses plain markdown segments via mistune v3 AST mode,
7
+ then converts the dict-based AST into our Block tree.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from typing import Any
14
+
15
+ import mistune
16
+
17
+ from termrender.blocks import Block, BlockType, InlineSpan
18
+
19
+ # Matches ANSI escape sequences that are NOT SGR (Select Graphic Rendition).
20
+ # SGR sequences have the form \x1b[...m — we keep those.
21
+ # Strip OSC (\x1b]), screen control (\x1b[...J, \x1b[...H, etc.), and others.
22
+ _UNSAFE_ANSI_RE = re.compile(
23
+ r'\x1b' # ESC
24
+ r'(?!' # negative lookahead: don't match SGR
25
+ r'\[[0-9;]*m' # SGR pattern
26
+ r')'
27
+ r'[\x20-\x7e]*' # match the rest of the sequence
28
+ )
29
+
30
+
31
+ def _sanitize_text(text: str) -> str:
32
+ """Strip non-SGR ANSI escape sequences from text."""
33
+ return _UNSAFE_ANSI_RE.sub('', text)
34
+
35
+ # Directive opener: :::name or :::name{attrs}
36
+ _DIRECTIVE_OPEN = re.compile(
37
+ r"^:::(\w+)(?:\{([^}]*)\})?\s*$"
38
+ )
39
+ # Directive closer: exactly ::: on its own line
40
+ _DIRECTIVE_CLOSE = re.compile(r"^:::\s*$")
41
+
42
+ # Attribute parser: key=value or key="quoted value"
43
+ _ATTR_PAIR = re.compile(
44
+ r"""(\w+)\s*=\s*(?:"([^"]*?)"|(\S+))"""
45
+ )
46
+
47
+ _DIRECTIVE_TO_BLOCK: dict[str, BlockType] = {
48
+ "panel": BlockType.PANEL,
49
+ "columns": BlockType.COLUMNS,
50
+ "col": BlockType.COL,
51
+ "tree": BlockType.TREE,
52
+ "callout": BlockType.CALLOUT,
53
+ "quote": BlockType.QUOTE,
54
+ "code": BlockType.CODE,
55
+ "divider": BlockType.DIVIDER,
56
+ }
57
+
58
+ _mistune_md = mistune.create_markdown(renderer="ast")
59
+
60
+
61
+ def _parse_attrs(raw: str | None) -> dict[str, Any]:
62
+ """Parse directive attributes from {key=value key2="quoted"} string."""
63
+ if not raw:
64
+ return {}
65
+ attrs: dict[str, Any] = {}
66
+ for m in _ATTR_PAIR.finditer(raw):
67
+ key = m.group(1)
68
+ value = m.group(2) if m.group(2) is not None else m.group(3)
69
+ attrs[key] = value
70
+ return attrs
71
+
72
+
73
+ def _convert_inline(nodes: list[dict]) -> list[InlineSpan]:
74
+ """Convert mistune inline AST nodes to InlineSpan list."""
75
+ spans: list[InlineSpan] = []
76
+ for node in nodes:
77
+ ntype = node["type"]
78
+ if ntype == "text":
79
+ spans.append(InlineSpan(text=_sanitize_text(node["raw"])))
80
+ elif ntype == "codespan":
81
+ spans.append(InlineSpan(text=node["raw"], code=True))
82
+ elif ntype == "strong":
83
+ for child in _convert_inline(node.get("children", [])):
84
+ spans.append(InlineSpan(text=child.text, bold=True, italic=child.italic, code=child.code))
85
+ elif ntype == "emphasis":
86
+ for child in _convert_inline(node.get("children", [])):
87
+ spans.append(InlineSpan(text=child.text, italic=True, bold=child.bold, code=child.code))
88
+ elif ntype == "softbreak":
89
+ spans.append(InlineSpan(text=" "))
90
+ elif ntype == "linebreak":
91
+ spans.append(InlineSpan(text="\n"))
92
+ else:
93
+ # Fallback: try raw text
94
+ if "raw" in node:
95
+ spans.append(InlineSpan(text=node["raw"]))
96
+ elif "children" in node:
97
+ spans.extend(_convert_inline(node["children"]))
98
+ return spans
99
+
100
+
101
+ def _convert_ast(nodes: list[dict]) -> list[Block]:
102
+ """Convert mistune AST nodes into Block tree."""
103
+ blocks: list[Block] = []
104
+ for node in nodes:
105
+ ntype = node["type"]
106
+
107
+ if ntype == "blank_line":
108
+ continue
109
+
110
+ if ntype == "heading":
111
+ level = node.get("attrs", {}).get("level", 1)
112
+ text = _convert_inline(node.get("children", []))
113
+ blocks.append(Block(
114
+ type=BlockType.HEADING,
115
+ text=text,
116
+ attrs={"level": level},
117
+ ))
118
+
119
+ elif ntype == "paragraph":
120
+ text = _convert_inline(node.get("children", []))
121
+ blocks.append(Block(type=BlockType.PARAGRAPH, text=text))
122
+
123
+ elif ntype == "block_code":
124
+ raw = node.get("raw", "")
125
+ info = node.get("attrs", {}).get("info", "")
126
+ if info == "mermaid":
127
+ blocks.append(Block(
128
+ type=BlockType.MERMAID,
129
+ attrs={"source": raw},
130
+ ))
131
+ else:
132
+ blocks.append(Block(
133
+ type=BlockType.CODE,
134
+ attrs={"lang": info, "source": raw},
135
+ ))
136
+
137
+ elif ntype == "list":
138
+ ordered = node.get("attrs", {}).get("ordered", False)
139
+ items: list[Block] = []
140
+ for item_node in node.get("children", []):
141
+ if item_node["type"] == "list_item":
142
+ item_children = item_node.get("children", [])
143
+ # list_item contains block_text nodes
144
+ item_spans: list[InlineSpan] = []
145
+ sub_blocks: list[Block] = []
146
+ for child in item_children:
147
+ if child["type"] == "block_text":
148
+ item_spans.extend(_convert_inline(child.get("children", [])))
149
+ else:
150
+ sub_blocks.extend(_convert_ast([child]))
151
+ items.append(Block(
152
+ type=BlockType.LIST_ITEM,
153
+ text=item_spans,
154
+ children=sub_blocks,
155
+ ))
156
+ blocks.append(Block(
157
+ type=BlockType.LIST,
158
+ children=items,
159
+ attrs={"ordered": ordered},
160
+ ))
161
+
162
+ elif ntype == "thematic_break":
163
+ blocks.append(Block(type=BlockType.DIVIDER))
164
+
165
+ elif ntype == "block_quote":
166
+ children = _convert_ast(node.get("children", []))
167
+ blocks.append(Block(type=BlockType.QUOTE, children=children))
168
+
169
+ else:
170
+ # Unknown block type - try to extract any content
171
+ if "children" in node:
172
+ blocks.extend(_convert_ast(node["children"]))
173
+
174
+ return blocks
175
+
176
+
177
+ def _parse_markdown(source: str) -> list[Block]:
178
+ """Parse a markdown string via mistune and convert to Block list."""
179
+ if not source.strip():
180
+ return []
181
+ ast_nodes = _mistune_md(source)
182
+ return _convert_ast(ast_nodes)
183
+
184
+
185
+ def _split_directives(source: str) -> list[dict]:
186
+ """Split source into directive and markdown segments.
187
+
188
+ Returns a list of segments, each being either:
189
+ {"type": "markdown", "content": str}
190
+ {"type": "directive", "name": str, "attrs": dict, "body": str}
191
+ """
192
+ lines = source.split("\n")
193
+ segments: list[dict] = []
194
+ current_md_lines: list[str] = []
195
+ stack: list[dict] = [] # stack of open directives
196
+
197
+ i = 0
198
+ while i < len(lines):
199
+ line = lines[i]
200
+
201
+ # Check for directive opener
202
+ m_open = _DIRECTIVE_OPEN.match(line)
203
+ if m_open:
204
+ if not stack:
205
+ # Top-level directive opening — flush accumulated markdown
206
+ if current_md_lines:
207
+ segments.append({
208
+ "type": "markdown",
209
+ "content": "\n".join(current_md_lines),
210
+ })
211
+ current_md_lines = []
212
+ entry = {
213
+ "name": m_open.group(1),
214
+ "attrs_raw": m_open.group(2),
215
+ "body_lines": [],
216
+ "depth": 1,
217
+ }
218
+ # Self-closing directives (no body content expected)
219
+ if entry["name"] in ("divider",):
220
+ segments.append({
221
+ "type": "directive",
222
+ "name": entry["name"],
223
+ "attrs": _parse_attrs(entry["attrs_raw"]),
224
+ "body": "",
225
+ })
226
+ else:
227
+ stack.append(entry)
228
+ else:
229
+ # Nested directive — track depth and include line in body
230
+ stack[-1]["depth"] += 1
231
+ stack[-1]["body_lines"].append(line)
232
+ i += 1
233
+ continue
234
+
235
+ # Check for directive closer
236
+ m_close = _DIRECTIVE_CLOSE.match(line)
237
+ if m_close and stack:
238
+ if stack[-1]["depth"] > 1:
239
+ # Closing a nested directive
240
+ stack[-1]["depth"] -= 1
241
+ stack[-1]["body_lines"].append(line)
242
+ else:
243
+ # Closing the top-level directive
244
+ entry = stack.pop()
245
+ segments.append({
246
+ "type": "directive",
247
+ "name": entry["name"],
248
+ "attrs": _parse_attrs(entry["attrs_raw"]),
249
+ "body": "\n".join(entry["body_lines"]),
250
+ })
251
+ i += 1
252
+ continue
253
+
254
+ # Regular line
255
+ if stack:
256
+ stack[-1]["body_lines"].append(line)
257
+ else:
258
+ current_md_lines.append(line)
259
+ i += 1
260
+
261
+ # Flush remaining markdown
262
+ if current_md_lines:
263
+ segments.append({
264
+ "type": "markdown",
265
+ "content": "\n".join(current_md_lines),
266
+ })
267
+
268
+ # If stack is not empty, treat unclosed directives as markdown
269
+ for entry in stack:
270
+ body = "\n".join(entry["body_lines"])
271
+ segments.append({
272
+ "type": "markdown",
273
+ "content": f":::{entry['name']}\n{body}",
274
+ })
275
+
276
+ return segments
277
+
278
+
279
+ _MAX_PARSE_DEPTH = 50
280
+
281
+
282
+ def _directive_to_block(name: str, attrs: dict[str, Any], body: str, _depth: int = 0) -> Block:
283
+ """Convert a parsed directive into a Block."""
284
+ block_type = _DIRECTIVE_TO_BLOCK.get(name, BlockType.PANEL)
285
+
286
+ # Tree and Code directives: store raw body, don't parse as markdown
287
+ if block_type in (BlockType.TREE, BlockType.CODE):
288
+ attrs["source"] = body
289
+ return Block(type=block_type, attrs=attrs)
290
+
291
+ # Divider: no children
292
+ if block_type == BlockType.DIVIDER:
293
+ return Block(type=BlockType.DIVIDER, attrs=attrs)
294
+
295
+ # Recursively parse the body through the full two-pass pipeline
296
+ body_doc = parse(body, _depth=_depth + 1)
297
+ return Block(
298
+ type=block_type,
299
+ children=body_doc.children,
300
+ attrs=attrs,
301
+ )
302
+
303
+
304
+ def parse(source: str, _depth: int = 0) -> Block:
305
+ """Parse markdown+directive source into a Block tree.
306
+
307
+ Returns a Block with type=DOCUMENT as root.
308
+ """
309
+ if _depth > _MAX_PARSE_DEPTH:
310
+ raise ValueError(f"Maximum directive nesting depth ({_MAX_PARSE_DEPTH}) exceeded")
311
+ segments = _split_directives(source)
312
+ children: list[Block] = []
313
+
314
+ for seg in segments:
315
+ if seg["type"] == "markdown":
316
+ children.extend(_parse_markdown(seg["content"]))
317
+ else:
318
+ children.append(_directive_to_block(
319
+ seg["name"], seg["attrs"], seg["body"], _depth=_depth,
320
+ ))
321
+
322
+ return Block(type=BlockType.DOCUMENT, children=children)
termrender/py.typed ADDED
File without changes
@@ -0,0 +1 @@
1
+ """Block-type renderers for termrender."""