pi-syntax-highlight 0.0.0-stage → 0.1.1

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 (52) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/DEVELOPER.md +73 -0
  3. package/README.md +65 -2
  4. package/assets/icon.png +0 -0
  5. package/assets/icon.svg +36 -0
  6. package/extensions/index.ts +22 -0
  7. package/package.json +49 -4
  8. package/src/active-theme.ts +26 -0
  9. package/src/detect-language.ts +294 -0
  10. package/src/emphasis.ts +160 -0
  11. package/src/grep-parse.ts +42 -0
  12. package/src/highlight.ts +109 -0
  13. package/src/markdown-fence-lang.ts +180 -0
  14. package/src/markdown-style.ts +134 -0
  15. package/src/markdown-theme.ts +53 -0
  16. package/src/render-bash.ts +180 -0
  17. package/src/render-edit.ts +207 -0
  18. package/src/render-find.ts +64 -0
  19. package/src/render-generic.ts +86 -0
  20. package/src/render-grep.ts +142 -0
  21. package/src/render-ls.ts +66 -0
  22. package/src/render-path.ts +54 -0
  23. package/src/render-read.ts +277 -0
  24. package/src/render-utils.ts +219 -0
  25. package/src/render-write.ts +81 -0
  26. package/src/resolve-renderers.ts +406 -0
  27. package/src/style-path.ts +48 -0
  28. package/src/tokens.ts +114 -0
  29. package/test/unit/active-theme.test.ts +38 -0
  30. package/test/unit/bash-preview.test.ts +57 -0
  31. package/test/unit/detect-language.test.ts +124 -0
  32. package/test/unit/emphasis.test.ts +113 -0
  33. package/test/unit/extensions-index.test.ts +116 -0
  34. package/test/unit/grep-parse.test.ts +125 -0
  35. package/test/unit/highlight.test.ts +107 -0
  36. package/test/unit/markdown-fence-lang.test.ts +131 -0
  37. package/test/unit/markdown-pipeline.test.ts +153 -0
  38. package/test/unit/markdown-render-parity.test.ts +127 -0
  39. package/test/unit/markdown-style.test.ts +152 -0
  40. package/test/unit/markdown-theme.test.ts +86 -0
  41. package/test/unit/render-bash.test.ts +194 -0
  42. package/test/unit/render-edit.test.ts +214 -0
  43. package/test/unit/render-find.test.ts +139 -0
  44. package/test/unit/render-generic.test.ts +152 -0
  45. package/test/unit/render-grep.test.ts +338 -0
  46. package/test/unit/render-ls.test.ts +132 -0
  47. package/test/unit/render-read.test.ts +375 -0
  48. package/test/unit/render-utils.test.ts +324 -0
  49. package/test/unit/render-write.test.ts +143 -0
  50. package/test/unit/resolve-renderers.test.ts +474 -0
  51. package/test/unit/style-path.test.ts +74 -0
  52. package/tsconfig.json +15 -0
@@ -0,0 +1,131 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { normalizeInfoString, transformFenceLanguages } from "../../src/markdown-fence-lang.ts";
4
+
5
+ const PROSE = "This paragraph explains why the transformer runs before rendering.\nIt keeps the fence character and the body untouched.";
6
+
7
+ test("normalizeInfoString: an empty info string takes the detected language", () => {
8
+ assert.equal(normalizeInfoString("", `{\n "name": "pi"\n}`), "json");
9
+ // Nothing detected and nothing declared stays empty: the fence keeps the flat
10
+ // color instead of gaining a wrong one.
11
+ assert.equal(normalizeInfoString(" ", PROSE), "");
12
+ });
13
+
14
+ test("normalizeInfoString: a known name or alias is returned as written", () => {
15
+ assert.equal(normalizeInfoString("ts", "const x = 1;"), "ts");
16
+ assert.equal(normalizeInfoString("{.ts}", "const x = 1;"), "ts");
17
+ assert.equal(normalizeInfoString(`js title="a"`, "const x = 1;"), "js");
18
+ });
19
+
20
+ test("normalizeInfoString: a token the author wrote is returned as written, whatever the body is", () => {
21
+ assert.equal(normalizeInfoString("foo", PROSE), "foo");
22
+ // Detection only fills a gap: a recognizable body never overrides a label.
23
+ assert.equal(normalizeInfoString("foo", "git clone https://example.com/repo.git\ncd repo"), "foo");
24
+ assert.equal(normalizeInfoString("powershell", `{\n "name": "pi"\n}`), "powershell");
25
+ });
26
+
27
+ test("an unlabeled fence gets the detected language and the text around it is copied", () => {
28
+ const markdown = `Here is the config:\n\n\`\`\`\n{\n "name": "pi"\n}\n\`\`\`\n\nThat is all.\n`;
29
+ assert.equal(
30
+ transformFenceLanguages(markdown),
31
+ `Here is the config:\n\n\`\`\`json\n{\n "name": "pi"\n}\n\`\`\`\n\nThat is all.\n`,
32
+ );
33
+ });
34
+
35
+ test("a fence that already names a language is left alone", () => {
36
+ const markdown = "```js\nconst x = 1;\n```\n";
37
+ assert.equal(transformFenceLanguages(markdown), markdown);
38
+ });
39
+
40
+ test("an info string with attributes keeps only its language", () => {
41
+ assert.equal(
42
+ transformFenceLanguages(`\`\`\`js title="a"\nconst x = 1;\n\`\`\`\n`),
43
+ "```js\nconst x = 1;\n```\n",
44
+ );
45
+ });
46
+
47
+ test("an unknown info string survives, and the body is not detected for it", () => {
48
+ const markdown = "```foo\ngit clone https://example.com/repo.git\ncd repo\nnpm install\n```\n";
49
+ assert.equal(transformFenceLanguages(markdown), markdown);
50
+ });
51
+
52
+ test("an unknown info string survives when the body is prose", () => {
53
+ const markdown = `\`\`\`foo\n${PROSE}\n\`\`\`\n`;
54
+ assert.equal(transformFenceLanguages(markdown), markdown);
55
+ });
56
+
57
+ test("an unclosed fence is untouched", () => {
58
+ const markdown = `\`\`\`\n{\n "name": "pi"\n}\n`;
59
+ assert.equal(transformFenceLanguages(markdown), markdown);
60
+ });
61
+
62
+ test("a block indented four spaces is not a fence and stays untouched", () => {
63
+ const markdown = ` \`\`\`\n {"name": "pi"}\n \`\`\`\n`;
64
+ assert.equal(transformFenceLanguages(markdown), markdown);
65
+ });
66
+
67
+ test("a tilde fence is rewritten the same way", () => {
68
+ assert.equal(
69
+ transformFenceLanguages(`~~~\n{\n "name": "pi"\n}\n~~~\n`),
70
+ `~~~json\n{\n "name": "pi"\n}\n~~~\n`,
71
+ );
72
+ });
73
+
74
+ test("with the last fence open only the closed one is rewritten", () => {
75
+ const markdown = `\`\`\`\n{\n "name": "pi"\n}\n\`\`\`\n\n\`\`\`\nconst x = 1;\n`;
76
+ assert.equal(
77
+ transformFenceLanguages(markdown),
78
+ `\`\`\`json\n{\n "name": "pi"\n}\n\`\`\`\n\n\`\`\`\nconst x = 1;\n`,
79
+ );
80
+ });
81
+
82
+ test("a closing fence may be longer than the opening one", () => {
83
+ assert.equal(
84
+ transformFenceLanguages(`\`\`\`\n{\n "name": "pi"\n}\n\`\`\`\`\`\n`),
85
+ `\`\`\`json\n{\n "name": "pi"\n}\n\`\`\`\`\`\n`,
86
+ );
87
+ });
88
+
89
+ test("a pandoc attribute list naming the language is unwrapped", () => {
90
+ assert.equal(
91
+ transformFenceLanguages(`\`\`\`{.ts}\ninterface User {\n id: number;\n}\n\`\`\`\n`),
92
+ "```ts\ninterface User {\n id: number;\n}\n```\n",
93
+ );
94
+ });
95
+
96
+ test("the transform is idempotent", () => {
97
+ const markdown = `Intro\n\n\`\`\`\n{\n "name": "pi"\n}\n\`\`\`\n\n\`\`\`js title="a"\nconst x = 1;\n\`\`\`\n\n~~~foo\ngit status\n~~~\n`;
98
+ const once = transformFenceLanguages(markdown);
99
+ assert.notEqual(once, markdown);
100
+ assert.equal(transformFenceLanguages(once), once);
101
+ });
102
+
103
+ test("a correctly labeled fence keeps its token even when the body would be detected", () => {
104
+ const powershell = "```powershell\nGet-ChildItem | Where-Object { $_.Name }\n```\n";
105
+ assert.equal(transformFenceLanguages(powershell), powershell);
106
+ });
107
+
108
+ test("a mermaid fence is left to the built-in transformer", () => {
109
+ const markdown = "```mermaid\ngraph TD;\n A-->B;\n```\n";
110
+ assert.equal(transformFenceLanguages(markdown), markdown);
111
+ });
112
+
113
+ test("a mermaid fence whose body looks like JSON is still left alone", () => {
114
+ const markdown = `\`\`\`mermaid\n{\n "name": "pi"\n}\n\`\`\`\n`;
115
+ assert.equal(transformFenceLanguages(markdown), markdown);
116
+ });
117
+
118
+ test("a reserved info string is compared case-insensitively", () => {
119
+ const markdown = `\`\`\`Mermaid\n{\n "name": "pi"\n}\n\`\`\`\n`;
120
+ assert.equal(transformFenceLanguages(markdown), markdown);
121
+ });
122
+
123
+ test("a backtick in the info string of a backtick fence opens nothing", () => {
124
+ const markdown = "```js``` is the info string.\n\n```js\nconst x = 1;\n```\n";
125
+ assert.equal(transformFenceLanguages(markdown), markdown);
126
+ });
127
+
128
+ test("a tilde in the info string of a tilde fence opens nothing", () => {
129
+ const markdown = "~~~js~~~ is the info string.\n\n~~~js\nconst x = 1;\n~~~\n";
130
+ assert.equal(transformFenceLanguages(markdown), markdown);
131
+ });
@@ -0,0 +1,153 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import type { MarkdownTransformContext, MarkdownTransformer } from "@earendil-works/pi-coding-agent";
4
+ import { createMarkdownTransformer, transformFenceLanguages } from "../../src/markdown-fence-lang.ts";
5
+ import {
6
+ DIM_OFF,
7
+ DIM_ON,
8
+ FG_DEFAULT,
9
+ ITALIC_OFF,
10
+ ITALIC_ON,
11
+ UNDERLINE_OFF,
12
+ UNDERLINE_ON,
13
+ type AnsiTheme,
14
+ } from "../../src/tokens.ts";
15
+
16
+ const ACCENT = "\x1b[38;5;5m";
17
+ const NEXT_ACCENT = "\x1b[38;5;6m";
18
+ const ESCAPE = "\u001b";
19
+
20
+ // Same shape as the host's theme: the sequences live in a map that a theme switch
21
+ // rewrites under the same object, so the fake can show the memo reacting to a value
22
+ // change instead of a reference change.
23
+ function fakeTheme(): { theme: AnsiTheme; ansi: Record<string, string> } {
24
+ const ansi: Record<string, string> = { accent: ACCENT, mdQuote: FG_DEFAULT + DIM_ON };
25
+ return {
26
+ ansi,
27
+ theme: {
28
+ getFgAnsi: (color) => ansi[color] ?? "",
29
+ getBgAnsi: () => "",
30
+ },
31
+ };
32
+ }
33
+
34
+ function context(messageType: MarkdownTransformContext["messageType"]): MarkdownTransformContext {
35
+ return { messageType, isStreaming: false, availableWidth: 80 };
36
+ }
37
+
38
+ function transformerFor(theme: AnsiTheme | undefined): MarkdownTransformer {
39
+ return createMarkdownTransformer({ resolveTheme: () => theme });
40
+ }
41
+
42
+ // Every sequence the pass injects is opened and closed inside the same line, so a
43
+ // line wrapped by the renderer can never inherit a style from the one before it.
44
+ const SEQUENCE_PAIRS = [
45
+ [ACCENT, FG_DEFAULT],
46
+ [ITALIC_ON, ITALIC_OFF],
47
+ [UNDERLINE_ON, UNDERLINE_OFF],
48
+ [DIM_OFF, DIM_ON],
49
+ ] as const;
50
+
51
+ function assertClosedPerLine(output: string): void {
52
+ for (const line of output.split("\n")) {
53
+ for (const [on, off] of SEQUENCE_PAIRS) {
54
+ assert.equal(occurrences(line, on), occurrences(line, off), `unbalanced ${JSON.stringify(on)} in ${line}`);
55
+ }
56
+ }
57
+ }
58
+
59
+ function occurrences(text: string, part: string): number {
60
+ return text.split(part).length - 1;
61
+ }
62
+
63
+ test("the pipeline: an assistant message gets the heading and the quote styles", () => {
64
+ const output = transformerFor(fakeTheme().theme)("# Title\n\n> quoted\n", context("assistant"));
65
+ assert.ok(output.includes(`${ACCENT}${ITALIC_ON}Title${ITALIC_OFF}${FG_DEFAULT}`));
66
+ assert.ok(output.includes(`> ${DIM_OFF}${ACCENT}quoted${FG_DEFAULT}${DIM_ON}`));
67
+ });
68
+
69
+ test("the pipeline: a user message is exactly what the fence labeling produced", () => {
70
+ const markdown = "# Title\n\n```\n{\n \"name\": \"pi\"\n}\n```\n\n- use `tsc`\n";
71
+ const output = transformerFor(fakeTheme().theme)(markdown, context("user"));
72
+ assert.equal(output, transformFenceLanguages(markdown));
73
+ // The escape of the restored delimiters would be printed verbatim in a user
74
+ // message (`preserveBackslashEscapes`), so nothing is styled there.
75
+ assert.ok(!output.includes(ESCAPE));
76
+ });
77
+
78
+ test("the pipeline: thinking text is exactly what the fence labeling produced", () => {
79
+ const markdown = "# Title\n\n> quoted\n";
80
+ const output = transformerFor(fakeTheme().theme)(markdown, context("assistant-thinking"));
81
+ assert.equal(output, transformFenceLanguages(markdown));
82
+ });
83
+
84
+ test("the pipeline: with no captured theme the message is only fence labeled", () => {
85
+ const markdown = "# Title\n\n```\n{\n \"name\": \"pi\"\n}\n```\n";
86
+ const output = transformerFor(undefined)(markdown, context("assistant"));
87
+ assert.equal(output, transformFenceLanguages(markdown));
88
+ assert.ok(output.includes("```json"));
89
+ assert.ok(!output.includes(ESCAPE));
90
+ });
91
+
92
+ test("the pipeline: a theme that throws keeps the fence labeling", () => {
93
+ const markdown = "```\n{\n \"name\": \"pi\"\n}\n```\n\n# Title\n";
94
+ const transformer = createMarkdownTransformer({
95
+ resolveTheme: () => {
96
+ throw new Error("Theme not initialized. Call initTheme() first.");
97
+ },
98
+ });
99
+ const output = transformer(markdown, context("assistant"));
100
+ assert.equal(output, transformFenceLanguages(markdown));
101
+ assert.ok(output.startsWith("```json"));
102
+ assert.ok(!output.includes(ESCAPE));
103
+ });
104
+
105
+ test("the pipeline: no injected sequence stays open past its line", () => {
106
+ const markdown = "# Title\n\n> quoted `code`\n\n#### Four\n\n- item `x`\n";
107
+ const output = transformerFor(fakeTheme().theme)(markdown, context("assistant"));
108
+ assertClosedPerLine(output);
109
+ });
110
+
111
+ test("the pipeline: an unclosed fence leaves the rest of the message alone", () => {
112
+ const markdown = "```js\n# not a heading\n> not a quote\n";
113
+ // Streaming: the fence has no closing line yet, so its body is only a prefix of
114
+ // the final one and styling it would flicker as the stream grows.
115
+ assert.equal(transformerFor(fakeTheme().theme)(markdown, context("assistant")), markdown);
116
+ });
117
+
118
+ test("the pipeline: a lone backtick leaves its line alone", () => {
119
+ const markdown = "Run `npm test\n";
120
+ assert.equal(transformerFor(fakeTheme().theme)(markdown, context("assistant")), markdown);
121
+ });
122
+
123
+ test("the pipeline: a heading still streaming keeps its style as the text grows", () => {
124
+ const transformer = transformerFor(fakeTheme().theme);
125
+ const closes = `${UNDERLINE_OFF}${FG_DEFAULT}`;
126
+ assert.equal(transformer("## ", context("assistant")), "## ");
127
+ const partial = transformer("## Tit", context("assistant"));
128
+ assert.ok(partial.startsWith(`## ${ACCENT}${UNDERLINE_ON}Tit`));
129
+ assert.ok(partial.endsWith(closes));
130
+ assert.ok(transformer("## Titl", context("assistant")).endsWith(closes));
131
+ });
132
+
133
+ test("the pipeline: the memo is keyed by the palette signature", () => {
134
+ const { theme, ansi } = fakeTheme();
135
+ const transformer = transformerFor(theme);
136
+ const markdown = "# Title\n";
137
+ assert.ok(transformer(markdown, context("assistant")).includes(ACCENT));
138
+ ansi.accent = NEXT_ACCENT;
139
+ const restyled = transformer(markdown, context("assistant"));
140
+ assert.ok(restyled.includes(NEXT_ACCENT));
141
+ assert.ok(!restyled.includes(ACCENT));
142
+ });
143
+
144
+ test("the pipeline: a theme change the pass cannot see keeps the memoized render", () => {
145
+ const { theme, ansi } = fakeTheme();
146
+ const transformer = transformerFor(theme);
147
+ const markdown = "# Title\n";
148
+ const first = transformer(markdown, context("assistant"));
149
+ // A token the pass never reads: the injected sequences are byte identical, so
150
+ // there is nothing to recompute.
151
+ ansi.warning = "\x1b[38;5;3m";
152
+ assert.equal(transformer(markdown, context("assistant")), first);
153
+ });
@@ -0,0 +1,127 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { getMarkdownTheme, initTheme } from "@earendil-works/pi-coding-agent";
4
+ import { Markdown, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { createMarkdownTransformer } from "../../src/markdown-fence-lang.ts";
6
+ import { markdownPalette } from "../../src/markdown-theme.ts";
7
+ import { ITALIC_OFF, ITALIC_ON, type AnsiTheme } from "../../src/tokens.ts";
8
+
9
+ // The theme the host renders with lives on `globalThis` under this symbol and is the
10
+ // same object an extension receives as `ctx.ui.theme`; reading it is the only way to
11
+ // hand the transformer the colors the renderer below actually uses.
12
+ const HOST_THEME_KEY = Symbol.for("@earendil-works/pi-coding-agent:theme");
13
+
14
+ initTheme("system");
15
+ const hostTheme = (globalThis as unknown as Record<symbol, AnsiTheme>)[HOST_THEME_KEY];
16
+
17
+ const WIDTH = 100;
18
+
19
+ // One transformer for the whole file, like the extension registers: the memo is the
20
+ // only state it has and every render below goes through it.
21
+ const transformer = createMarkdownTransformer({ resolveTheme: () => hostTheme });
22
+
23
+ function transform(markdown: string): string {
24
+ return transformer(markdown, { messageType: "assistant", isStreaming: false, availableWidth: WIDTH });
25
+ }
26
+
27
+ // The markdown component the assistant message builds: no padding, no default text
28
+ // style, and the transformer only on the styled side.
29
+ function renderLines(markdown: string, styled: boolean): string[] {
30
+ const options = styled ? { transform } : undefined;
31
+ return new Markdown(markdown, 0, 0, getMarkdownTheme(), undefined, options).render(WIDTH);
32
+ }
33
+
34
+ function withoutBackticks(line: string): string {
35
+ return line.replace(/`/g, "");
36
+ }
37
+
38
+ function trimEnd(line: string): string {
39
+ return line.trimEnd();
40
+ }
41
+
42
+ function occurrences(text: string, part: string): number {
43
+ return text.split(part).length - 1;
44
+ }
45
+
46
+ // The corpus covers every construct the pass touches plus the ones it must leave
47
+ // alone. Every fence is labeled on purpose: an unlabeled one is relabeled by the
48
+ // fence stage, which is a visible change that stage owns and this contract does not.
49
+ const CORPUS: ReadonlyArray<{ name: string; markdown: string }> = [
50
+ {
51
+ name: "headings",
52
+ markdown: "# One\n\n## Two\n\n### Three\n\n#### Four\n\n##### Five\n\n###### Six\n",
53
+ },
54
+ { name: "quotes", markdown: "> quoted text\n>\n> > nested quote\n> second line\n" },
55
+ { name: "lists", markdown: "- one\n- two with `code`\n - nested\n\n1. first\n2. second\n" },
56
+ { name: "table", markdown: "| key | value |\n| --- | --- |\n| a | b |\n" },
57
+ { name: "inline styles", markdown: "Some **bold**, *italic*, ~~struck~~ and `code` in one line.\n" },
58
+ { name: "links", markdown: "See [the docs](https://example.com) and the [other `one`](https://example.org).\n" },
59
+ { name: "js fence", markdown: "```js\nconst x = 1;\n```\n" },
60
+ { name: "mermaid fence", markdown: "```mermaid\ngraph TD;\n A-->B;\n```\n" },
61
+ { name: "math fence", markdown: "```math\nx^2 + y^2\n```\n" },
62
+ { name: "inline math", markdown: "The value $x^2$ stays inline.\n" },
63
+ {
64
+ name: "code spans in every context",
65
+ markdown: "# Heading with `code`\n\n> quote with `code`\n\n- item with `code`\n\nText with `code` and `--flag`.\n",
66
+ },
67
+ ];
68
+
69
+ test("the rendered transcript keeps every visible character of the untransformed one", () => {
70
+ for (const item of CORPUS) {
71
+ const plain = renderLines(item.markdown, false);
72
+ const transformed = renderLines(item.markdown, true);
73
+ assert.equal(transformed.length, plain.length, item.name);
74
+ const stripped = transformed.map(stripTerminalSequences);
75
+ const expected = plain.map(stripTerminalSequences);
76
+ // The restored delimiters of the inline code spans are the only visible
77
+ // difference the pass is allowed to make. Right padding is layout, not text:
78
+ // a line carrying two extra visible characters keeps the same total width and
79
+ // therefore two spaces less, so the comparison is over trimmed lines.
80
+ assert.deepEqual(stripped.map(withoutBackticks).map(trimEnd), expected.map(withoutBackticks).map(trimEnd), item.name);
81
+ stripped.forEach((line, index) => {
82
+ const plainLine = expected[index] ?? "";
83
+ // Sequences take no column: the width the renderer measures for the styled
84
+ // line is the width of its text, which is the untouched line plus the ticks.
85
+ assert.equal(visibleWidth(transformed[index] ?? ""), visibleWidth(line), item.name);
86
+ const added = occurrences(line, "`") - occurrences(plainLine, "`");
87
+ // Padding equalizes both widths, so the column difference the delimiters add
88
+ // is only observable on the trimmed lines.
89
+ assert.equal(visibleWidth(line.trimEnd()), visibleWidth(plainLine.trimEnd()) + added, item.name);
90
+ });
91
+ }
92
+ });
93
+
94
+ test("every code span of the corpus comes back with its delimiters", () => {
95
+ const stripped = renderLines(CORPUS[CORPUS.length - 1]?.markdown ?? "", true)
96
+ .map(stripTerminalSequences)
97
+ .join("\n");
98
+ assert.ok(stripped.includes("`code`"));
99
+ assert.ok(stripped.includes("`--flag`"));
100
+ });
101
+
102
+ test("the transformer injects the palette the live theme yields", () => {
103
+ const palette = markdownPalette(hostTheme);
104
+ const transformed = transform("# Title\n\n> quoted\n");
105
+ // The attributes travel whatever the theme resolves the colors to, so these hold
106
+ // even in a monochrome terminal, where the token maps to the default color.
107
+ assert.ok(transformed.includes(`${ITALIC_ON}Title`));
108
+ assert.ok(transformed.includes(ITALIC_OFF));
109
+ assert.ok(!transformed.includes("\u001b[0m"));
110
+ if (palette.accent !== "") assert.ok(transformed.includes(palette.accent));
111
+ if (palette.quoteOpen !== "") assert.ok(transformed.includes(palette.quoteOpen));
112
+ });
113
+
114
+ test("a table cell with a code span keeps its text and only moves its columns", () => {
115
+ const markdown = "| key | value |\n| --- | --- |\n| a | `b` |\n";
116
+ const plain = renderLines(markdown, false).map(stripTerminalSequences);
117
+ const styled = renderLines(markdown, true).map(stripTerminalSequences);
118
+ // The restored ticks make one cell two columns wider and the renderer measures the
119
+ // cell to lay the table out, so the padding moves. The content does not: taking the
120
+ // padding and the ticks out of both renders leaves the same characters, and this is
121
+ // the only construct where the two renders differ by more than the delimiters.
122
+ assert.equal(
123
+ styled.join("\n").replace(/[` ]/g, ""),
124
+ plain.join("\n").replace(/[` ]/g, ""),
125
+ );
126
+ assert.ok(styled.join("\n").includes("`b`"));
127
+ });
@@ -0,0 +1,152 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { styleMarkdown } from "../../src/markdown-style.ts";
4
+ import type { MarkdownPalette } from "../../src/markdown-theme.ts";
5
+ import {
6
+ DIM_OFF,
7
+ DIM_ON,
8
+ FG_DEFAULT,
9
+ ITALIC_OFF,
10
+ ITALIC_ON,
11
+ UNDERLINE_OFF,
12
+ UNDERLINE_ON,
13
+ } from "../../src/tokens.ts";
14
+
15
+ const ACCENT = "\x1b[38;5;5m";
16
+ const QUOTE_OPEN = DIM_OFF + ACCENT;
17
+ const QUOTE_CLOSE = FG_DEFAULT + DIM_ON;
18
+
19
+ // The pass receives the palette as a value, so every case reads as arithmetic on
20
+ // the sequences instead of depending on a theme.
21
+ const palette: MarkdownPalette = {
22
+ accent: ACCENT,
23
+ quoteOpen: QUOTE_OPEN,
24
+ quoteClose: QUOTE_CLOSE,
25
+ signature: [ACCENT, QUOTE_OPEN, QUOTE_CLOSE].join("\u0000"),
26
+ };
27
+
28
+ // A monochrome theme: no color, so only the attributes are left to inject.
29
+ const COLORLESS: MarkdownPalette = { accent: "", quoteOpen: "", quoteClose: "", signature: "" };
30
+
31
+ function style(markdown: string, selected: MarkdownPalette = palette): string {
32
+ return styleMarkdown(markdown, selected);
33
+ }
34
+
35
+ test("styleMarkdown: an inline code span gets its delimiters back as escaped text", () => {
36
+ assert.equal(style("Run `npm test` first"), "Run \\`npm test\\` first");
37
+ });
38
+
39
+ test("styleMarkdown: every code span of a line is restored", () => {
40
+ assert.equal(style("`a` and `b`"), "\\`a\\` and \\`b\\`");
41
+ });
42
+
43
+ test("styleMarkdown: a code span is restored inside a list item, a link and a table cell", () => {
44
+ assert.equal(style("- use `tsc` here"), "- use \\`tsc\\` here");
45
+ assert.equal(style("[the `--watch` flag](https://example.com)"), "[the \\`--watch\\` flag](https://example.com)");
46
+ assert.equal(style("| `a` | b |"), "| \\`a\\` | b |");
47
+ });
48
+
49
+ test("styleMarkdown: a code span inside a quote keeps the quote pair around it", () => {
50
+ assert.equal(style("> run `x` now"), `> ${QUOTE_OPEN}run \\\`x\\\` now${QUOTE_CLOSE}`);
51
+ });
52
+
53
+ test("styleMarkdown: a code span inside a heading keeps the heading style around it", () => {
54
+ assert.equal(
55
+ style("## Run `x`"),
56
+ `## ${ACCENT}${UNDERLINE_ON}Run \\\`x\\\`${UNDERLINE_OFF}${FG_DEFAULT}`,
57
+ );
58
+ });
59
+
60
+ test("styleMarkdown: an already escaped backtick leaves the line alone", () => {
61
+ // The model wrote the delimiters itself: escaping them again would print the
62
+ // backslashes and lose the span.
63
+ assert.equal(style("Run \\`npm test\\` first"), "Run \\`npm test\\` first");
64
+ });
65
+
66
+ test("styleMarkdown: a span whose text ends in a backslash leaves the line alone", () => {
67
+ assert.equal(style("Run `a\\` now"), "Run `a\\` now");
68
+ });
69
+
70
+ test("styleMarkdown: a lone backtick leaves the line alone until its pair arrives", () => {
71
+ assert.equal(style("Run `npm test first"), "Run `npm test first");
72
+ });
73
+
74
+ test("styleMarkdown: a multi-backtick span is not touched", () => {
75
+ assert.equal(style("Use ``a`b`` here"), "Use ``a`b`` here");
76
+ });
77
+
78
+ test("styleMarkdown: a code span inside a fence body is not touched", () => {
79
+ const markdown = "```md\nRun `npm test` first\n```\n";
80
+ assert.equal(style(markdown), markdown);
81
+ });
82
+
83
+ test("styleMarkdown: every heading level takes the accent and the level decides the attribute", () => {
84
+ assert.equal(style("# Title"), `# ${ACCENT}${ITALIC_ON}Title${ITALIC_OFF}${FG_DEFAULT}`);
85
+ assert.equal(style("## Title"), `## ${ACCENT}${UNDERLINE_ON}Title${UNDERLINE_OFF}${FG_DEFAULT}`);
86
+ assert.equal(style("### Title"), `### ${ACCENT}${ITALIC_ON}Title${ITALIC_OFF}${FG_DEFAULT}`);
87
+ // h4-h6 add no attribute: the host keeps them bold and the renderer prints their
88
+ // `#` prefix, which is what tells them apart.
89
+ assert.equal(style("#### Title"), `#### ${ACCENT}Title${FG_DEFAULT}`);
90
+ assert.equal(style("##### Title"), `##### ${ACCENT}Title${FG_DEFAULT}`);
91
+ assert.equal(style("###### Title"), `###### ${ACCENT}Title${FG_DEFAULT}`);
92
+ });
93
+
94
+ test("styleMarkdown: a heading takes the accent without re-injecting it after an inline span", () => {
95
+ const styled = style("# **bold** tail");
96
+ assert.equal(styled, `# ${ACCENT}${ITALIC_ON}**bold** tail${ITALIC_OFF}${FG_DEFAULT}`);
97
+ // Accepted behaviour of the injected route: the host re-opens its own heading
98
+ // color after the bold run, so the accent appears once, never after the inline.
99
+ assert.equal(styled.split(ACCENT).length - 1, 1);
100
+ });
101
+
102
+ test("styleMarkdown: an empty heading is not touched", () => {
103
+ assert.equal(style("## "), "## ");
104
+ assert.equal(style("##"), "##");
105
+ });
106
+
107
+ test("styleMarkdown: a heading inside a fence body is not touched", () => {
108
+ const markdown = "```md\n# Title\n```\n";
109
+ assert.equal(style(markdown), markdown);
110
+ });
111
+
112
+ test("styleMarkdown: setext headings are not touched", () => {
113
+ const markdown = "Title\n=====\n";
114
+ assert.equal(style(markdown), markdown);
115
+ });
116
+
117
+ test("styleMarkdown: up to three spaces of indentation still open a heading", () => {
118
+ assert.equal(style(" # Title"), ` # ${ACCENT}${ITALIC_ON}Title${ITALIC_OFF}${FG_DEFAULT}`);
119
+ // Four spaces are an indented code block, so the line is body text.
120
+ assert.equal(style(" # Title"), " # Title");
121
+ });
122
+
123
+ test("styleMarkdown: a quote line wraps its text in the quote pair after every marker", () => {
124
+ assert.equal(style("> quoted"), `> ${QUOTE_OPEN}quoted${QUOTE_CLOSE}`);
125
+ assert.equal(style("> > nested"), `> > ${QUOTE_OPEN}nested${QUOTE_CLOSE}`);
126
+ });
127
+
128
+ test("styleMarkdown: each line of a multi-line quote gets its own pair", () => {
129
+ assert.equal(style("> one\n> two"), `> ${QUOTE_OPEN}one${QUOTE_CLOSE}\n> ${QUOTE_OPEN}two${QUOTE_CLOSE}`);
130
+ });
131
+
132
+ test("styleMarkdown: a quote line with no text is not touched", () => {
133
+ assert.equal(style(">"), ">");
134
+ assert.equal(style("> "), "> ");
135
+ });
136
+
137
+ test("styleMarkdown: a monochrome theme keeps the heading attributes and drops the colors", () => {
138
+ assert.equal(style("# Title", COLORLESS), `# ${ITALIC_ON}Title${ITALIC_OFF}`);
139
+ assert.equal(style("## Title", COLORLESS), `## ${UNDERLINE_ON}Title${UNDERLINE_OFF}`);
140
+ // Nothing left to inject at all, so the line is returned exactly as it came.
141
+ assert.equal(style("#### Title", COLORLESS), "#### Title");
142
+ assert.equal(style("> quoted", COLORLESS), "> quoted");
143
+ });
144
+
145
+ test("styleMarkdown: a second pass over the same text changes nothing", () => {
146
+ const markdown = "# Title\n\n> quote with `code`\n\n- item `x`\n\n```js\nconst x = 1;\n```\n";
147
+ const once = style(markdown);
148
+ assert.notEqual(once, markdown);
149
+ // The guard for lines that already carry a sequence is what makes this hold: a
150
+ // restyle would nest the previous pair inside the new one.
151
+ assert.equal(style(once), once);
152
+ });
@@ -0,0 +1,86 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { markdownPalette } from "../../src/markdown-theme.ts";
4
+ import { DIM_OFF, DIM_ON, FG_DEFAULT, type AnsiTheme } from "../../src/tokens.ts";
5
+
6
+ const ACCENT = "\x1b[38;5;5m";
7
+ const QUOTE_COLOR = "\x1b[38;5;8m";
8
+ const OTHER_QUOTE_COLOR = "\x1b[38;5;1m";
9
+
10
+ // A theme whose sequences live in a mutable map, like the host's: a theme switch
11
+ // changes the values under the same object, so a fake that returned fixed literals
12
+ // could not show the signature moving.
13
+ function fakeTheme(overrides: Record<string, string> = {}): { theme: AnsiTheme; ansi: Record<string, string> } {
14
+ const ansi: Record<string, string> = { accent: ACCENT, mdQuote: FG_DEFAULT + DIM_ON, ...overrides };
15
+ return {
16
+ ansi,
17
+ theme: {
18
+ getFgAnsi: (color) => ansi[color] ?? "",
19
+ getBgAnsi: () => "",
20
+ },
21
+ };
22
+ }
23
+
24
+ test("markdownPalette: the heading accent is the theme's foreground for the accent token", () => {
25
+ assert.equal(markdownPalette(fakeTheme().theme).accent, ACCENT);
26
+ });
27
+
28
+ test("markdownPalette: a faint quote turns dim off while it opens and restores it when it closes", () => {
29
+ const palette = markdownPalette(fakeTheme().theme);
30
+ assert.equal(palette.quoteOpen, DIM_OFF + ACCENT);
31
+ // `\x1b[22m` closes bold along with dim, which is why the close puts the theme's
32
+ // own faint back instead of leaving the line brighter than the host painted it.
33
+ assert.equal(palette.quoteClose, FG_DEFAULT + DIM_ON);
34
+ });
35
+
36
+ test("markdownPalette: a quote that is not faint opens with the color alone", () => {
37
+ const palette = markdownPalette(fakeTheme({ mdQuote: QUOTE_COLOR }).theme);
38
+ assert.equal(palette.quoteOpen, ACCENT);
39
+ assert.equal(palette.quoteClose, FG_DEFAULT);
40
+ });
41
+
42
+ test("markdownPalette: a token that resolves to the terminal default adds no color", () => {
43
+ // The host maps a token with no color of its own to 39, and wrapping text in that
44
+ // sequence only cancels the style the surrounding line already has.
45
+ assert.equal(markdownPalette(fakeTheme({ accent: "" }).theme).accent, "");
46
+ assert.equal(markdownPalette(fakeTheme({ accent: FG_DEFAULT }).theme).accent, "");
47
+ });
48
+
49
+ test("markdownPalette: a colorless quote injects no pair at all", () => {
50
+ const palette = markdownPalette(fakeTheme({ accent: FG_DEFAULT }).theme);
51
+ assert.equal(palette.quoteOpen, "");
52
+ assert.equal(palette.quoteClose, "");
53
+ });
54
+
55
+ test("markdownPalette: the signature is stable while the sequences are", () => {
56
+ const { theme } = fakeTheme();
57
+ const first = markdownPalette(theme);
58
+ assert.equal(markdownPalette(theme).signature, first.signature);
59
+ // The signature is the concatenation of what the pass injects, so two palettes
60
+ // with the same one cannot produce different bytes.
61
+ assert.equal(first.signature, [first.accent, first.quoteOpen, first.quoteClose].join("\u0000"));
62
+ });
63
+
64
+ test("markdownPalette: the signature follows the accent when the theme changes", () => {
65
+ const { theme, ansi } = fakeTheme();
66
+ const before = markdownPalette(theme).signature;
67
+ ansi.accent = "\x1b[38;5;6m";
68
+ assert.notEqual(markdownPalette(theme).signature, before);
69
+ });
70
+
71
+ test("markdownPalette: the signature follows the faint flag of the quote", () => {
72
+ const { theme, ansi } = fakeTheme();
73
+ const before = markdownPalette(theme).signature;
74
+ ansi.mdQuote = QUOTE_COLOR;
75
+ assert.notEqual(markdownPalette(theme).signature, before);
76
+ });
77
+
78
+ test("markdownPalette: a change the pass cannot see leaves the signature alone", () => {
79
+ const { theme, ansi } = fakeTheme({ mdQuote: QUOTE_COLOR });
80
+ const before = markdownPalette(theme).signature;
81
+ // Another color, same faint flag: the injected sequences are byte identical, so
82
+ // invalidating a memoized render over it would be wasted work.
83
+ ansi.mdQuote = OTHER_QUOTE_COLOR;
84
+ ansi.warning = "\x1b[38;5;3m";
85
+ assert.equal(markdownPalette(theme).signature, before);
86
+ });