pi-syntax-highlight 0.1.0 → 0.2.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 (47) hide show
  1. package/CHANGELOG.md +81 -40
  2. package/DEVELOPER.md +100 -0
  3. package/LICENSE +21 -0
  4. package/README.md +42 -44
  5. package/extensions/index.ts +5 -10
  6. package/package.json +20 -5
  7. package/src/detect-language.ts +205 -8
  8. package/src/emphasis.ts +82 -1
  9. package/src/highlight.ts +25 -9
  10. package/src/lru-cache.ts +30 -0
  11. package/src/markdown-fence-lang.ts +20 -87
  12. package/src/render-bash.ts +29 -2
  13. package/src/render-edit.ts +0 -6
  14. package/src/render-generic.ts +10 -21
  15. package/src/render-read.ts +8 -149
  16. package/src/render-utils.ts +8 -17
  17. package/src/resolve-renderers.ts +181 -240
  18. package/src/tokens.ts +1 -34
  19. package/src/active-theme.ts +0 -26
  20. package/src/markdown-style.ts +0 -134
  21. package/src/markdown-theme.ts +0 -53
  22. package/src/render-path.ts +0 -54
  23. package/src/render-write.ts +0 -81
  24. package/test/unit/active-theme.test.ts +0 -38
  25. package/test/unit/bash-preview.test.ts +0 -57
  26. package/test/unit/detect-language.test.ts +0 -124
  27. package/test/unit/emphasis.test.ts +0 -113
  28. package/test/unit/extensions-index.test.ts +0 -116
  29. package/test/unit/grep-parse.test.ts +0 -125
  30. package/test/unit/highlight.test.ts +0 -107
  31. package/test/unit/markdown-fence-lang.test.ts +0 -131
  32. package/test/unit/markdown-pipeline.test.ts +0 -153
  33. package/test/unit/markdown-render-parity.test.ts +0 -127
  34. package/test/unit/markdown-style.test.ts +0 -152
  35. package/test/unit/markdown-theme.test.ts +0 -86
  36. package/test/unit/render-bash.test.ts +0 -194
  37. package/test/unit/render-edit.test.ts +0 -214
  38. package/test/unit/render-find.test.ts +0 -139
  39. package/test/unit/render-generic.test.ts +0 -152
  40. package/test/unit/render-grep.test.ts +0 -338
  41. package/test/unit/render-ls.test.ts +0 -132
  42. package/test/unit/render-read.test.ts +0 -375
  43. package/test/unit/render-utils.test.ts +0 -324
  44. package/test/unit/render-write.test.ts +0 -143
  45. package/test/unit/resolve-renderers.test.ts +0 -474
  46. package/test/unit/style-path.test.ts +0 -74
  47. package/tsconfig.json +0 -15
@@ -1,37 +1,20 @@
1
1
  import type { MarkdownTransformer } from "@earendil-works/pi-coding-agent";
2
2
  import { detectLanguage } from "./detect-language.ts";
3
- import { markdownPalette, type MarkdownPalette } from "./markdown-theme.ts";
4
- import { styleMarkdown } from "./markdown-style.ts";
5
- import type { AnsiTheme } from "./tokens.ts";
6
-
7
- // Fences the built-in mermaid transformer already consumed: by the
8
- // time this transformer runs, that one has rewritten the block, and guessing a
9
- // language from a diagram body would repaint it as something else entirely.
10
- const RESERVED_INFO = new Set(["mermaid", "math", "latex", "katex"]);
3
+ import { LruCache } from "./lru-cache.ts";
11
4
 
12
5
  // CommonMark allows up to three spaces of indentation; four spaces open an
13
6
  // indented code block and a blockquote prefix is not a fence at all, so neither
14
7
  // matches here and both are copied untouched.
15
8
  const OPENING_FENCE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
16
9
 
17
- // Exported so the styling pass scans fences with the very same grammar instead of
18
- // keeping a second copy of it: two scanners would eventually disagree about what a
19
- // fence is, and the disagreement would paint body text as markdown.
20
- export interface OpeningFence {
10
+ const MEMO_SIZE = 32;
11
+
12
+ interface OpeningFence {
21
13
  indent: string;
22
14
  fence: string;
23
15
  info: string;
24
16
  }
25
17
 
26
- // The info string carries either the language, an attribute list such as
27
- // `{.ts}`, or the language followed by attributes such as `js title="a"`.
28
- // A token the author wrote is returned as it is: rewriting a correctly labeled
29
- // fence is a visible difference, and an unknown name is still their choice. Only
30
- // an unlabeled fence is worth a guess.
31
- export function normalizeInfoString(info: string, body: string): string {
32
- return normalizeToken(cleanInfoToken(info), body);
33
- }
34
-
35
18
  // Only the opening line of a closed fence is rewritten; an open fence is still
36
19
  // arriving, so its body is only a prefix of the final one.
37
20
  export function transformFenceLanguages(markdown: string): string {
@@ -61,72 +44,37 @@ export function transformFenceLanguages(markdown: string): string {
61
44
  return output.join("\n");
62
45
  }
63
46
 
64
- export interface MarkdownTransformerOptions {
65
- // Read at render time rather than captured at load time: the extension registers
66
- // before any session exists, and the object the host hands out is a proxy whose
67
- // reads resolve against the theme in effect, so one captured reference stays
68
- // valid across a theme switch.
69
- resolveTheme: () => AnsiTheme | undefined;
70
- }
71
-
72
47
  // `Markdown.render` invokes the transformer on every cache miss, and a resize or
73
48
  // a theme change invalidates that cache, so the same markdown arrives again and
74
- // again. One entry is enough: the transcript renders one message at a time. The
75
- // key carries the palette signature because a theme switch changes the output
76
- // without changing the input; the width is not part of it because no stage reads it.
77
- export function createMarkdownTransformer(options: MarkdownTransformerOptions): MarkdownTransformer {
78
- let memo: { input: string; signature: string; output: string } | undefined;
79
- return (markdown, context) => {
80
- // Only assistant prose is styled: a user message renders its backslash escapes
81
- // verbatim (`user-message.js` sets `preserveBackslashEscapes`), which would make
82
- // the restored code-span delimiters visible, and thinking text is painted with an
83
- // italic default style this pass would degrade.
84
- const palette = context.messageType === "assistant" ? paletteOrUndefined(options.resolveTheme) : undefined;
85
- const signature = palette?.signature ?? "";
86
- if (memo !== undefined && memo.input === markdown && memo.signature === signature) return memo.output;
49
+ // again. The transcript holds several messages, hence a small LRU; the width is not
50
+ // part of the key because no stage reads it.
51
+ export function createMarkdownTransformer(): MarkdownTransformer {
52
+ const memo = new LruCache<string, string>(MEMO_SIZE);
53
+ return (markdown) => {
54
+ const cached = memo.get(markdown);
55
+ if (cached !== undefined) return cached;
87
56
  let output = markdown;
88
57
  try {
89
58
  output = transformFenceLanguages(markdown);
90
59
  } catch {
91
60
  // A fence this module cannot parse must not take the message down: the
92
61
  // original markdown still renders with flat colors.
93
- output = markdown;
94
- }
95
- if (palette !== undefined) {
96
- try {
97
- output = styleMarkdown(output, palette);
98
- } catch {
99
- // Styling is the optional half of the pipeline: the fence labels above are
100
- // already in `output` and stay, so a failure costs the colors and nothing else.
101
- }
102
62
  }
103
- memo = { input: markdown, signature, output };
63
+ memo.set(markdown, output);
104
64
  return output;
105
65
  };
106
66
  }
107
67
 
108
- // The derivation is the one step that can fail: `resolveTheme` answers `undefined`
109
- // before a theme is captured, and the host's theme throws while uninitialized
110
- // (`theme.js` reads `globalThis` and throws when nothing is installed). Neither may
111
- // reach the renderer, so no palette means no styling instead of no message.
112
- function paletteOrUndefined(resolveTheme: () => AnsiTheme | undefined): MarkdownPalette | undefined {
113
- try {
114
- const theme = resolveTheme();
115
- return theme === undefined ? undefined : markdownPalette(theme);
116
- } catch {
117
- return undefined;
118
- }
119
- }
120
-
68
+ // An info string the author wrote is copied byte for byte, whatever the body
69
+ // looks like: detection only fills the gap of an empty one, and a body that
70
+ // already carries escape sequences is not source code to guess a grammar for.
121
71
  function rewriteOpeningFence(line: string, opening: OpeningFence, body: string): string {
122
- const token = cleanInfoToken(opening.info);
123
- if (RESERVED_INFO.has(token.toLowerCase())) return line;
124
- const language = normalizeToken(token, body);
125
- if (language === opening.info) return line;
126
- return `${opening.indent}${opening.fence}${language}`;
72
+ if (opening.info !== "" || body.includes("\x1b")) return line;
73
+ const language = detectLanguage(body);
74
+ return language === undefined ? line : `${opening.indent}${opening.fence}${language}`;
127
75
  }
128
76
 
129
- export function parseOpeningFence(line: string): OpeningFence | undefined {
77
+ function parseOpeningFence(line: string): OpeningFence | undefined {
130
78
  const matched = OPENING_FENCE.exec(line);
131
79
  if (matched === null) return undefined;
132
80
  const fence = matched[2] ?? "";
@@ -147,7 +95,7 @@ function findClosingFence(lines: readonly string[], start: number, opening: Open
147
95
 
148
96
  // A closing fence is the opening character repeated at least as many times as the
149
97
  // opener, indented at most three spaces, with nothing but spaces after it.
150
- export function isClosingFence(line: string, opening: OpeningFence): boolean {
98
+ function isClosingFence(line: string, opening: OpeningFence): boolean {
151
99
  return closingFencePattern(opening).test(line);
152
100
  }
153
101
 
@@ -163,18 +111,3 @@ function closingFencePattern(opening: OpeningFence): RegExp {
163
111
  function appendLines(target: string[], source: readonly string[], start: number, end: number): void {
164
112
  for (const line of source.slice(start, end + 1)) target.push(line);
165
113
  }
166
-
167
- // Detection only fills a gap: a label the author wrote is returned whatever the
168
- // body looks like.
169
- function normalizeToken(token: string, body: string): string {
170
- if (token !== "") return token;
171
- return detectLanguage(body) ?? "";
172
- }
173
-
174
- function cleanInfoToken(info: string): string {
175
- const first = info.trim().split(/\s+/)[0] ?? "";
176
- // `{.ts}`, `{ts,}`, and a bare `.ts` name the same language; the attributes
177
- // after the language (`js title="a"`) were cut by the split.
178
- const unwrapped = first.startsWith("{") ? first.slice(1) : first;
179
- return unwrapped.replace(/^\.+/, "").replace(/[`,}]+$/, "");
180
- }
@@ -1,7 +1,8 @@
1
1
  import { truncateToVisualLines } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth, type Component } from "@earendil-works/pi-tui";
3
+ import { detectOutputLanguage } from "./detect-language.ts";
3
4
  import { parseGrepLine } from "./grep-parse.ts";
4
- import { highlight as builtInHighlight, highlightLines, type HighlightFn } from "./highlight.ts";
5
+ import { HIGHLIGHT_LINE_BUDGET, highlight as builtInHighlight, highlightLines, type HighlightFn } from "./highlight.ts";
5
6
  import { DIFF_HEADER, colonPrefix, isJsonDocument, styleDiffLine, truncationWarnings } from "./render-utils.ts";
6
7
  import { TOKEN, type StyleTheme } from "./tokens.ts";
7
8
 
@@ -79,6 +80,15 @@ function isDiffOutput(lines: string[]): boolean {
79
80
  return hunks > 0 || changes > 1;
80
81
  }
81
82
 
83
+ // Detection reads the same lines the tokenizer will paint: past the budget the
84
+ // body falls back to the plain color, so a signal from there would not change a
85
+ // painted line. The head is the sample because a document announces its language
86
+ // at the top.
87
+ function detectionSample(lines: string[]): string {
88
+ const head = lines.length <= HIGHLIGHT_LINE_BUDGET ? lines : lines.slice(0, HIGHLIGHT_LINE_BUDGET);
89
+ return head.join("\n");
90
+ }
91
+
82
92
  // Commands that print compiler or test output repeat grep's "path:line: text"
83
93
  // shape, so it is parsed with the same function instead of a second regex.
84
94
  function styleLine(line: string, theme: StyleTheme): string {
@@ -90,6 +100,21 @@ function styleLine(line: string, theme: StyleTheme): string {
90
100
  return `${colonPrefix(path, entry.line, theme)} ${theme.fg(TOKEN.content, entry.text)}`;
91
101
  }
92
102
 
103
+ // The three shapes the flat path colors by hand. A grammar has no red for
104
+ // `npm ERR!`, so those lines keep what they get today.
105
+ function classifies(line: string): boolean {
106
+ return ERROR_LINE.test(line) || WARNING_LINE.test(line) || parseGrepLine(line).kind === "match";
107
+ }
108
+
109
+ function styleDetectedLines(lines: string[], language: string, theme: StyleTheme, highlight: HighlightFn): string[] {
110
+ const fallback = (line: string): string => theme.fg(TOKEN.content, line);
111
+ const painted = highlightLines(lines.join("\n"), language, fallback, highlight, HIGHLIGHT_LINE_BUDGET);
112
+ // A painted line cannot be recolored from the inside, so a classified
113
+ // line replaces the highlighted one instead of being wrapped. `highlightLines` splits the same code, which is what keeps
114
+ // the two arrays aligned.
115
+ return painted.map((line, index) => (classifies(lines[index]) ? styleLine(lines[index], theme) : line));
116
+ }
117
+
93
118
  function styleOutput(output: string, theme: StyleTheme, highlight: HighlightFn): string {
94
119
  const lines = output.split("\n");
95
120
  if (isDiffOutput(lines)) return lines.map((line) => styleDiffLine(line, theme)).join("\n");
@@ -97,8 +122,10 @@ function styleOutput(output: string, theme: StyleTheme, highlight: HighlightFn):
97
122
  // Whole-block highlighting keeps keys, strings and numbers distinct; the
98
123
  // fallback protects readers when the tokenizer throws.
99
124
  const fallback = (line: string): string => theme.fg(TOKEN.content, line);
100
- return highlightLines(output, "json", fallback, highlight).join("\n");
125
+ return highlightLines(output, "json", fallback, highlight, HIGHLIGHT_LINE_BUDGET).join("\n");
101
126
  }
127
+ const language = detectOutputLanguage(detectionSample(lines));
128
+ if (language !== undefined) return styleDetectedLines(lines, language, theme, highlight).join("\n");
102
129
  return lines.map((line) => styleLine(line, theme)).join("\n");
103
130
  }
104
131
 
@@ -199,9 +199,3 @@ export function buildEditDiffText(input: EditDiffInput): string {
199
199
  }
200
200
  return styled.join("\n");
201
201
  }
202
-
203
- // The body the built-in paints inside the call's `Box`: the failure text in the
204
- // error color, with no newline of its own because the box adds the gap.
205
- export function buildEditErrorText(output: string, theme: StyleTheme): string {
206
- return output === "" ? "" : theme.fg(TOKEN.broken, output);
207
- }
@@ -1,5 +1,5 @@
1
1
  import { highlight as builtInHighlight, highlightLines, type HighlightFn } from "./highlight.ts";
2
- import { DIFF_HEADER, isJsonDocument, moreLinesFooter, splitTrailingNotice, styleDiffLine } from "./render-utils.ts";
2
+ import { DIFF_HEADER, isJsonDocument, moreLinesFooter, styleDiffLine } from "./render-utils.ts";
3
3
  import { TOKEN, type StyleTheme } from "./tokens.ts";
4
4
 
5
5
  // Tools with no renderer of their own collapse to the line count the built-in
@@ -43,7 +43,6 @@ function detectBodyKind(body: string): BodyKind {
43
43
  // regardless of how much the tool returned. JSON is the one batch call: a
44
44
  // per-line pass would break multi-line strings and map keys out of context.
45
45
  function styleLines(kind: BodyKind, lines: string[], theme: StyleTheme, highlightFn: HighlightFn): string[] {
46
- if (lines.length === 0) return [];
47
46
  const fallback = (line: string): string => theme.fg(TOKEN.content, line);
48
47
  switch (kind) {
49
48
  case "json":
@@ -57,30 +56,20 @@ function styleLines(kind: BodyKind, lines: string[], theme: StyleTheme, highligh
57
56
 
58
57
  /**
59
58
  * Body-only rendering for tools that bring no renderer of their own (MCP
60
- * servers, codemode, names the host does not know). There is no header to
61
- * reproduce: the generic overlay never invents one.
59
+ * servers, codemode, names the host does not know). It mirrors the host's own
60
+ * result fallback line for line, so the only difference a reader can see is the
61
+ * highlighting of a JSON or diff body.
62
62
  *
63
63
  * `highlightFn` is injected in tests, where `highlightCode` reads the
64
64
  * module-global theme.
65
65
  */
66
66
  export function buildGenericResultText(input: GenericInput, highlightFn: HighlightFn = builtInHighlight): string {
67
- const output = input.output.trim();
68
- // An error has no notice slot to split off: every line keeps the content
69
- // color, which is the rule find and ls follow too.
70
- const { body, notice } = input.isError ? { body: output, notice: undefined } : splitTrailingNotice(output);
71
- const lines = body === "" ? [] : body.split("\n");
67
+ if (input.output === "") return "";
68
+ const lines = input.output.split("\n");
72
69
  const visible = input.expanded ? lines : lines.slice(0, COLLAPSED_LINES);
73
- const styled = input.isError
74
- ? visible.map((line) => input.theme.fg(TOKEN.content, line))
75
- : styleLines(detectBodyKind(body), visible, input.theme, highlightFn);
76
-
77
- let text = "";
78
- if (styled.length > 0) {
79
- text += `\n${styled.join("\n")}`;
80
- // The notice is split off first, so it never counts as a hidden line.
81
- const hidden = lines.length - styled.length;
82
- if (hidden > 0) text += moreLinesFooter(hidden, input.theme, input.expandHint);
83
- }
84
- if (notice) text += `\n${input.theme.fg(TOKEN.notice, `[${notice}]`)}`;
70
+ const kind = input.isError ? "plain" : detectBodyKind(input.output);
71
+ let text = styleLines(kind, visible, input.theme, highlightFn).join("\n");
72
+ const hidden = lines.length - visible.length;
73
+ if (hidden > 0) text += moreLinesFooter(hidden, input.theme, input.expandHint);
85
74
  return text;
86
75
  }
@@ -1,17 +1,7 @@
1
- import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
2
- import {
3
- DEFAULT_MAX_BYTES,
4
- DEFAULT_MAX_LINES,
5
- formatReadLineRange,
6
- formatSize,
7
- getLanguageFromPath,
8
- getPackageDir,
9
- keyText,
10
- } from "@earendil-works/pi-coding-agent";
1
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, getLanguageFromPath } from "@earendil-works/pi-coding-agent";
11
2
  import { highlightLines, type HighlightFn } from "./highlight.ts";
12
- import { absolutePath, relativeToCwdOrAbsolute, renderToolPath } from "./render-path.ts";
13
3
  import { moreLinesFooter, replaceTabs } from "./render-utils.ts";
14
- import { BOLD_OFF, BOLD_ON, TOKEN, type StyleTheme } from "./tokens.ts";
4
+ import { TOKEN, type StyleTheme } from "./tokens.ts";
15
5
 
16
6
  // The built-in read renderer shows 10 lines when collapsed; any other number is
17
7
  // a visible difference against stock pi.
@@ -28,18 +18,6 @@ const READ_NOTICES = [
28
18
  ];
29
19
  const NOTICE_SEPARATOR = "\n\n";
30
20
 
31
- // The compact header the built-in prints instead of the full path for the files
32
- // the agent reads about itself.
33
- const COMPACT_RESOURCE_FILE_NAMES = new Set(["AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"]);
34
- const SKILL_FILE_NAME = "SKILL.md";
35
- const PI_DOC_PREFIXES = ["docs/", "examples/"];
36
- const PI_DOC_README = "README.md";
37
-
38
- // `keyText` reads the live keybinding table, which is empty outside a session;
39
- // the built-in default keeps the hint readable instead of " ( to expand)".
40
- const EXPAND_KEYBINDING = "app.tools.expand";
41
- const DEFAULT_EXPAND_KEY = "ctrl+o";
42
-
43
21
  // The truncation the host records for a read; every field is optional because a
44
22
  // result restored from a session may carry an older shape.
45
23
  export interface ReadTruncation {
@@ -56,8 +34,6 @@ export interface ReadResultInput {
56
34
  output: string;
57
35
  /** The argument's path, "" when the call does not carry one. */
58
36
  path: string;
59
- /** 1-based first line the tool read, which is also the first line number shown. */
60
- offset: number | undefined;
61
37
  details: { truncation?: ReadTruncation } | undefined;
62
38
  expanded: boolean;
63
39
  isError: boolean;
@@ -68,45 +44,12 @@ export interface ReadResultInput {
68
44
  highlight: HighlightFn;
69
45
  }
70
46
 
71
- export interface ReadCallInput {
72
- path: string;
73
- offset: number | undefined;
74
- limit: number | undefined;
75
- /** The transcript is collapsed, so the built-in header is the compact one. */
76
- compact: boolean;
77
- theme: StyleTheme;
78
- cwd: string | undefined;
79
- }
80
-
81
- // The two compact headers the built-in prints: a skill is announced by name, a
82
- // resource of the agent or of pi by a cwd-relative label.
83
- type ReadClassification = { kind: "skill" | "resource"; label: string };
84
-
85
47
  export function readPath(args: unknown): string {
86
48
  if (typeof args !== "object" || args === null) return "";
87
49
  const value = (args as { file_path?: unknown; path?: unknown }).file_path ?? (args as { path?: unknown }).path;
88
50
  return typeof value === "string" ? value : "";
89
51
  }
90
52
 
91
- // Line counts arrive as numbers from the schema and as numeric strings from a
92
- // restored session, so both are read; a value that is not a finite number leaves
93
- // the field unset and the caller falls back to the built-in default.
94
- function lineCount(value: unknown): number | undefined {
95
- const parsed = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
96
- if (typeof parsed !== "number" || !Number.isFinite(parsed)) return undefined;
97
- // Fractional and non-positive offsets do not name a line; the tool itself
98
- // rejects them, so the clamp only keeps the gutter printable.
99
- return Math.max(1, Math.floor(parsed));
100
- }
101
-
102
- export function readOffset(args: unknown): number | undefined {
103
- return lineCount(typeof args === "object" && args !== null ? (args as { offset?: unknown }).offset : undefined);
104
- }
105
-
106
- export function readLimit(args: unknown): number | undefined {
107
- return lineCount(typeof args === "object" && args !== null ? (args as { limit?: unknown }).limit : undefined);
108
- }
109
-
110
53
  // The tool separates its continuation notice from the body with a blank line, so
111
54
  // the split both looks for that separator and matches the whole block: a body
112
55
  // line that reads like a notice stays in the body. The oversized-first-line
@@ -142,28 +85,13 @@ function languageOf(path: string): string | undefined {
142
85
  }
143
86
 
144
87
  // One call for the whole body: a per-line pass would break multi-line
145
- // constructs, and the cached highlighter already caps how many lines it takes.
88
+ // constructs, and the highlighter takes every line the renderer shows.
146
89
  function styleLines(contents: string[], language: string | undefined, input: ReadResultInput): string[] {
147
- const fallback = (line: string): string => input.theme.fg(TOKEN.plain, line);
90
+ const fallback = (line: string): string => input.theme.fg(TOKEN.content, line);
148
91
  if (language === undefined) return contents.map(fallback);
149
92
  return highlightLines(contents.join("\n"), language, fallback, input.highlight);
150
93
  }
151
94
 
152
- // The real line numbers of the file: `offset` is where the tool started reading,
153
- // so the first visible line is not always line 1. Numbers are right-aligned to
154
- // the widest one on screen, and a blank line has no trailing space to paint.
155
- // That last decision belongs to the raw line: a colored line never is empty.
156
- function numbered(rawLines: string[], styledLines: string[], start: number, theme: StyleTheme): string {
157
- const width = String(start + rawLines.length - 1).length;
158
- const separator = theme.fg(TOKEN.context, " |");
159
- return rawLines
160
- .map((raw, index) => {
161
- const number = theme.fg(TOKEN.lineNumber, String(start + index).padStart(width));
162
- return raw === "" ? `${number}${separator}` : `${number}${separator} ${styledLines[index]}`;
163
- })
164
- .join("\n");
165
- }
166
-
167
95
  // The three wordings the built-in prints, byte for byte, including the built-in
168
96
  // default it falls back to when the host recorded no limit.
169
97
  function readTruncationNotice(truncation: ReadTruncation | undefined, theme: StyleTheme): string {
@@ -187,17 +115,17 @@ export function buildReadResultText(input: ReadResultInput): string {
187
115
  const { body, notice } = splitReadNotice(input.output, firstLineExceedsLimit);
188
116
  const lines = trimTrailingEmptyLines(body.split("\n"));
189
117
  // A failure, an image block and the oversized-first-line message are not file
190
- // text: no gutter and no grammar, exactly like the built-in.
118
+ // text: no grammar, exactly like the built-in.
191
119
  const fileText = !input.isError && !input.hasImage && !firstLineExceedsLimit;
192
120
  const limit = input.expanded ? lines.length : COLLAPSED_LINES;
193
- // The tab expansion happens before the grammar and before the gutter: both
194
- // measure the columns the terminal will show.
121
+ // The tab expansion happens before the grammar, which measures the columns the
122
+ // terminal will show.
195
123
  const contents = lines.slice(0, limit).map((line) => replaceTabs(line));
196
124
  const styled = styleLines(contents, fileText ? languageOf(input.path) : undefined, input);
197
125
 
198
126
  let text = "";
199
127
  if (styled.length > 0) {
200
- text += `\n${fileText ? numbered(contents, styled, input.offset ?? 1, input.theme) : styled.join("\n")}`;
128
+ text += `\n${styled.join("\n")}`;
201
129
  }
202
130
  // The notice is the last body line of the built-in output, so it stays before
203
131
  // the footer even though it is no longer counted as one of the file's lines.
@@ -206,72 +134,3 @@ export function buildReadResultText(input: ReadResultInput): string {
206
134
  if (hidden > 0) text += moreLinesFooter(hidden, input.theme, input.expandHint);
207
135
  return text + readTruncationNotice(truncation, input.theme);
208
136
  }
209
-
210
- // The label the pi package directory gives a path inside it, or undefined when
211
- // the path is outside and when the package root cannot be located (a global
212
- // install with no readable package directory).
213
- function piDocsLabel(path: string): string | undefined {
214
- let root: string;
215
- try {
216
- root = resolve(getPackageDir());
217
- } catch {
218
- return undefined;
219
- }
220
- const relativePath = relative(root, resolve(path));
221
- if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
222
- return undefined;
223
- }
224
- const label = relativePath.split(sep).join("/");
225
- return label === PI_DOC_README || PI_DOC_PREFIXES.some((prefix) => label.startsWith(prefix)) ? label : undefined;
226
- }
227
-
228
- function classifyReadPath(rawPath: string, cwd: string | undefined): ReadClassification | undefined {
229
- if (rawPath === "") return undefined;
230
- const absolute = absolutePath(rawPath, cwd);
231
- const fileName = basename(absolute);
232
- if (fileName === SKILL_FILE_NAME) return { kind: "skill", label: basename(dirname(absolute)) || fileName };
233
- // The built-in also folds pi's own documentation and examples into a label;
234
- // every other file keeps the full header.
235
- const docs = piDocsLabel(absolute);
236
- if (docs !== undefined) return { kind: "resource", label: docs };
237
- if (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {
238
- return { kind: "resource", label: relativeToCwdOrAbsolute(absolute, cwd) };
239
- }
240
- return undefined;
241
- }
242
-
243
- function expandKey(): string {
244
- try {
245
- return keyText(EXPAND_KEYBINDING) || DEFAULT_EXPAND_KEY;
246
- } catch {
247
- return DEFAULT_EXPAND_KEY;
248
- }
249
- }
250
-
251
- // The `:start-end` the header appends, omitted when the call carries no range.
252
- function lineRange(offset: number | undefined, limit: number | undefined, theme: StyleTheme): string {
253
- const range = formatReadLineRange(offset, limit);
254
- return range === "" ? "" : theme.fg(TOKEN.notice, range);
255
- }
256
-
257
- function fullReadCall(input: ReadCallInput): string {
258
- const title = input.theme.fg("toolTitle", input.theme.bold("read"));
259
- return `${title} ${renderToolPath(input.path, input.theme, input.cwd)}${lineRange(input.offset, input.limit, input.theme)}`;
260
- }
261
-
262
- function compactReadCall(classification: ReadClassification, input: ReadCallInput): string {
263
- const range = lineRange(input.offset, input.limit, input.theme);
264
- const hint = input.theme.fg("dim", ` (${expandKey()} to expand)`);
265
- if (classification.kind === "skill") {
266
- // The built-in spells the bold markers itself so the brackets share them.
267
- const label = input.theme.fg("customMessageLabel", `${BOLD_ON}[skill]${BOLD_OFF} `);
268
- return `${label}${input.theme.fg("customMessageText", classification.label)}${range}${hint}`;
269
- }
270
- const title = input.theme.fg("toolTitle", input.theme.bold(`read ${classification.kind}`));
271
- return `${title} ${input.theme.fg(TOKEN.path, classification.label)}${range}${hint}`;
272
- }
273
-
274
- export function buildReadCallText(input: ReadCallInput): string {
275
- const classification = input.compact ? classifyReadPath(input.path, input.cwd) : undefined;
276
- return classification === undefined ? fullReadCall(input) : compactReadCall(classification, input);
277
- }
@@ -6,6 +6,7 @@ import {
6
6
  imageFallback,
7
7
  stripTerminalSequences,
8
8
  type Component,
9
+ type Keybinding,
9
10
  } from "@earendil-works/pi-tui";
10
11
  import { TOKEN, type StyleTheme } from "./tokens.ts";
11
12
 
@@ -19,6 +20,9 @@ export interface RenderContext {
19
20
  state: Record<string, unknown>;
20
21
  showImages: boolean;
21
22
  durationMs: number | undefined;
23
+ // Owned by the copy of pi that runs the row, which is the one that knows the
24
+ // user's keybindings; an imported `keyHint` may resolve to another copy.
25
+ keyHint?: (keybinding: Keybinding, description: string) => string;
22
26
  }
23
27
 
24
28
  // Control characters crash `string-width`; tab and newline stay because the body
@@ -64,17 +68,6 @@ export function replaceTabs(text: string): string {
64
68
  return text.replace(/\t/g, " ");
65
69
  }
66
70
 
67
- // The generic overlay receives an output that ends with a notice such as
68
- // "\n\n[100 matches limit]". The blank line is the only separator, so a block
69
- // that itself contains a newline is body text, not a notice.
70
- export function splitTrailingNotice(output: string): { body: string; notice?: string } {
71
- const start = output.lastIndexOf("\n\n[");
72
- if (start === -1) return { body: output };
73
- const block = output.slice(start + 2);
74
- if (!block.endsWith("]") || block.includes("\n")) return { body: output };
75
- return { body: output.slice(0, start).trimEnd(), notice: block.slice(1, -1) };
76
- }
77
-
78
71
  // Byte-identical to the built-in footer (renderers/grep.ts, find.ts, ls.ts):
79
72
  // any divergence here is a visible difference against stock pi.
80
73
  export function moreLinesFooter(hidden: number, theme: StyleTheme, expandHint: string): string {
@@ -150,13 +143,11 @@ function truncationWarning(parts: TruncationParts): string {
150
143
  // before the body counts as one is up to each renderer.
151
144
  export const DIFF_HEADER = /^(diff --git|--- |\+\+\+ |@@ )/;
152
145
 
153
- // Added and removed lines of a diff: the foreground token alone is a thin strip
154
- // of color on a dark terminal, so the state is repeated on the background. Both
155
- // diff-aware renderers share this so the two bodies cannot drift apart.
146
+ // Added and removed lines of a diff: foreground only, as the host paints a
147
+ // result body; a background would add a colored block the host never draws.
148
+ // Both diff-aware renderers share this so the two bodies cannot drift apart.
156
149
  export function diffChangeLine(line: string, theme: StyleTheme): string {
157
- return line.startsWith("+")
158
- ? theme.bg("toolSuccessBg", theme.fg("toolDiffAdded", line))
159
- : theme.bg("toolErrorBg", theme.fg("toolDiffRemoved", line));
150
+ return theme.fg(line.startsWith("+") ? "toolDiffAdded" : "toolDiffRemoved", line);
160
151
  }
161
152
 
162
153
  // The three header forms get the function color, added and removed lines the