@bastani/atomic-tui 0.0.0-stage → 0.9.88

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 (214) hide show
  1. package/LICENSE +22 -0
  2. package/NOTICE.md +13 -0
  3. package/README.md +76 -2
  4. package/dist/alt-screen-search.d.ts +46 -0
  5. package/dist/alt-screen-search.d.ts.map +1 -0
  6. package/dist/alt-screen-search.js +282 -0
  7. package/dist/alt-screen-search.js.map +1 -0
  8. package/dist/autocomplete.d.ts +57 -0
  9. package/dist/autocomplete.d.ts.map +1 -0
  10. package/dist/autocomplete.js +690 -0
  11. package/dist/autocomplete.js.map +1 -0
  12. package/dist/colors.d.ts +73 -0
  13. package/dist/colors.d.ts.map +1 -0
  14. package/dist/colors.js +273 -0
  15. package/dist/colors.js.map +1 -0
  16. package/dist/components/alt-screen-flash.d.ts +13 -0
  17. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  18. package/dist/components/alt-screen-flash.js +37 -0
  19. package/dist/components/alt-screen-flash.js.map +1 -0
  20. package/dist/components/box.d.ts +25 -0
  21. package/dist/components/box.d.ts.map +1 -0
  22. package/dist/components/box.js +138 -0
  23. package/dist/components/box.js.map +1 -0
  24. package/dist/components/cancellable-loader.d.ts +22 -0
  25. package/dist/components/cancellable-loader.d.ts.map +1 -0
  26. package/dist/components/cancellable-loader.js +35 -0
  27. package/dist/components/cancellable-loader.js.map +1 -0
  28. package/dist/components/editor.d.ts +274 -0
  29. package/dist/components/editor.d.ts.map +1 -0
  30. package/dist/components/editor.js +2074 -0
  31. package/dist/components/editor.js.map +1 -0
  32. package/dist/components/h-stack.d.ts +7 -0
  33. package/dist/components/h-stack.d.ts.map +1 -0
  34. package/dist/components/h-stack.js +43 -0
  35. package/dist/components/h-stack.js.map +1 -0
  36. package/dist/components/image.d.ts +40 -0
  37. package/dist/components/image.d.ts.map +1 -0
  38. package/dist/components/image.js +123 -0
  39. package/dist/components/image.js.map +1 -0
  40. package/dist/components/input.d.ts +50 -0
  41. package/dist/components/input.d.ts.map +1 -0
  42. package/dist/components/input.js +421 -0
  43. package/dist/components/input.js.map +1 -0
  44. package/dist/components/loader.d.ts +33 -0
  45. package/dist/components/loader.d.ts.map +1 -0
  46. package/dist/components/loader.js +76 -0
  47. package/dist/components/loader.js.map +1 -0
  48. package/dist/components/markdown.d.ts +110 -0
  49. package/dist/components/markdown.d.ts.map +1 -0
  50. package/dist/components/markdown.js +939 -0
  51. package/dist/components/markdown.js.map +1 -0
  52. package/dist/components/mouse-region.d.ts +12 -0
  53. package/dist/components/mouse-region.d.ts.map +1 -0
  54. package/dist/components/mouse-region.js +21 -0
  55. package/dist/components/mouse-region.js.map +1 -0
  56. package/dist/components/scroll-view.d.ts +59 -0
  57. package/dist/components/scroll-view.d.ts.map +1 -0
  58. package/dist/components/scroll-view.js +195 -0
  59. package/dist/components/scroll-view.js.map +1 -0
  60. package/dist/components/select-list.d.ts +54 -0
  61. package/dist/components/select-list.d.ts.map +1 -0
  62. package/dist/components/select-list.js +215 -0
  63. package/dist/components/select-list.js.map +1 -0
  64. package/dist/components/settings-list.d.ts +61 -0
  65. package/dist/components/settings-list.d.ts.map +1 -0
  66. package/dist/components/settings-list.js +259 -0
  67. package/dist/components/settings-list.js.map +1 -0
  68. package/dist/components/spacer.d.ts +12 -0
  69. package/dist/components/spacer.d.ts.map +1 -0
  70. package/dist/components/spacer.js +23 -0
  71. package/dist/components/spacer.js.map +1 -0
  72. package/dist/components/stack.d.ts +32 -0
  73. package/dist/components/stack.d.ts.map +1 -0
  74. package/dist/components/stack.js +111 -0
  75. package/dist/components/stack.js.map +1 -0
  76. package/dist/components/text.d.ts +20 -0
  77. package/dist/components/text.d.ts.map +1 -0
  78. package/dist/components/text.js +98 -0
  79. package/dist/components/text.js.map +1 -0
  80. package/dist/components/truncated-text.d.ts +13 -0
  81. package/dist/components/truncated-text.d.ts.map +1 -0
  82. package/dist/components/truncated-text.js +51 -0
  83. package/dist/components/truncated-text.js.map +1 -0
  84. package/dist/components/v-stack.d.ts +8 -0
  85. package/dist/components/v-stack.d.ts.map +1 -0
  86. package/dist/components/v-stack.js +26 -0
  87. package/dist/components/v-stack.js.map +1 -0
  88. package/dist/editor-component.d.ts +39 -0
  89. package/dist/editor-component.d.ts.map +1 -0
  90. package/dist/editor-component.js +2 -0
  91. package/dist/editor-component.js.map +1 -0
  92. package/dist/env.d.ts +5 -0
  93. package/dist/env.d.ts.map +1 -0
  94. package/dist/env.js +7 -0
  95. package/dist/env.js.map +1 -0
  96. package/dist/fuzzy.d.ts +16 -0
  97. package/dist/fuzzy.d.ts.map +1 -0
  98. package/dist/fuzzy.js +126 -0
  99. package/dist/fuzzy.js.map +1 -0
  100. package/dist/index.d.ts +38 -0
  101. package/dist/index.d.ts.map +1 -0
  102. package/dist/index.js +51 -0
  103. package/dist/index.js.map +1 -0
  104. package/dist/keybindings.d.ts +279 -0
  105. package/dist/keybindings.d.ts.map +1 -0
  106. package/dist/keybindings.js +248 -0
  107. package/dist/keybindings.js.map +1 -0
  108. package/dist/keys.d.ts +184 -0
  109. package/dist/keys.d.ts.map +1 -0
  110. package/dist/keys.js +1260 -0
  111. package/dist/keys.js.map +1 -0
  112. package/dist/kill-ring.d.ts +28 -0
  113. package/dist/kill-ring.d.ts.map +1 -0
  114. package/dist/kill-ring.js +44 -0
  115. package/dist/kill-ring.js.map +1 -0
  116. package/dist/latex.d.ts +10 -0
  117. package/dist/latex.d.ts.map +1 -0
  118. package/dist/latex.js +1402 -0
  119. package/dist/latex.js.map +1 -0
  120. package/dist/layout-node.d.ts +40 -0
  121. package/dist/layout-node.d.ts.map +1 -0
  122. package/dist/layout-node.js +6 -0
  123. package/dist/layout-node.js.map +1 -0
  124. package/dist/layout.d.ts +42 -0
  125. package/dist/layout.d.ts.map +1 -0
  126. package/dist/layout.js +349 -0
  127. package/dist/layout.js.map +1 -0
  128. package/dist/native-modifiers.d.ts +4 -0
  129. package/dist/native-modifiers.d.ts.map +1 -0
  130. package/dist/native-modifiers.js +13 -0
  131. package/dist/native-modifiers.js.map +1 -0
  132. package/dist/native-module-path.d.ts +7 -0
  133. package/dist/native-module-path.d.ts.map +1 -0
  134. package/dist/native-module-path.js +19 -0
  135. package/dist/native-module-path.js.map +1 -0
  136. package/dist/native-platform.d.ts +20 -0
  137. package/dist/native-platform.d.ts.map +1 -0
  138. package/dist/native-platform.js +42 -0
  139. package/dist/native-platform.js.map +1 -0
  140. package/dist/oklab.d.ts +43 -0
  141. package/dist/oklab.d.ts.map +1 -0
  142. package/dist/oklab.js +210 -0
  143. package/dist/oklab.js.map +1 -0
  144. package/dist/paste.d.ts +2 -0
  145. package/dist/paste.d.ts.map +1 -0
  146. package/dist/paste.js +16 -0
  147. package/dist/paste.js.map +1 -0
  148. package/dist/program-status.d.ts +23 -0
  149. package/dist/program-status.d.ts.map +1 -0
  150. package/dist/program-status.js +43 -0
  151. package/dist/program-status.js.map +1 -0
  152. package/dist/stdin-buffer.d.ts +58 -0
  153. package/dist/stdin-buffer.d.ts.map +1 -0
  154. package/dist/stdin-buffer.js +401 -0
  155. package/dist/stdin-buffer.js.map +1 -0
  156. package/dist/terminal-colors.d.ts +27 -0
  157. package/dist/terminal-colors.d.ts.map +1 -0
  158. package/dist/terminal-colors.js +64 -0
  159. package/dist/terminal-colors.js.map +1 -0
  160. package/dist/terminal-image.d.ts +125 -0
  161. package/dist/terminal-image.d.ts.map +1 -0
  162. package/dist/terminal-image.js +624 -0
  163. package/dist/terminal-image.js.map +1 -0
  164. package/dist/terminal.d.ts +149 -0
  165. package/dist/terminal.d.ts.map +1 -0
  166. package/dist/terminal.js +519 -0
  167. package/dist/terminal.js.map +1 -0
  168. package/dist/tui-alt-screen.d.ts +179 -0
  169. package/dist/tui-alt-screen.d.ts.map +1 -0
  170. package/dist/tui-alt-screen.js +1616 -0
  171. package/dist/tui-alt-screen.js.map +1 -0
  172. package/dist/tui-main-screen.d.ts +39 -0
  173. package/dist/tui-main-screen.d.ts.map +1 -0
  174. package/dist/tui-main-screen.js +599 -0
  175. package/dist/tui-main-screen.js.map +1 -0
  176. package/dist/tui.d.ts +412 -0
  177. package/dist/tui.d.ts.map +1 -0
  178. package/dist/tui.js +1123 -0
  179. package/dist/tui.js.map +1 -0
  180. package/dist/undo-stack.d.ts +17 -0
  181. package/dist/undo-stack.d.ts.map +1 -0
  182. package/dist/undo-stack.js +25 -0
  183. package/dist/undo-stack.js.map +1 -0
  184. package/dist/utils.d.ts +115 -0
  185. package/dist/utils.d.ts.map +1 -0
  186. package/dist/utils.js +1325 -0
  187. package/dist/utils.js.map +1 -0
  188. package/dist/wheel-scroll.d.ts +23 -0
  189. package/dist/wheel-scroll.d.ts.map +1 -0
  190. package/dist/wheel-scroll.js +73 -0
  191. package/dist/wheel-scroll.js.map +1 -0
  192. package/dist/word-navigation.d.ts +25 -0
  193. package/dist/word-navigation.d.ts.map +1 -0
  194. package/dist/word-navigation.js +96 -0
  195. package/dist/word-navigation.js.map +1 -0
  196. package/native/clipboard.h +208 -0
  197. package/native/darwin/README.md +22 -0
  198. package/native/darwin/build.sh +69 -0
  199. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  200. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  201. package/native/darwin/src/darwin-platform.m +132 -0
  202. package/native/linux/README.md +23 -0
  203. package/native/linux/build.sh +65 -0
  204. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  205. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  206. package/native/linux/src/clipboard-worker.h +70 -0
  207. package/native/linux/src/linux-platform-x11.c +274 -0
  208. package/native/napi.h +91 -0
  209. package/native/win32/README.md +31 -0
  210. package/native/win32/build.mjs +232 -0
  211. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  212. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  213. package/native/win32/src/win32-platform.c +241 -0
  214. package/package.json +74 -4
@@ -0,0 +1,939 @@
1
+ import { Marked, Tokenizer } from "marked";
2
+ import markedCjkFriendly from "marked-cjk-friendly";
3
+ import { renderLatex } from "../latex.js";
4
+ import { getCapabilities, hyperlink, isImageLine } from "../terminal-image.js";
5
+ import { applyBackgroundToLine, cjkPunctuationRegex, flattenLines, visibleWidth, wrapTextWithAnsi } from "../utils.js";
6
+ const STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
7
+ class MarkdownTokenizer extends Tokenizer {
8
+ url(src) {
9
+ const token = super.url(src);
10
+ if (!token)
11
+ return undefined;
12
+ // Bare URLs stop at CJK punctuation; explicit links and angle autolinks
13
+ // use separate tokenizers and can still contain these characters.
14
+ const punctuationIndex = token.raw.search(cjkPunctuationRegex);
15
+ return punctuationIndex < 0 ? token : super.url(token.raw.slice(0, punctuationIndex));
16
+ }
17
+ del(src) {
18
+ const match = STRICT_STRIKETHROUGH_REGEX.exec(src);
19
+ if (!match) {
20
+ return undefined;
21
+ }
22
+ const text = match[2];
23
+ return {
24
+ type: "del",
25
+ raw: match[0],
26
+ text,
27
+ tokens: this.lexer.inlineTokens(text),
28
+ };
29
+ }
30
+ }
31
+ function isEscaped(source, index) {
32
+ let backslashes = 0;
33
+ for (let position = index - 1; position >= 0 && source[position] === "\\"; position--) {
34
+ backslashes++;
35
+ }
36
+ return backslashes % 2 === 1;
37
+ }
38
+ function findClosingDelimiter(source, closing, start) {
39
+ let index = source.indexOf(closing, start);
40
+ while (index >= 0 && isEscaped(source, index)) {
41
+ index = source.indexOf(closing, index + closing.length);
42
+ }
43
+ return index;
44
+ }
45
+ function looksLikePendingDollarMath(source) {
46
+ return /\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source);
47
+ }
48
+ function tokenizeInlineLatex(source) {
49
+ let opening = "";
50
+ let closing = "";
51
+ if (source.startsWith("$$")) {
52
+ opening = "$$";
53
+ closing = "$$";
54
+ }
55
+ else if (source.startsWith("\\(")) {
56
+ opening = "\\(";
57
+ closing = "\\)";
58
+ }
59
+ else if (source.startsWith("\\[")) {
60
+ opening = "\\[";
61
+ closing = "\\]";
62
+ }
63
+ else if (source.startsWith("$") && !/^\$\s/.test(source)) {
64
+ opening = "$";
65
+ closing = "$";
66
+ }
67
+ else {
68
+ return undefined;
69
+ }
70
+ const closingIndex = findClosingDelimiter(source, closing, opening.length);
71
+ if (closingIndex >= 0 &&
72
+ opening === "$" &&
73
+ (/\s$/.test(source.slice(opening.length, closingIndex)) ||
74
+ /^\d/.test(source.slice(closingIndex + 1)) ||
75
+ (/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source.slice(opening.length, closingIndex)) &&
76
+ /^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex + 1))) ||
77
+ source.slice(opening.length, closingIndex).includes("`"))) {
78
+ return undefined;
79
+ }
80
+ if (closingIndex < 0) {
81
+ const pendingSource = source.slice(opening.length);
82
+ if (opening.startsWith("\\") || looksLikePendingDollarMath(pendingSource)) {
83
+ return { type: "latex", raw: source, text: pendingSource, pending: true };
84
+ }
85
+ return undefined;
86
+ }
87
+ const text = source.slice(opening.length, closingIndex);
88
+ if (!text || text.includes("\n")) {
89
+ return undefined;
90
+ }
91
+ const raw = source.slice(0, closingIndex + closing.length);
92
+ return { type: "latex", raw, text };
93
+ }
94
+ const TABLE_DELIMITER_ROW_REGEX = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
95
+ // A GFM table starts with a header row followed by a delimiter row such as "|---|---|" or "| --- |".
96
+ // The header needs a "|" only when the delimiter has none: a pipe-free delimiter without a pipe in the
97
+ // header is a thematic break, not a table.
98
+ function containsTableStart(source) {
99
+ const lines = source.split("\n");
100
+ for (let index = 0; index < lines.length - 1; index++) {
101
+ const delimiterRow = lines[index + 1];
102
+ if ((delimiterRow.includes("|") || lines[index].includes("|")) && TABLE_DELIMITER_ROW_REGEX.test(delimiterRow)) {
103
+ return true;
104
+ }
105
+ }
106
+ return false;
107
+ }
108
+ function tokenizeBlockLatex(source) {
109
+ // Display math never spans a table. Without this check, an unclosed "$$" or "\[" pairs with a later
110
+ // opener or stays pending, swallowing the table. See https://github.com/earendil-works/pi/issues/11159.
111
+ const dollarMatch = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);
112
+ if (dollarMatch?.[1] && !containsTableStart(dollarMatch[1])) {
113
+ return { type: "latexBlock", raw: dollarMatch[0], text: dollarMatch[1].trim() };
114
+ }
115
+ const bracketMatch = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);
116
+ if (bracketMatch?.[1] && !containsTableStart(bracketMatch[1])) {
117
+ return { type: "latexBlock", raw: bracketMatch[0], text: bracketMatch[1].trim() };
118
+ }
119
+ const pendingBracket = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
120
+ if (pendingBracket?.[1] && !containsTableStart(pendingBracket[1])) {
121
+ return { type: "latexBlock", raw: pendingBracket[0], text: pendingBracket[1], pending: true };
122
+ }
123
+ const pendingDollar = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
124
+ if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1]) && !containsTableStart(pendingDollar[1])) {
125
+ return { type: "latexBlock", raw: pendingDollar[0], text: pendingDollar[1], pending: true };
126
+ }
127
+ return undefined;
128
+ }
129
+ const LATEX_MARKDOWN_EXTENSIONS = [
130
+ {
131
+ name: "latexBlock",
132
+ level: "block",
133
+ start(source) {
134
+ const match = /(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);
135
+ return match ? match.index + (match[0].startsWith("\n") ? 1 : 0) : undefined;
136
+ },
137
+ tokenizer: tokenizeBlockLatex,
138
+ },
139
+ {
140
+ name: "latex",
141
+ level: "inline",
142
+ start(source) {
143
+ const indices = [source.indexOf("$"), source.indexOf("\\("), source.indexOf("\\[")].filter((index) => index >= 0);
144
+ return indices.length > 0 ? Math.min(...indices) : undefined;
145
+ },
146
+ tokenizer: tokenizeInlineLatex,
147
+ },
148
+ ];
149
+ function trimPartialClosingFences(tokens) {
150
+ const token = tokens[tokens.length - 1];
151
+ if (token?.type === "list") {
152
+ trimPartialClosingFences(token.items[token.items.length - 1]?.tokens ?? []);
153
+ return;
154
+ }
155
+ if (token?.type === "blockquote") {
156
+ trimPartialClosingFences(token.tokens ?? []);
157
+ return;
158
+ }
159
+ if (token?.type !== "code") {
160
+ return;
161
+ }
162
+ // Trim streamed partial closing fences so code blocks do not shrink/flicker
163
+ // when the final fence character arrives. See https://github.com/earendil-works/pi/issues/5825.
164
+ const marker = /^(`{3,}|~{3,})/.exec(token.raw)?.[1];
165
+ const lastLine = token.raw.split("\n").pop();
166
+ if (!marker || !lastLine || lastLine.length >= marker.length || lastLine !== marker[0]?.repeat(lastLine.length)) {
167
+ return;
168
+ }
169
+ token.text = token.text.slice(0, -lastLine.length).replace(/\n$/, "");
170
+ }
171
+ // An unclosed comment runs to the end of an HTML block, as in CommonMark, so streamed comments stay hidden.
172
+ const HTML_COMMENT_REGEX = /<!--[\s\S]*?(?:-->|$)/g;
173
+ function stripHtmlComments(html) {
174
+ return html.replace(HTML_COMMENT_REGEX, "");
175
+ }
176
+ /**
177
+ * Remove block HTML tokens that hold only comments, so they render no line. A removed comment between two blank
178
+ * lines, or at the start or end, also drops a blank line, so it leaves no extra gap.
179
+ * See https://github.com/earendil-works/pi/issues/11710.
180
+ */
181
+ function removeHtmlCommentBlocks(tokens) {
182
+ for (let i = tokens.length - 1; i >= 0; i--) {
183
+ const token = tokens[i];
184
+ if (token.type === "list") {
185
+ for (const item of token.items)
186
+ removeHtmlCommentBlocks(item.tokens);
187
+ }
188
+ else if (token.type === "blockquote") {
189
+ removeHtmlCommentBlocks(token.tokens ?? []);
190
+ }
191
+ else if (token.type === "html" && stripHtmlComments(token.raw).trim() === "") {
192
+ tokens.splice(i, 1);
193
+ if (tokens[i]?.type === "space" && (i === 0 || tokens[i - 1]?.type === "space")) {
194
+ tokens.splice(i, 1);
195
+ }
196
+ else if (i === tokens.length && tokens[i - 1]?.type === "space") {
197
+ tokens.splice(--i, 1);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ const markdownParser = new Marked();
203
+ markdownParser.setOptions({
204
+ tokenizer: new MarkdownTokenizer(),
205
+ });
206
+ markdownParser.use({
207
+ tokenizer: { emStrong: markedCjkFriendly().tokenizer?.emStrong },
208
+ extensions: [...LATEX_MARKDOWN_EXTENSIONS],
209
+ });
210
+ export class Markdown {
211
+ text;
212
+ paddingX; // Left/right padding
213
+ paddingY; // Top/bottom padding
214
+ defaultTextStyle;
215
+ theme;
216
+ options;
217
+ defaultStylePrefix;
218
+ // Cache for rendered output
219
+ cachedText;
220
+ cachedWidth;
221
+ cachedLines;
222
+ // Parsed tokens depend only on the source, so they survive theme and width invalidation. Held weakly: a token tree is
223
+ // about ten times the size of its source, and every message of a long transcript keeps a Markdown component. The
224
+ // tokens survive a burst of re-renders, such as a theme preview, and are collected afterwards.
225
+ cachedTokens;
226
+ // The last render's top-level blocks. While a message streams only its last block changes, so a render styles and
227
+ // wraps only that block. Each render keeps only the blocks it used, which drops a streamed block's earlier versions.
228
+ // Held weakly like the tokens: the blocks repeat the source in their keys and the code in their highlighting, and
229
+ // only a burst of renders, such as streaming or a resize, needs them.
230
+ blocks;
231
+ // Highlighted code of the block being rendered, only set while renderBlock runs.
232
+ blockHighlightedCode;
233
+ constructor(text, paddingX, paddingY, theme, defaultTextStyle, options) {
234
+ this.text = text;
235
+ this.paddingX = paddingX;
236
+ this.paddingY = paddingY;
237
+ this.theme = theme;
238
+ this.defaultTextStyle = defaultTextStyle;
239
+ this.options = options ? { ...options } : {};
240
+ }
241
+ setText(text) {
242
+ this.text = text;
243
+ this.clearRenderCache();
244
+ }
245
+ invalidate() {
246
+ this.clearRenderCache();
247
+ // The theme may have changed, which changes every styled line and the default style's prefix.
248
+ this.blocks = undefined;
249
+ this.defaultStylePrefix = undefined;
250
+ }
251
+ clearRenderCache() {
252
+ this.cachedText = undefined;
253
+ this.cachedWidth = undefined;
254
+ this.cachedLines = undefined;
255
+ }
256
+ render(width) {
257
+ // Check cache
258
+ if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
259
+ return this.cachedLines;
260
+ }
261
+ // Calculate available width for content (subtract horizontal padding)
262
+ const contentWidth = Math.max(1, width - this.paddingX * 2);
263
+ const text = this.options.transform?.(this.text, contentWidth) ?? this.text;
264
+ // Don't render anything if there's no actual text
265
+ if (!text || text.trim() === "") {
266
+ this.blocks = undefined;
267
+ const result = [];
268
+ // Update cache
269
+ this.cachedText = this.text;
270
+ this.cachedWidth = width;
271
+ this.cachedLines = result;
272
+ return result;
273
+ }
274
+ // Replace tabs with 3 spaces for consistent rendering
275
+ const normalizedText = text.replace(/\t/g, " ");
276
+ // Parse markdown to HTML-like tokens
277
+ const cached = this.cachedTokens?.deref();
278
+ let tokens = cached?.source === normalizedText ? cached.tokens : undefined;
279
+ if (!tokens) {
280
+ tokens = markdownParser.lexer(normalizedText);
281
+ trimPartialClosingFences(tokens);
282
+ removeHtmlCommentBlocks(tokens);
283
+ this.cachedTokens = new WeakRef({ source: normalizedText, tokens });
284
+ }
285
+ // A reference link resolves through a definition anywhere in the text, so blocks with the same source can render
286
+ // differently; such texts are rare in practice and render without reusing blocks.
287
+ const reuseBlocks = Object.keys(tokens.links).length === 0;
288
+ const previousBlocks = this.blocks?.deref();
289
+ const blocks = new Map();
290
+ this.blocks = new WeakRef(blocks);
291
+ const contentLines = [];
292
+ for (let i = 0; i < tokens.length; i++) {
293
+ const token = tokens[i];
294
+ const nextTokenType = tokens[i + 1]?.type;
295
+ const reused = reuseBlocks ? (blocks.get(token.raw) ?? previousBlocks?.get(token.raw)) : undefined;
296
+ const block = reused ?? { width: -1, nextTokenType, lines: [], highlightedCode: new Map() };
297
+ if (block.width !== width || block.nextTokenType !== nextTokenType) {
298
+ this.renderBlock(block, token, nextTokenType, width, contentWidth);
299
+ }
300
+ if (reuseBlocks)
301
+ blocks.set(token.raw, block);
302
+ for (const line of block.lines) {
303
+ contentLines.push(line);
304
+ }
305
+ }
306
+ // Add top/bottom padding (empty lines)
307
+ const bgFn = this.defaultTextStyle?.bgColor;
308
+ const emptyLine = " ".repeat(width);
309
+ const emptyLines = [];
310
+ for (let i = 0; i < this.paddingY; i++) {
311
+ const line = bgFn ? applyBackgroundToLine(emptyLine, width, bgFn) : emptyLine;
312
+ emptyLines.push(line);
313
+ }
314
+ flattenLines(emptyLines);
315
+ // Combine top padding, content, and bottom padding
316
+ const result = emptyLines.concat(contentLines, emptyLines);
317
+ // Update cache
318
+ this.cachedText = this.text;
319
+ this.cachedWidth = width;
320
+ this.cachedLines = result;
321
+ return result.length > 0 ? result : [""];
322
+ }
323
+ /** Render one top-level block to output lines: wrapped, with margins, and padded or backgrounded to the width. */
324
+ renderBlock(block, token, nextTokenType, width, contentWidth) {
325
+ this.blockHighlightedCode = block.highlightedCode;
326
+ const leftMargin = " ".repeat(this.paddingX);
327
+ const rightMargin = " ".repeat(this.paddingX);
328
+ const bgFn = this.defaultTextStyle?.bgColor;
329
+ const lines = [];
330
+ for (const line of this.renderToken(token, contentWidth, nextTokenType)) {
331
+ if (isImageLine(line)) {
332
+ lines.push(line);
333
+ continue;
334
+ }
335
+ for (const wrappedLine of wrapTextWithAnsi(line, contentWidth)) {
336
+ const lineWithMargins = leftMargin + wrappedLine + rightMargin;
337
+ if (bgFn) {
338
+ lines.push(applyBackgroundToLine(lineWithMargins, width, bgFn));
339
+ }
340
+ else {
341
+ // No background - just pad to width
342
+ const paddingNeeded = Math.max(0, width - visibleWidth(lineWithMargins));
343
+ lines.push(lineWithMargins + " ".repeat(paddingNeeded));
344
+ }
345
+ }
346
+ }
347
+ this.blockHighlightedCode = undefined;
348
+ flattenLines(lines);
349
+ block.lines = lines;
350
+ block.width = width;
351
+ block.nextTokenType = nextTokenType;
352
+ }
353
+ /**
354
+ * Apply default text style to a string.
355
+ * This is the base styling applied to all text content.
356
+ * NOTE: Background color is NOT applied here - it's applied at the padding stage
357
+ * to ensure it extends to the full line width.
358
+ */
359
+ applyDefaultStyle(text) {
360
+ if (!this.defaultTextStyle) {
361
+ return text;
362
+ }
363
+ let styled = text;
364
+ // Apply foreground color (NOT background - that's applied at padding stage)
365
+ if (this.defaultTextStyle.color) {
366
+ styled = this.defaultTextStyle.color(styled);
367
+ }
368
+ // Apply text decorations using this.theme
369
+ if (this.defaultTextStyle.bold) {
370
+ styled = this.theme.bold(styled);
371
+ }
372
+ if (this.defaultTextStyle.italic) {
373
+ styled = this.theme.italic(styled);
374
+ }
375
+ if (this.defaultTextStyle.strikethrough) {
376
+ styled = this.theme.strikethrough(styled);
377
+ }
378
+ if (this.defaultTextStyle.underline) {
379
+ styled = this.theme.underline(styled);
380
+ }
381
+ return styled;
382
+ }
383
+ getDefaultStylePrefix() {
384
+ if (!this.defaultTextStyle) {
385
+ return "";
386
+ }
387
+ if (this.defaultStylePrefix !== undefined) {
388
+ return this.defaultStylePrefix;
389
+ }
390
+ const sentinel = "\u0000";
391
+ let styled = sentinel;
392
+ if (this.defaultTextStyle.color) {
393
+ styled = this.defaultTextStyle.color(styled);
394
+ }
395
+ if (this.defaultTextStyle.bold) {
396
+ styled = this.theme.bold(styled);
397
+ }
398
+ if (this.defaultTextStyle.italic) {
399
+ styled = this.theme.italic(styled);
400
+ }
401
+ if (this.defaultTextStyle.strikethrough) {
402
+ styled = this.theme.strikethrough(styled);
403
+ }
404
+ if (this.defaultTextStyle.underline) {
405
+ styled = this.theme.underline(styled);
406
+ }
407
+ const sentinelIndex = styled.indexOf(sentinel);
408
+ this.defaultStylePrefix = sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
409
+ return this.defaultStylePrefix;
410
+ }
411
+ getStylePrefix(styleFn) {
412
+ const sentinel = "\u0000";
413
+ const styled = styleFn(sentinel);
414
+ const sentinelIndex = styled.indexOf(sentinel);
415
+ return sentinelIndex >= 0 ? styled.slice(0, sentinelIndex) : "";
416
+ }
417
+ getDefaultInlineStyleContext() {
418
+ return {
419
+ applyText: (text) => this.applyDefaultStyle(text),
420
+ stylePrefix: this.getDefaultStylePrefix(),
421
+ };
422
+ }
423
+ renderToken(token, width, nextTokenType, styleContext) {
424
+ const lines = [];
425
+ switch (token.type) {
426
+ case "heading": {
427
+ const headingLevel = token.depth;
428
+ const headingPrefix = `${"#".repeat(headingLevel)} `;
429
+ // Build a heading-specific style context so inline tokens (codespan, bold, etc.)
430
+ // restore heading styling after their own ANSI resets instead of falling back to
431
+ // the default text style.
432
+ let headingStyleFn;
433
+ if (headingLevel === 1) {
434
+ headingStyleFn = (text) => this.theme.heading(this.theme.bold(this.theme.underline(text)));
435
+ }
436
+ else {
437
+ headingStyleFn = (text) => this.theme.heading(this.theme.bold(text));
438
+ }
439
+ const headingStyleContext = {
440
+ applyText: headingStyleFn,
441
+ stylePrefix: this.getStylePrefix(headingStyleFn),
442
+ };
443
+ const headingText = this.renderInlineTokens(token.tokens || [], headingStyleContext);
444
+ const styledHeading = headingLevel >= 3 ? headingStyleFn(headingPrefix) + headingText : headingText;
445
+ lines.push(styledHeading);
446
+ if (nextTokenType && nextTokenType !== "space") {
447
+ lines.push(""); // Add spacing after headings (unless space token follows)
448
+ }
449
+ break;
450
+ }
451
+ case "paragraph": {
452
+ const paragraphText = this.renderInlineTokens(token.tokens || [], styleContext);
453
+ lines.push(paragraphText);
454
+ // Don't add spacing if next token is space or list
455
+ if (nextTokenType && nextTokenType !== "list" && nextTokenType !== "space") {
456
+ lines.push("");
457
+ }
458
+ break;
459
+ }
460
+ case "text":
461
+ lines.push(this.renderInlineTokens([token], styleContext));
462
+ break;
463
+ case "latexBlock": {
464
+ const latexToken = token;
465
+ let rendered = !latexToken.pending && this.options.renderLatex !== false
466
+ ? renderLatex(latexToken.text, { display: true })
467
+ : undefined;
468
+ // A 2D layout cannot be wrapped row by row; fall back to the raw source when it does not fit.
469
+ if (rendered === undefined || rendered.split("\n").some((line) => visibleWidth(line) > width)) {
470
+ rendered = latexToken.raw.trim();
471
+ }
472
+ for (const line of rendered.split("\n")) {
473
+ lines.push(this.applyDefaultStyle(line));
474
+ }
475
+ if (nextTokenType && nextTokenType !== "space") {
476
+ lines.push("");
477
+ }
478
+ break;
479
+ }
480
+ case "code": {
481
+ const indent = this.theme.codeBlockIndent ?? " ";
482
+ lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
483
+ if (this.theme.highlightCode) {
484
+ const key = `${token.lang ?? ""}\0${token.text}`;
485
+ let highlighted = this.blockHighlightedCode?.get(key);
486
+ if (!highlighted) {
487
+ highlighted = this.theme.highlightCode(token.text, token.lang);
488
+ this.blockHighlightedCode?.set(key, highlighted);
489
+ }
490
+ for (const hlLine of highlighted) {
491
+ lines.push(`${indent}${hlLine}`);
492
+ }
493
+ }
494
+ else {
495
+ // Split code by newlines and style each line
496
+ const codeLines = token.text.split("\n");
497
+ for (const codeLine of codeLines) {
498
+ lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
499
+ }
500
+ }
501
+ lines.push(this.theme.codeBlockBorder("```"));
502
+ if (nextTokenType && nextTokenType !== "space") {
503
+ lines.push(""); // Add spacing after code blocks (unless space token follows)
504
+ }
505
+ break;
506
+ }
507
+ case "list": {
508
+ const listLines = this.renderList(token, 0, width, styleContext);
509
+ lines.push(...listLines);
510
+ // Don't add spacing after lists if a space token follows
511
+ // (the space token will handle it)
512
+ break;
513
+ }
514
+ case "table": {
515
+ const tableLines = this.renderTable(token, width, nextTokenType, styleContext);
516
+ lines.push(...tableLines);
517
+ break;
518
+ }
519
+ case "blockquote": {
520
+ const quoteStyle = (text) => this.theme.quote(this.theme.italic(text));
521
+ const quoteStylePrefix = this.getStylePrefix(quoteStyle);
522
+ const applyQuoteStyle = (line) => {
523
+ if (!quoteStylePrefix) {
524
+ return quoteStyle(line);
525
+ }
526
+ const lineWithReappliedStyle = line.replace(/\x1b\[0m/g, `\x1b[0m${quoteStylePrefix}`);
527
+ return quoteStyle(lineWithReappliedStyle);
528
+ };
529
+ // With no room for another border ("│ " plus at least one content column), render the
530
+ // nested content without one. Otherwise each extra level re-wraps every child line at
531
+ // width 1 and the output grows exponentially with nesting depth.
532
+ if (width < 3) {
533
+ const quoteTokens = token.tokens || [];
534
+ for (let i = 0; i < quoteTokens.length; i++) {
535
+ for (const line of this.renderToken(quoteTokens[i], width, quoteTokens[i + 1]?.type, styleContext)) {
536
+ lines.push(line);
537
+ }
538
+ }
539
+ break;
540
+ }
541
+ // Calculate available width for quote content (subtract border "│ " = 2 chars)
542
+ const quoteContentWidth = width - 2;
543
+ // Blockquotes contain block-level tokens (paragraph, list, code, etc.), so render
544
+ // children with renderToken() instead of renderInlineTokens().
545
+ // Default message style should not apply inside blockquotes.
546
+ const quoteInlineStyleContext = {
547
+ applyText: (text) => text,
548
+ stylePrefix: quoteStylePrefix,
549
+ };
550
+ const quoteTokens = token.tokens || [];
551
+ const renderedQuoteLines = [];
552
+ for (let i = 0; i < quoteTokens.length; i++) {
553
+ const quoteToken = quoteTokens[i];
554
+ const nextQuoteToken = quoteTokens[i + 1];
555
+ for (const line of this.renderToken(quoteToken, quoteContentWidth, nextQuoteToken?.type, quoteInlineStyleContext)) {
556
+ renderedQuoteLines.push(line);
557
+ }
558
+ }
559
+ // Avoid rendering an extra empty quote line before the outer blockquote spacing.
560
+ while (renderedQuoteLines.length > 0 && renderedQuoteLines[renderedQuoteLines.length - 1] === "") {
561
+ renderedQuoteLines.pop();
562
+ }
563
+ for (const quoteLine of renderedQuoteLines) {
564
+ const styledLine = applyQuoteStyle(quoteLine);
565
+ const wrappedLines = wrapTextWithAnsi(styledLine, quoteContentWidth);
566
+ for (const wrappedLine of wrappedLines) {
567
+ lines.push(this.theme.quoteBorder("│ ") + wrappedLine);
568
+ }
569
+ }
570
+ if (nextTokenType && nextTokenType !== "space") {
571
+ lines.push(""); // Add spacing after blockquotes (unless space token follows)
572
+ }
573
+ break;
574
+ }
575
+ case "hr":
576
+ lines.push(this.theme.hr("─".repeat(Math.min(width, 80))));
577
+ if (nextTokenType && nextTokenType !== "space") {
578
+ lines.push(""); // Add spacing after horizontal rules (unless space token follows)
579
+ }
580
+ break;
581
+ case "html":
582
+ // Render HTML as plain text (escaped for terminal), without its comments
583
+ if ("raw" in token && typeof token.raw === "string") {
584
+ lines.push(this.applyDefaultStyle(stripHtmlComments(token.raw).trim()));
585
+ }
586
+ break;
587
+ case "space":
588
+ // Space tokens represent blank lines in markdown
589
+ lines.push("");
590
+ break;
591
+ default:
592
+ // Handle any other token types as plain text
593
+ if ("text" in token && typeof token.text === "string") {
594
+ lines.push(token.text);
595
+ }
596
+ }
597
+ return lines;
598
+ }
599
+ renderInlineTokens(tokens, styleContext) {
600
+ let result = "";
601
+ const resolvedStyleContext = styleContext ?? this.getDefaultInlineStyleContext();
602
+ const { applyText, stylePrefix } = resolvedStyleContext;
603
+ const applyTextWithNewlines = (text) => {
604
+ const segments = text.split("\n");
605
+ return segments.map((segment) => applyText(segment)).join("\n");
606
+ };
607
+ // After a skipped HTML comment, drop the next text's leading space if the text before ended with one,
608
+ // so "a <!-- c --> b" renders as "a b".
609
+ let dropLeadingSpace = false;
610
+ for (let i = 0; i < tokens.length; i++) {
611
+ let token = tokens[i];
612
+ if (dropLeadingSpace && token.type === "text" && !token.tokens?.length && /^[ \t]/.test(token.text)) {
613
+ token = { ...token, text: token.text.replace(/^[ \t]+/, "") };
614
+ }
615
+ dropLeadingSpace = false;
616
+ switch (token.type) {
617
+ case "latex": {
618
+ const latexToken = token;
619
+ const rendered = !latexToken.pending && this.options.renderLatex !== false
620
+ ? (renderLatex(latexToken.text) ?? latexToken.raw)
621
+ : latexToken.raw;
622
+ result += applyTextWithNewlines(rendered);
623
+ break;
624
+ }
625
+ case "escape":
626
+ result += applyTextWithNewlines(this.options.preserveBackslashEscapes ? token.raw : token.text);
627
+ break;
628
+ case "text":
629
+ // Text tokens in list items can have nested tokens for inline formatting
630
+ if (token.tokens && token.tokens.length > 0) {
631
+ result += this.renderInlineTokens(token.tokens, resolvedStyleContext);
632
+ }
633
+ else {
634
+ result += applyTextWithNewlines(token.text);
635
+ }
636
+ break;
637
+ case "paragraph":
638
+ // Paragraph tokens contain nested inline tokens
639
+ result += this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
640
+ break;
641
+ case "strong": {
642
+ const boldContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
643
+ result += this.theme.bold(boldContent) + stylePrefix;
644
+ break;
645
+ }
646
+ case "em": {
647
+ const italicContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
648
+ result += this.theme.italic(italicContent) + stylePrefix;
649
+ break;
650
+ }
651
+ case "codespan":
652
+ result += this.theme.code(token.text) + stylePrefix;
653
+ break;
654
+ case "link": {
655
+ const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
656
+ const styledLink = this.theme.link(this.theme.underline(linkText));
657
+ if (getCapabilities().hyperlinks) {
658
+ // OSC 8: render as a clickable hyperlink. The URL is not printed inline,
659
+ // so we always show only the link text regardless of whether it matches href.
660
+ result += hyperlink(styledLink, token.href) + stylePrefix;
661
+ }
662
+ else {
663
+ // Fallback: print URL in parentheses when text differs from href.
664
+ // Compare raw token.text (not styled) against href for the equality check.
665
+ // For mailto: links strip the prefix (autolinked emails use text="foo@bar.com"
666
+ // but href="mailto:foo@bar.com").
667
+ const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href;
668
+ if (token.text === token.href || token.text === hrefForComparison) {
669
+ result += styledLink + stylePrefix;
670
+ }
671
+ else {
672
+ result += styledLink + this.theme.linkUrl(` (${token.href})`) + stylePrefix;
673
+ }
674
+ }
675
+ break;
676
+ }
677
+ case "br":
678
+ result += "\n";
679
+ break;
680
+ case "del": {
681
+ const delContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
682
+ result += this.theme.strikethrough(delContent) + stylePrefix;
683
+ break;
684
+ }
685
+ case "html":
686
+ // Render inline HTML as plain text; comments are hidden
687
+ if (token.raw.startsWith("<!--")) {
688
+ dropLeadingSpace = i === 0 || /[ \t]$/.test(tokens[i - 1].raw);
689
+ }
690
+ else {
691
+ result += applyTextWithNewlines(token.raw);
692
+ }
693
+ break;
694
+ default:
695
+ // Handle any other inline token types as plain text
696
+ if ("text" in token && typeof token.text === "string") {
697
+ result += applyTextWithNewlines(token.text);
698
+ }
699
+ }
700
+ }
701
+ while (stylePrefix && result.endsWith(stylePrefix)) {
702
+ result = result.slice(0, -stylePrefix.length);
703
+ }
704
+ return result;
705
+ }
706
+ getOrderedListMarker(item) {
707
+ const match = /^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);
708
+ return match ? `${match[1]} ` : undefined;
709
+ }
710
+ getUnorderedListMarker(item) {
711
+ const match = /^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);
712
+ return match ? `${match[1]} ` : undefined;
713
+ }
714
+ /**
715
+ * Render a list with proper nesting support
716
+ */
717
+ renderList(token, depth, width, styleContext) {
718
+ const lines = [];
719
+ const indent = " ".repeat(depth);
720
+ // Use the list's start property (defaults to 1 for ordered lists)
721
+ const startNumber = typeof token.start === "number" ? token.start : 1;
722
+ for (let i = 0; i < token.items.length; i++) {
723
+ const item = token.items[i];
724
+ const isLastItem = i === token.items.length - 1;
725
+ const bullet = token.ordered
726
+ ? this.options.preserveOrderedListMarkers
727
+ ? (this.getOrderedListMarker(item) ?? `${startNumber + i}. `)
728
+ : `${startNumber + i}. `
729
+ : this.options.preserveOrderedListMarkers
730
+ ? (this.getUnorderedListMarker(item) ?? "- ")
731
+ : "- ";
732
+ const taskMarker = item.task ? `[${item.checked ? "x" : " "}] ` : "";
733
+ const marker = bullet + taskMarker;
734
+ const firstPrefix = indent + this.theme.listBullet(marker);
735
+ const continuationPrefix = indent + " ".repeat(visibleWidth(marker));
736
+ const itemWidth = Math.max(1, width - visibleWidth(firstPrefix));
737
+ let renderedAnyLine = false;
738
+ for (const itemToken of item.tokens) {
739
+ if (itemToken.type === "list") {
740
+ lines.push(...this.renderList(itemToken, depth + 1, width, styleContext));
741
+ renderedAnyLine = true;
742
+ continue;
743
+ }
744
+ const itemLines = this.renderToken(itemToken, itemWidth, undefined, styleContext);
745
+ for (const line of itemLines) {
746
+ for (const wrappedLine of wrapTextWithAnsi(line, itemWidth)) {
747
+ const linePrefix = renderedAnyLine ? continuationPrefix : firstPrefix;
748
+ lines.push(linePrefix + wrappedLine);
749
+ renderedAnyLine = true;
750
+ }
751
+ }
752
+ }
753
+ if (!renderedAnyLine) {
754
+ lines.push(firstPrefix);
755
+ }
756
+ if (token.loose && !isLastItem) {
757
+ lines.push("");
758
+ }
759
+ }
760
+ return lines;
761
+ }
762
+ /**
763
+ * Get the visible width of the longest word in a string.
764
+ */
765
+ getLongestWordWidth(text, maxWidth) {
766
+ const words = text.split(/\s+/).filter((word) => word.length > 0);
767
+ let longest = 0;
768
+ for (const word of words) {
769
+ longest = Math.max(longest, visibleWidth(word));
770
+ }
771
+ if (maxWidth === undefined) {
772
+ return longest;
773
+ }
774
+ return Math.min(longest, maxWidth);
775
+ }
776
+ /**
777
+ * Wrap a table cell to fit into a column.
778
+ *
779
+ * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled
780
+ * consistently with the rest of the renderer.
781
+ */
782
+ wrapCellText(text, maxWidth, stylePrefix = "") {
783
+ const lines = wrapTextWithAnsi(text, Math.max(1, maxWidth));
784
+ return lines.map((line, index) => {
785
+ // Reset text styles after each non-final fragment, then restore the surrounding style before padding and borders.
786
+ const styleReset = index < lines.length - 1 ? "\x1b[22;23;24;25;27;28;29;39m" : "";
787
+ return `${line}${styleReset}${stylePrefix}`;
788
+ });
789
+ }
790
+ /**
791
+ * Render a table with width-aware cell wrapping.
792
+ * Cells that don't fit are wrapped to multiple lines.
793
+ */
794
+ renderTable(token, availableWidth, nextTokenType, styleContext) {
795
+ const lines = [];
796
+ const numCols = token.header.length;
797
+ if (numCols === 0) {
798
+ return lines;
799
+ }
800
+ // Calculate border overhead: "│ " + (n-1) * " │ " + " │"
801
+ // = 2 + (n-1) * 3 + 2 = 3n + 1
802
+ const borderOverhead = 3 * numCols + 1;
803
+ const availableForCells = availableWidth - borderOverhead;
804
+ if (availableForCells < numCols) {
805
+ // Too narrow to render a stable table. Fall back to raw markdown.
806
+ const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
807
+ if (nextTokenType && nextTokenType !== "space") {
808
+ fallbackLines.push("");
809
+ }
810
+ return fallbackLines;
811
+ }
812
+ const maxUnbrokenWordWidth = 30;
813
+ // Calculate natural column widths (what each column needs without constraints)
814
+ const naturalWidths = [];
815
+ const minWordWidths = [];
816
+ for (let i = 0; i < numCols; i++) {
817
+ const headerText = this.renderInlineTokens(token.header[i].tokens || [], styleContext);
818
+ naturalWidths[i] = visibleWidth(headerText);
819
+ minWordWidths[i] = Math.max(1, this.getLongestWordWidth(headerText, maxUnbrokenWordWidth));
820
+ }
821
+ for (const row of token.rows) {
822
+ for (let i = 0; i < row.length; i++) {
823
+ const cellText = this.renderInlineTokens(row[i].tokens || [], styleContext);
824
+ naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
825
+ minWordWidths[i] = Math.max(minWordWidths[i] || 1, this.getLongestWordWidth(cellText, maxUnbrokenWordWidth));
826
+ }
827
+ }
828
+ let minColumnWidths = minWordWidths;
829
+ let minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
830
+ if (minCellsWidth > availableForCells) {
831
+ minColumnWidths = new Array(numCols).fill(1);
832
+ const remaining = availableForCells - numCols;
833
+ if (remaining > 0) {
834
+ const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
835
+ const growth = minWordWidths.map((width) => {
836
+ const weight = Math.max(0, width - 1);
837
+ return totalWeight > 0 ? Math.floor((weight / totalWeight) * remaining) : 0;
838
+ });
839
+ for (let i = 0; i < numCols; i++) {
840
+ minColumnWidths[i] += growth[i] ?? 0;
841
+ }
842
+ const allocated = growth.reduce((total, width) => total + width, 0);
843
+ let leftover = remaining - allocated;
844
+ for (let i = 0; leftover > 0 && i < numCols; i++) {
845
+ minColumnWidths[i]++;
846
+ leftover--;
847
+ }
848
+ }
849
+ minCellsWidth = minColumnWidths.reduce((a, b) => a + b, 0);
850
+ }
851
+ // Calculate column widths that fit within available width
852
+ const totalNaturalWidth = naturalWidths.reduce((a, b) => a + b, 0) + borderOverhead;
853
+ let columnWidths;
854
+ if (totalNaturalWidth <= availableWidth) {
855
+ // Everything fits naturally
856
+ columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
857
+ }
858
+ else {
859
+ // Need to shrink columns to fit
860
+ const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
861
+ return total + Math.max(0, width - minColumnWidths[index]);
862
+ }, 0);
863
+ const extraWidth = Math.max(0, availableForCells - minCellsWidth);
864
+ columnWidths = minColumnWidths.map((minWidth, index) => {
865
+ const naturalWidth = naturalWidths[index];
866
+ const minWidthDelta = Math.max(0, naturalWidth - minWidth);
867
+ let grow = 0;
868
+ if (totalGrowPotential > 0) {
869
+ grow = Math.floor((minWidthDelta / totalGrowPotential) * extraWidth);
870
+ }
871
+ return minWidth + grow;
872
+ });
873
+ // Adjust for rounding errors - distribute remaining space
874
+ const allocated = columnWidths.reduce((a, b) => a + b, 0);
875
+ let remaining = availableForCells - allocated;
876
+ while (remaining > 0) {
877
+ let grew = false;
878
+ for (let i = 0; i < numCols && remaining > 0; i++) {
879
+ if (columnWidths[i] < naturalWidths[i]) {
880
+ columnWidths[i]++;
881
+ remaining--;
882
+ grew = true;
883
+ }
884
+ }
885
+ if (!grew) {
886
+ break;
887
+ }
888
+ }
889
+ }
890
+ // Render top border
891
+ const topBorderCells = columnWidths.map((w) => "─".repeat(w));
892
+ lines.push(`┌─${topBorderCells.join("─┬─")}─┐`);
893
+ // Render header with wrapping
894
+ const headerCellLines = token.header.map((cell, i) => {
895
+ const text = this.renderInlineTokens(cell.tokens || [], styleContext);
896
+ return this.wrapCellText(text, columnWidths[i], styleContext?.stylePrefix);
897
+ });
898
+ const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
899
+ for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
900
+ const rowParts = headerCellLines.map((cellLines, colIdx) => {
901
+ const text = cellLines[lineIdx] || "";
902
+ const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
903
+ return this.theme.bold(padded);
904
+ });
905
+ lines.push(`│ ${rowParts.join(" │ ")} │`);
906
+ }
907
+ // Render separator
908
+ const separatorCells = columnWidths.map((w) => "─".repeat(w));
909
+ const separatorLine = `├─${separatorCells.join("─┼─")}─┤`;
910
+ lines.push(separatorLine);
911
+ // Render rows with wrapping
912
+ for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
913
+ const row = token.rows[rowIndex];
914
+ const rowCellLines = row.map((cell, i) => {
915
+ const text = this.renderInlineTokens(cell.tokens || [], styleContext);
916
+ return this.wrapCellText(text, columnWidths[i], styleContext?.stylePrefix);
917
+ });
918
+ const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
919
+ for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
920
+ const rowParts = rowCellLines.map((cellLines, colIdx) => {
921
+ const text = cellLines[lineIdx] || "";
922
+ return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
923
+ });
924
+ lines.push(`│ ${rowParts.join(" │ ")} │`);
925
+ }
926
+ if (rowIndex < token.rows.length - 1) {
927
+ lines.push(separatorLine);
928
+ }
929
+ }
930
+ // Render bottom border
931
+ const bottomBorderCells = columnWidths.map((w) => "─".repeat(w));
932
+ lines.push(`└─${bottomBorderCells.join("─┴─")}─┘`);
933
+ if (nextTokenType && nextTokenType !== "space") {
934
+ lines.push(""); // Add spacing after table
935
+ }
936
+ return lines;
937
+ }
938
+ }
939
+ //# sourceMappingURL=markdown.js.map