@code-yeongyu/senpi-tui 2026.7.25-2

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