@lenylvt/pi-tui 0.64.0

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.
Files changed (127) hide show
  1. package/README.md +767 -0
  2. package/dist/autocomplete.d.ts +50 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +623 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +22 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +104 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +35 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +244 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1861 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +28 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +69 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +426 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +21 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +49 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +95 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +660 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +50 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +159 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +50 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +185 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +23 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +89 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +13 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +51 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +39 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fuzzy.d.ts +16 -0
  59. package/dist/fuzzy.d.ts.map +1 -0
  60. package/dist/fuzzy.js +107 -0
  61. package/dist/fuzzy.js.map +1 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +32 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/keybindings.d.ts +193 -0
  67. package/dist/keybindings.d.ts.map +1 -0
  68. package/dist/keybindings.js +174 -0
  69. package/dist/keybindings.js.map +1 -0
  70. package/dist/keys.d.ts +170 -0
  71. package/dist/keys.d.ts.map +1 -0
  72. package/dist/keys.js +1124 -0
  73. package/dist/keys.js.map +1 -0
  74. package/dist/kill-ring.d.ts +28 -0
  75. package/dist/kill-ring.d.ts.map +1 -0
  76. package/dist/kill-ring.js +44 -0
  77. package/dist/kill-ring.js.map +1 -0
  78. package/dist/stdin-buffer.d.ts +48 -0
  79. package/dist/stdin-buffer.d.ts.map +1 -0
  80. package/dist/stdin-buffer.js +317 -0
  81. package/dist/stdin-buffer.js.map +1 -0
  82. package/dist/terminal-image.d.ts +68 -0
  83. package/dist/terminal-image.d.ts.map +1 -0
  84. package/dist/terminal-image.js +288 -0
  85. package/dist/terminal-image.js.map +1 -0
  86. package/dist/terminal.d.ts +84 -0
  87. package/dist/terminal.d.ts.map +1 -0
  88. package/dist/terminal.js +285 -0
  89. package/dist/terminal.js.map +1 -0
  90. package/dist/tui.d.ts +218 -0
  91. package/dist/tui.d.ts.map +1 -0
  92. package/dist/tui.js +966 -0
  93. package/dist/tui.js.map +1 -0
  94. package/dist/undo-stack.d.ts +17 -0
  95. package/dist/undo-stack.d.ts.map +1 -0
  96. package/dist/undo-stack.js +25 -0
  97. package/dist/undo-stack.js.map +1 -0
  98. package/dist/utils.d.ts +78 -0
  99. package/dist/utils.d.ts.map +1 -0
  100. package/dist/utils.js +960 -0
  101. package/dist/utils.js.map +1 -0
  102. package/package.json +55 -0
  103. package/src/autocomplete.ts +771 -0
  104. package/src/components/box.ts +137 -0
  105. package/src/components/cancellable-loader.ts +40 -0
  106. package/src/components/editor.ts +2230 -0
  107. package/src/components/image.ts +104 -0
  108. package/src/components/input.ts +503 -0
  109. package/src/components/loader.ts +55 -0
  110. package/src/components/markdown.ts +820 -0
  111. package/src/components/select-list.ts +229 -0
  112. package/src/components/settings-list.ts +250 -0
  113. package/src/components/spacer.ts +28 -0
  114. package/src/components/text.ts +106 -0
  115. package/src/components/truncated-text.ts +65 -0
  116. package/src/editor-component.ts +74 -0
  117. package/src/fuzzy.ts +133 -0
  118. package/src/index.ts +104 -0
  119. package/src/keybindings.ts +244 -0
  120. package/src/keys.ts +1356 -0
  121. package/src/kill-ring.ts +46 -0
  122. package/src/stdin-buffer.ts +386 -0
  123. package/src/terminal-image.ts +381 -0
  124. package/src/terminal.ts +360 -0
  125. package/src/tui.ts +1200 -0
  126. package/src/undo-stack.ts +28 -0
  127. package/src/utils.ts +1068 -0
@@ -0,0 +1,820 @@
1
+ import { marked, type Token } from "marked";
2
+ import { isImageLine } from "../terminal-image.js";
3
+ import type { Component } from "../tui.js";
4
+ import { applyBackgroundToLine, visibleWidth, wrapTextWithAnsi } from "../utils.js";
5
+
6
+ /**
7
+ * Default text styling for markdown content.
8
+ * Applied to all text unless overridden by markdown formatting.
9
+ */
10
+ export interface DefaultTextStyle {
11
+ /** Foreground color function */
12
+ color?: (text: string) => string;
13
+ /** Background color function */
14
+ bgColor?: (text: string) => string;
15
+ /** Bold text */
16
+ bold?: boolean;
17
+ /** Italic text */
18
+ italic?: boolean;
19
+ /** Strikethrough text */
20
+ strikethrough?: boolean;
21
+ /** Underline text */
22
+ underline?: boolean;
23
+ }
24
+
25
+ /**
26
+ * Theme functions for markdown elements.
27
+ * Each function takes text and returns styled text with ANSI codes.
28
+ */
29
+ export interface MarkdownTheme {
30
+ heading: (text: string) => string;
31
+ link: (text: string) => string;
32
+ linkUrl: (text: string) => string;
33
+ code: (text: string) => string;
34
+ codeBlock: (text: string) => string;
35
+ codeBlockBorder: (text: string) => string;
36
+ quote: (text: string) => string;
37
+ quoteBorder: (text: string) => string;
38
+ hr: (text: string) => string;
39
+ listBullet: (text: string) => string;
40
+ bold: (text: string) => string;
41
+ italic: (text: string) => string;
42
+ strikethrough: (text: string) => string;
43
+ underline: (text: string) => string;
44
+ highlightCode?: (code: string, lang?: string) => string[];
45
+ /** Prefix applied to each rendered code block line (default: " ") */
46
+ codeBlockIndent?: string;
47
+ }
48
+
49
+ interface InlineStyleContext {
50
+ applyText: (text: string) => string;
51
+ stylePrefix: string;
52
+ }
53
+
54
+ export class Markdown implements Component {
55
+ private text: string;
56
+ private paddingX: number; // Left/right padding
57
+ private paddingY: number; // Top/bottom padding
58
+ private defaultTextStyle?: DefaultTextStyle;
59
+ private theme: MarkdownTheme;
60
+ private defaultStylePrefix?: string;
61
+
62
+ // Cache for rendered output
63
+ private cachedText?: string;
64
+ private cachedWidth?: number;
65
+ private cachedLines?: string[];
66
+
67
+ constructor(
68
+ text: string,
69
+ paddingX: number,
70
+ paddingY: number,
71
+ theme: MarkdownTheme,
72
+ defaultTextStyle?: DefaultTextStyle,
73
+ ) {
74
+ this.text = text;
75
+ this.paddingX = paddingX;
76
+ this.paddingY = paddingY;
77
+ this.theme = theme;
78
+ this.defaultTextStyle = defaultTextStyle;
79
+ }
80
+
81
+ setText(text: string): void {
82
+ this.text = text;
83
+ this.invalidate();
84
+ }
85
+
86
+ invalidate(): void {
87
+ this.cachedText = undefined;
88
+ this.cachedWidth = undefined;
89
+ this.cachedLines = undefined;
90
+ }
91
+
92
+ render(width: number): string[] {
93
+ // Check cache
94
+ if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
95
+ return this.cachedLines;
96
+ }
97
+
98
+ // Calculate available width for content (subtract horizontal padding)
99
+ const contentWidth = Math.max(1, width - this.paddingX * 2);
100
+
101
+ // Don't render anything if there's no actual text
102
+ if (!this.text || this.text.trim() === "") {
103
+ const result: string[] = [];
104
+ // Update cache
105
+ this.cachedText = this.text;
106
+ this.cachedWidth = width;
107
+ this.cachedLines = result;
108
+ return result;
109
+ }
110
+
111
+ // Replace tabs with 3 spaces for consistent rendering
112
+ const normalizedText = this.text.replace(/\t/g, " ");
113
+
114
+ // Parse markdown to HTML-like tokens
115
+ const tokens = marked.lexer(normalizedText);
116
+
117
+ // Convert tokens to styled terminal output
118
+ const renderedLines: string[] = [];
119
+
120
+ for (let i = 0; i < tokens.length; i++) {
121
+ const token = tokens[i];
122
+ const nextToken = tokens[i + 1];
123
+ const tokenLines = this.renderToken(token, contentWidth, nextToken?.type);
124
+ renderedLines.push(...tokenLines);
125
+ }
126
+
127
+ // Wrap lines (NO padding, NO background yet)
128
+ const wrappedLines: string[] = [];
129
+ for (const line of renderedLines) {
130
+ if (isImageLine(line)) {
131
+ wrappedLines.push(line);
132
+ } else {
133
+ wrappedLines.push(...wrapTextWithAnsi(line, contentWidth));
134
+ }
135
+ }
136
+
137
+ // Add margins and background to each wrapped line
138
+ const leftMargin = " ".repeat(this.paddingX);
139
+ const rightMargin = " ".repeat(this.paddingX);
140
+ const bgFn = this.defaultTextStyle?.bgColor;
141
+ const contentLines: string[] = [];
142
+
143
+ for (const line of wrappedLines) {
144
+ if (isImageLine(line)) {
145
+ contentLines.push(line);
146
+ continue;
147
+ }
148
+
149
+ const lineWithMargins = leftMargin + line + rightMargin;
150
+
151
+ if (bgFn) {
152
+ contentLines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
153
+ } else {
154
+ // No background - just pad to width
155
+ const visibleLen = visibleWidth(lineWithMargins);
156
+ const paddingNeeded = Math.max(0, width - visibleLen);
157
+ contentLines.push(lineWithMargins + " ".repeat(paddingNeeded));
158
+ }
159
+ }
160
+
161
+ // Add top/bottom padding (empty lines)
162
+ const emptyLine = " ".repeat(width);
163
+ const emptyLines: string[] = [];
164
+ for (let i = 0; i < this.paddingY; i++) {
165
+ const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
166
+ emptyLines.push(line);
167
+ }
168
+
169
+ // Combine top padding, content, and bottom padding
170
+ const result = [...emptyLines, ...contentLines, ...emptyLines];
171
+
172
+ // Update cache
173
+ this.cachedText = this.text;
174
+ this.cachedWidth = width;
175
+ this.cachedLines = result;
176
+
177
+ return result.length > 0 ? result : [""];
178
+ }
179
+
180
+ /**
181
+ * Apply default text style to a string.
182
+ * This is the base styling applied to all text content.
183
+ * NOTE: Background color is NOT applied here - it's applied at the padding stage
184
+ * to ensure it extends to the full line width.
185
+ */
186
+ private applyDefaultStyle(text: string): string {
187
+ if (!this.defaultTextStyle) {
188
+ return text;
189
+ }
190
+
191
+ let styled = text;
192
+
193
+ // Apply foreground color (NOT background - that's applied at padding stage)
194
+ if (this.defaultTextStyle.color) {
195
+ styled = this.defaultTextStyle.color(styled);
196
+ }
197
+
198
+ // Apply text decorations using this.theme
199
+ if (this.defaultTextStyle.bold) {
200
+ styled = this.theme.bold(styled);
201
+ }
202
+ if (this.defaultTextStyle.italic) {
203
+ styled = this.theme.italic(styled);
204
+ }
205
+ if (this.defaultTextStyle.strikethrough) {
206
+ styled = this.theme.strikethrough(styled);
207
+ }
208
+ if (this.defaultTextStyle.underline) {
209
+ styled = this.theme.underline(styled);
210
+ }
211
+
212
+ return styled;
213
+ }
214
+
215
+ private getDefaultStylePrefix(): string {
216
+ if (!this.defaultTextStyle) {
217
+ return "";
218
+ }
219
+
220
+ if (this.defaultStylePrefix !== undefined) {
221
+ return this.defaultStylePrefix;
222
+ }
223
+
224
+ const sentinel = "\u0000";
225
+ let styled = sentinel;
226
+
227
+ if (this.defaultTextStyle.color) {
228
+ styled = this.defaultTextStyle.color(styled);
229
+ }
230
+
231
+ if (this.defaultTextStyle.bold) {
232
+ styled = this.theme.bold(styled);
233
+ }
234
+ if (this.defaultTextStyle.italic) {
235
+ styled = this.theme.italic(styled);
236
+ }
237
+ if (this.defaultTextStyle.strikethrough) {
238
+ styled = this.theme.strikethrough(styled);
239
+ }
240
+ if (this.defaultTextStyle.underline) {
241
+ styled = this.theme.underline(styled);
242
+ }
243
+
244
+ const sentinelIndex = styled.indexOf(sentinel);
245
+ this.defaultStylePrefix = sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
246
+ return this.defaultStylePrefix;
247
+ }
248
+
249
+ private getStylePrefix(styleFn: (text: string) => string): string {
250
+ const sentinel = "\u0000";
251
+ const styled = styleFn(sentinel);
252
+ const sentinelIndex = styled.indexOf(sentinel);
253
+ return sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
254
+ }
255
+
256
+ private getDefaultInlineStyleContext(): InlineStyleContext {
257
+ return {
258
+ applyText: (text: string) => this.applyDefaultStyle(text),
259
+ stylePrefix: this.getDefaultStylePrefix(),
260
+ };
261
+ }
262
+
263
+ private renderToken(
264
+ token: Token,
265
+ width: number,
266
+ nextTokenType?: string,
267
+ styleContext?: InlineStyleContext,
268
+ ): string[] {
269
+ const lines: string[] = [];
270
+
271
+ switch (token.type) {
272
+ case "heading": {
273
+ const headingLevel = token.depth;
274
+ const headingPrefix = `${"#".repeat(headingLevel)} `;
275
+
276
+ // Build a heading-specific style context so inline tokens (codespan, bold, etc.)
277
+ // restore heading styling after their own ANSI resets instead of falling back to
278
+ // the default text style.
279
+ let headingStyleFn: (text: string) => string;
280
+ if (headingLevel === 1) {
281
+ headingStyleFn = (text: string) => this.theme.heading(this.theme.bold(this.theme.underline(text)));
282
+ } else {
283
+ headingStyleFn = (text: string) => this.theme.heading(this.theme.bold(text));
284
+ }
285
+
286
+ const headingStyleContext: InlineStyleContext = {
287
+ applyText: headingStyleFn,
288
+ stylePrefix: this.getStylePrefix(headingStyleFn),
289
+ };
290
+
291
+ const headingText = this.renderInlineTokens(token.tokens || [], headingStyleContext);
292
+ const styledHeading = headingLevel >= 3 ? headingStyleFn(headingPrefix) + headingText : headingText;
293
+ lines.push(styledHeading);
294
+ if (nextTokenType && nextTokenType !== "space") {
295
+ lines.push(""); // Add spacing after headings (unless space token follows)
296
+ }
297
+ break;
298
+ }
299
+
300
+ case "paragraph": {
301
+ const paragraphText = this.renderInlineTokens(token.tokens || [], styleContext);
302
+ lines.push(paragraphText);
303
+ // Don't add spacing if next token is space or list
304
+ if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") {
305
+ lines.push("");
306
+ }
307
+ break;
308
+ }
309
+
310
+ case "code": {
311
+ const indent = this.theme.codeBlockIndent ?? " ";
312
+ lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
313
+ if (this.theme.highlightCode) {
314
+ const highlightedLines = this.theme.highlightCode(token.text, token.lang);
315
+ for (const hlLine of highlightedLines) {
316
+ lines.push(`${indent}${hlLine}`);
317
+ }
318
+ } else {
319
+ // Split code by newlines and style each line
320
+ const codeLines = token.text.split("\n");
321
+ for (const codeLine of codeLines) {
322
+ lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
323
+ }
324
+ }
325
+ lines.push(this.theme.codeBlockBorder("```"));
326
+ if (nextTokenType && nextTokenType !== "space") {
327
+ lines.push(""); // Add spacing after code blocks (unless space token follows)
328
+ }
329
+ break;
330
+ }
331
+
332
+ case "list": {
333
+ const listLines = this.renderList(token as any, 0, styleContext);
334
+ lines.push(...listLines);
335
+ // Don't add spacing after lists if a space token follows
336
+ // (the space token will handle it)
337
+ break;
338
+ }
339
+
340
+ case "table": {
341
+ const tableLines = this.renderTable(token as any, width, nextTokenType, styleContext);
342
+ lines.push(...tableLines);
343
+ break;
344
+ }
345
+
346
+ case "blockquote": {
347
+ const quoteStyle = (text: string) => this.theme.quote(this.theme.italic(text));
348
+ const quoteStylePrefix = this.getStylePrefix(quoteStyle);
349
+ const applyQuoteStyle = (line: string): string => {
350
+ if (!quoteStylePrefix) {
351
+ return quoteStyle(line);
352
+ }
353
+ const lineWithReappliedStyle = line.replace(/\x1b\[0m/g, `\x1b[0m${quoteStylePrefix}`);
354
+ return quoteStyle(lineWithReappliedStyle);
355
+ };
356
+
357
+ // Calculate available width for quote content (subtract border "│ " = 2 chars)
358
+ const quoteContentWidth = Math.max(1, width - 2);
359
+
360
+ // Blockquotes contain block-level tokens (paragraph, list, code, etc.), so render
361
+ // children with renderToken() instead of renderInlineTokens().
362
+ // Default message style should not apply inside blockquotes.
363
+ const quoteInlineStyleContext: InlineStyleContext = {
364
+ applyText: (text: string) => text,
365
+ stylePrefix: quoteStylePrefix,
366
+ };
367
+ const quoteTokens = token.tokens || [];
368
+ const renderedQuoteLines: string[] = [];
369
+ for (let i = 0; i < quoteTokens.length; i++) {
370
+ const quoteToken = quoteTokens[i];
371
+ const nextQuoteToken = quoteTokens[i + 1];
372
+ renderedQuoteLines.push(
373
+ ...this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext),
374
+ );
375
+ }
376
+
377
+ // Avoid rendering an extra empty quote line before the outer blockquote spacing.
378
+ while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") {
379
+ renderedQuoteLines.pop();
380
+ }
381
+
382
+ for (const quoteLine of renderedQuoteLines) {
383
+ const styledLine = applyQuoteStyle(quoteLine);
384
+ const wrappedLines = wrapTextWithAnsi(styledLine, quoteContentWidth);
385
+ for (const wrappedLine of wrappedLines) {
386
+ lines.push(this.theme.quoteBorder("│ ") + wrappedLine);
387
+ }
388
+ }
389
+ if (nextTokenType && nextTokenType !== "space") {
390
+ lines.push(""); // Add spacing after blockquotes (unless space token follows)
391
+ }
392
+ break;
393
+ }
394
+
395
+ case "hr":
396
+ lines.push(this.theme.hr("─".repeat(Math.min(width, 80))));
397
+ if (nextTokenType && nextTokenType !== "space") {
398
+ lines.push(""); // Add spacing after horizontal rules (unless space token follows)
399
+ }
400
+ break;
401
+
402
+ case "html":
403
+ // Render HTML as plain text (escaped for terminal)
404
+ if ("raw" in token && typeof token.raw === "string") {
405
+ lines.push(this.applyDefaultStyle(token.raw.trim()));
406
+ }
407
+ break;
408
+
409
+ case "space":
410
+ // Space tokens represent blank lines in markdown
411
+ lines.push("");
412
+ break;
413
+
414
+ default:
415
+ // Handle any other token types as plain text
416
+ if ("text" in token && typeof token.text === "string") {
417
+ lines.push(token.text);
418
+ }
419
+ }
420
+
421
+ return lines;
422
+ }
423
+
424
+ private renderInlineTokens(tokens: Token[], styleContext?: InlineStyleContext): string {
425
+ let result = "";
426
+ const resolvedStyleContext = styleContext ?? this.getDefaultInlineStyleContext();
427
+ const { applyText, stylePrefix } = resolvedStyleContext;
428
+ const applyTextWithNewlines = (text: string): string => {
429
+ const segments: string[] = text.split("\n");
430
+ return segments.map((segment: string) => applyText(segment)).join("\n");
431
+ };
432
+
433
+ for (const token of tokens) {
434
+ switch (token.type) {
435
+ case "text":
436
+ // Text tokens in list items can have nested tokens for inline formatting
437
+ if (token.tokens && token.tokens.length > 0) {
438
+ result += this.renderInlineTokens(token.tokens, resolvedStyleContext);
439
+ } else {
440
+ result += applyTextWithNewlines(token.text);
441
+ }
442
+ break;
443
+
444
+ case "paragraph":
445
+ // Paragraph tokens contain nested inline tokens
446
+ result += this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
447
+ break;
448
+
449
+ case "strong": {
450
+ const boldContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
451
+ result += this.theme.bold(boldContent) + stylePrefix;
452
+ break;
453
+ }
454
+
455
+ case "em": {
456
+ const italicContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
457
+ result += this.theme.italic(italicContent) + stylePrefix;
458
+ break;
459
+ }
460
+
461
+ case "codespan":
462
+ result += this.theme.code(token.text) + stylePrefix;
463
+ break;
464
+
465
+ case "link": {
466
+ const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
467
+ // If link text matches href, only show the link once
468
+ // Compare raw text (token.text) not styled text (linkText) since linkText has ANSI codes
469
+ // For mailto: links, strip the prefix before comparing (autolinked emails have
470
+ // text="foo@bar.com" but href="mailto:foo@bar.com")
471
+ const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href;
472
+ if (token.text === token.href || token.text === hrefForComparison) {
473
+ result += this.theme.link(this.theme.underline(linkText)) + stylePrefix;
474
+ } else {
475
+ result +=
476
+ this.theme.link(this.theme.underline(linkText)) +
477
+ this.theme.linkUrl(` (${token.href})`) +
478
+ stylePrefix;
479
+ }
480
+ break;
481
+ }
482
+
483
+ case "br":
484
+ result += "\n";
485
+ break;
486
+
487
+ case "del": {
488
+ const delContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
489
+ result += this.theme.strikethrough(delContent) + stylePrefix;
490
+ break;
491
+ }
492
+
493
+ case "html":
494
+ // Render inline HTML as plain text
495
+ if ("raw" in token && typeof token.raw === "string") {
496
+ result += applyTextWithNewlines(token.raw);
497
+ }
498
+ break;
499
+
500
+ default:
501
+ // Handle any other inline token types as plain text
502
+ if ("text" in token && typeof token.text === "string") {
503
+ result += applyTextWithNewlines(token.text);
504
+ }
505
+ }
506
+ }
507
+
508
+ return result;
509
+ }
510
+
511
+ /**
512
+ * Render a list with proper nesting support
513
+ */
514
+ private renderList(
515
+ token: Token & { items: any[]; ordered: boolean; start?: number },
516
+ depth: number,
517
+ styleContext?: InlineStyleContext,
518
+ ): string[] {
519
+ const lines: string[] = [];
520
+ const indent = " ".repeat(depth);
521
+ // Use the list's start property (defaults to 1 for ordered lists)
522
+ const startNumber = token.start ?? 1;
523
+
524
+ for (let i = 0; i < token.items.length; i++) {
525
+ const item = token.items[i];
526
+ const bullet = token.ordered ? `${startNumber + i}. ` : "- ";
527
+
528
+ // Process item tokens to handle nested lists
529
+ const itemLines = this.renderListItem(item.tokens || [], depth, styleContext);
530
+
531
+ if (itemLines.length > 0) {
532
+ // First line - check if it's a nested list
533
+ // A nested list will start with indent (spaces) followed by cyan bullet
534
+ const firstLine = itemLines[0];
535
+ const isNestedList = /^\s+\x1b\[36m[-\d]/.test(firstLine); // starts with spaces + cyan + bullet char
536
+
537
+ if (isNestedList) {
538
+ // This is a nested list, just add it as-is (already has full indent)
539
+ lines.push(firstLine);
540
+ } else {
541
+ // Regular text content - add indent and bullet
542
+ lines.push(indent + this.theme.listBullet(bullet) + firstLine);
543
+ }
544
+
545
+ // Rest of the lines
546
+ for (let j = 1; j < itemLines.length; j++) {
547
+ const line = itemLines[j];
548
+ const isNestedListLine = /^\s+\x1b\[36m[-\d]/.test(line); // starts with spaces + cyan + bullet char
549
+
550
+ if (isNestedListLine) {
551
+ // Nested list line - already has full indent
552
+ lines.push(line);
553
+ } else {
554
+ // Regular content - add parent indent + 2 spaces for continuation
555
+ lines.push(`${indent} ${line}`);
556
+ }
557
+ }
558
+ } else {
559
+ lines.push(indent + this.theme.listBullet(bullet));
560
+ }
561
+ }
562
+
563
+ return lines;
564
+ }
565
+
566
+ /**
567
+ * Render list item tokens, handling nested lists
568
+ * Returns lines WITHOUT the parent indent (renderList will add it)
569
+ */
570
+ private renderListItem(tokens: Token[], parentDepth: number, styleContext?: InlineStyleContext): string[] {
571
+ const lines: string[] = [];
572
+
573
+ for (const token of tokens) {
574
+ if (token.type === "list") {
575
+ // Nested list - render with one additional indent level
576
+ // These lines will have their own indent, so we just add them as-is
577
+ const nestedLines = this.renderList(token as any, parentDepth + 1, styleContext);
578
+ lines.push(...nestedLines);
579
+ } else if (token.type === "text") {
580
+ // Text content (may have inline tokens)
581
+ const text =
582
+ token.tokens && token.tokens.length > 0
583
+ ? this.renderInlineTokens(token.tokens, styleContext)
584
+ : token.text || "";
585
+ lines.push(text);
586
+ } else if (token.type === "paragraph") {
587
+ // Paragraph in list item
588
+ const text = this.renderInlineTokens(token.tokens || [], styleContext);
589
+ lines.push(text);
590
+ } else if (token.type === "code") {
591
+ // Code block in list item
592
+ const indent = this.theme.codeBlockIndent ?? " ";
593
+ lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
594
+ if (this.theme.highlightCode) {
595
+ const highlightedLines = this.theme.highlightCode(token.text, token.lang);
596
+ for (const hlLine of highlightedLines) {
597
+ lines.push(`${indent}${hlLine}`);
598
+ }
599
+ } else {
600
+ const codeLines = token.text.split("\n");
601
+ for (const codeLine of codeLines) {
602
+ lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
603
+ }
604
+ }
605
+ lines.push(this.theme.codeBlockBorder("```"));
606
+ } else {
607
+ // Other token types - try to render as inline
608
+ const text = this.renderInlineTokens([token], styleContext);
609
+ if (text) {
610
+ lines.push(text);
611
+ }
612
+ }
613
+ }
614
+
615
+ return lines;
616
+ }
617
+
618
+ /**
619
+ * Get the visible width of the longest word in a string.
620
+ */
621
+ private getLongestWordWidth(text: string, maxWidth?: number): number {
622
+ const words = text.split(/\s+/).filter((word) => word.length > 0);
623
+ let longest = 0;
624
+ for (const word of words) {
625
+ longest = Math.max(longest, visibleWidth(word));
626
+ }
627
+ if (maxWidth === undefined) {
628
+ return longest;
629
+ }
630
+ return Math.min(longest, maxWidth);
631
+ }
632
+
633
+ /**
634
+ * Wrap a table cell to fit into a column.
635
+ *
636
+ * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled
637
+ * consistently with the rest of the renderer.
638
+ */
639
+ private wrapCellText(text: string, maxWidth: number): string[] {
640
+ return wrapTextWithAnsi(text, Math.max(1, maxWidth));
641
+ }
642
+
643
+ /**
644
+ * Render a table with width-aware cell wrapping.
645
+ * Cells that don't fit are wrapped to multiple lines.
646
+ */
647
+ private renderTable(
648
+ token: Token & { header: any[]; rows: any[][]; raw?: string },
649
+ availableWidth: number,
650
+ nextTokenType?: string,
651
+ styleContext?: InlineStyleContext,
652
+ ): string[] {
653
+ const lines: string[] = [];
654
+ const numCols = token.header.length;
655
+
656
+ if (numCols === 0) {
657
+ return lines;
658
+ }
659
+
660
+ // Calculate border overhead: "│ " + (n-1) * " │ " + " │"
661
+ // = 2 + (n-1) * 3 + 2 = 3n + 1
662
+ const borderOverhead = 3 * numCols + 1;
663
+ const availableForCells = availableWidth - borderOverhead;
664
+ if (availableForCells < numCols) {
665
+ // Too narrow to render a stable table. Fall back to raw markdown.
666
+ const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
667
+ if (nextTokenType && nextTokenType !== "space") {
668
+ fallbackLines.push("");
669
+ }
670
+ return fallbackLines;
671
+ }
672
+
673
+ const maxUnbrokenWordWidth = 30;
674
+
675
+ // Calculate natural column widths (what each column needs without constraints)
676
+ const naturalWidths: number[] = [];
677
+ const minWordWidths: number[] = [];
678
+ for (let i = 0; i < numCols; i++) {
679
+ const headerText = this.renderInlineTokens(token.header[i].tokens || [], styleContext);
680
+ naturalWidths[i] = visibleWidth(headerText);
681
+ minWordWidths[i] = Math.max(1, this.getLongestWordWidth(headerText, maxUnbrokenWordWidth));
682
+ }
683
+ for (const row of token.rows) {
684
+ for (let i = 0; i < row.length; i++) {
685
+ const cellText = this.renderInlineTokens(row[i].tokens || [], styleContext);
686
+ naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
687
+ minWordWidths[i] = Math.max(
688
+ minWordWidths[i] || 1,
689
+ this.getLongestWordWidth(cellText, maxUnbrokenWordWidth),
690
+ );
691
+ }
692
+ }
693
+
694
+ let minColumnWidths = minWordWidths;
695
+ let minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
696
+
697
+ if (minCellsWidth > availableForCells) {
698
+ minColumnWidths = new Array(numCols).fill(1);
699
+ const remaining = availableForCells - numCols;
700
+
701
+ if (remaining > 0) {
702
+ const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
703
+ const growth = minWordWidths.map((width) => {
704
+ const weight = Math.max(0, width - 1);
705
+ return totalWeight > 0 ? Math.floor((weight / totalWeight) * remaining) : 0;
706
+ });
707
+
708
+ for (let i = 0; i < numCols; i++) {
709
+ minColumnWidths[i] += growth[i] ?? 0;
710
+ }
711
+
712
+ const allocated = growth.reduce((total, width) => total + width, 0);
713
+ let leftover = remaining - allocated;
714
+ for (let i = 0; leftover > 0 && i < numCols; i++) {
715
+ minColumnWidths[i]++;
716
+ leftover--;
717
+ }
718
+ }
719
+
720
+ minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
721
+ }
722
+
723
+ // Calculate column widths that fit within available width
724
+ const totalNaturalWidth = naturalWidths.reduce((a, b) => a + b, 0) + borderOverhead;
725
+ let columnWidths: number[];
726
+
727
+ if (totalNaturalWidth <= availableWidth) {
728
+ // Everything fits naturally
729
+ columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
730
+ } else {
731
+ // Need to shrink columns to fit
732
+ const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
733
+ return total + Math.max(0, width - minColumnWidths[index]);
734
+ }, 0);
735
+ const extraWidth = Math.max(0, availableForCells - minCellsWidth);
736
+ columnWidths = minColumnWidths.map((minWidth, index) => {
737
+ const naturalWidth = naturalWidths[index];
738
+ const minWidthDelta = Math.max(0, naturalWidth - minWidth);
739
+ let grow = 0;
740
+ if (totalGrowPotential > 0) {
741
+ grow = Math.floor((minWidthDelta / totalGrowPotential) * extraWidth);
742
+ }
743
+ return minWidth + grow;
744
+ });
745
+
746
+ // Adjust for rounding errors - distribute remaining space
747
+ const allocated = columnWidths.reduce((a, b) => a + b, 0);
748
+ let remaining = availableForCells - allocated;
749
+ while (remaining > 0) {
750
+ let grew = false;
751
+ for (let i = 0; i < numCols && remaining > 0; i++) {
752
+ if (columnWidths[i] < naturalWidths[i]) {
753
+ columnWidths[i]++;
754
+ remaining--;
755
+ grew = true;
756
+ }
757
+ }
758
+ if (!grew) {
759
+ break;
760
+ }
761
+ }
762
+ }
763
+
764
+ // Render top border
765
+ const topBorderCells = columnWidths.map((w) => "─".repeat(w));
766
+ lines.push(`┌─${topBorderCells.join("─┬─")}─┐`);
767
+
768
+ // Render header with wrapping
769
+ const headerCellLines: string[][] = token.header.map((cell, i) => {
770
+ const text = this.renderInlineTokens(cell.tokens || [], styleContext);
771
+ return this.wrapCellText(text, columnWidths[i]);
772
+ });
773
+ const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
774
+
775
+ for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
776
+ const rowParts = headerCellLines.map((cellLines, colIdx) => {
777
+ const text = cellLines[lineIdx] || "";
778
+ const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
779
+ return this.theme.bold(padded);
780
+ });
781
+ lines.push(`│ ${rowParts.join(" │ ")} │`);
782
+ }
783
+
784
+ // Render separator
785
+ const separatorCells = columnWidths.map((w) => "─".repeat(w));
786
+ const separatorLine = `├─${separatorCells.join("─┼─")}─┤`;
787
+ lines.push(separatorLine);
788
+
789
+ // Render rows with wrapping
790
+ for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
791
+ const row = token.rows[rowIndex];
792
+ const rowCellLines: string[][] = row.map((cell, i) => {
793
+ const text = this.renderInlineTokens(cell.tokens || [], styleContext);
794
+ return this.wrapCellText(text, columnWidths[i]);
795
+ });
796
+ const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
797
+
798
+ for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
799
+ const rowParts = rowCellLines.map((cellLines, colIdx) => {
800
+ const text = cellLines[lineIdx] || "";
801
+ return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
802
+ });
803
+ lines.push(`│ ${rowParts.join(" │ ")} │`);
804
+ }
805
+
806
+ if (rowIndex < token.rows.length - 1) {
807
+ lines.push(separatorLine);
808
+ }
809
+ }
810
+
811
+ // Render bottom border
812
+ const bottomBorderCells = columnWidths.map((w) => "─".repeat(w));
813
+ lines.push(`└─${bottomBorderCells.join("─┴─")}─┘`);
814
+
815
+ if (nextTokenType && nextTokenType !== "space") {
816
+ lines.push(""); // Add spacing after table
817
+ }
818
+ return lines;
819
+ }
820
+ }