pi-syntax-highlight 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/README.md +68 -2
- package/extensions/index.ts +22 -0
- package/package.json +35 -4
- package/src/active-theme.ts +26 -0
- package/src/detect-language.ts +294 -0
- package/src/emphasis.ts +160 -0
- package/src/grep-parse.ts +42 -0
- package/src/highlight.ts +109 -0
- package/src/markdown-fence-lang.ts +180 -0
- package/src/markdown-style.ts +134 -0
- package/src/markdown-theme.ts +53 -0
- package/src/render-bash.ts +180 -0
- package/src/render-edit.ts +207 -0
- package/src/render-find.ts +64 -0
- package/src/render-generic.ts +86 -0
- package/src/render-grep.ts +142 -0
- package/src/render-ls.ts +66 -0
- package/src/render-path.ts +54 -0
- package/src/render-read.ts +277 -0
- package/src/render-utils.ts +219 -0
- package/src/render-write.ts +81 -0
- package/src/resolve-renderers.ts +406 -0
- package/src/style-path.ts +48 -0
- package/src/tokens.ts +114 -0
- package/test/unit/active-theme.test.ts +38 -0
- package/test/unit/bash-preview.test.ts +57 -0
- package/test/unit/detect-language.test.ts +124 -0
- package/test/unit/emphasis.test.ts +113 -0
- package/test/unit/extensions-index.test.ts +116 -0
- package/test/unit/grep-parse.test.ts +125 -0
- package/test/unit/highlight.test.ts +107 -0
- package/test/unit/markdown-fence-lang.test.ts +131 -0
- package/test/unit/markdown-pipeline.test.ts +153 -0
- package/test/unit/markdown-render-parity.test.ts +127 -0
- package/test/unit/markdown-style.test.ts +152 -0
- package/test/unit/markdown-theme.test.ts +86 -0
- package/test/unit/render-bash.test.ts +194 -0
- package/test/unit/render-edit.test.ts +214 -0
- package/test/unit/render-find.test.ts +139 -0
- package/test/unit/render-generic.test.ts +152 -0
- package/test/unit/render-grep.test.ts +338 -0
- package/test/unit/render-ls.test.ts +132 -0
- package/test/unit/render-read.test.ts +375 -0
- package/test/unit/render-utils.test.ts +324 -0
- package/test/unit/render-write.test.ts +143 -0
- package/test/unit/resolve-renderers.test.ts +474 -0
- package/test/unit/style-path.test.ts +74 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { truncateToVisualLines } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth, type Component } from "@earendil-works/pi-tui";
|
|
3
|
+
import { parseGrepLine } from "./grep-parse.ts";
|
|
4
|
+
import { highlight as builtInHighlight, highlightLines, type HighlightFn } from "./highlight.ts";
|
|
5
|
+
import { DIFF_HEADER, colonPrefix, isJsonDocument, styleDiffLine, truncationWarnings } from "./render-utils.ts";
|
|
6
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
7
|
+
|
|
8
|
+
// The built-in shell renderer keeps five visual lines when collapsed; any other
|
|
9
|
+
// number is a visible difference against stock pi.
|
|
10
|
+
const PREVIEW_LINES = 5;
|
|
11
|
+
|
|
12
|
+
// The built-in separates its "[Full output: ...]" block with a blank line, which
|
|
13
|
+
// is what keeps the strip from eating body text that merely ends in "]".
|
|
14
|
+
const FULL_OUTPUT_SEPARATOR = "\n\n[";
|
|
15
|
+
|
|
16
|
+
const DIFF_HUNK = /^@@ /;
|
|
17
|
+
const DIFF_CHANGE = /^[+-]/;
|
|
18
|
+
const ERROR_LINE = /^(error|fatal|panic|traceback|ERR!)/i;
|
|
19
|
+
const WARNING_LINE = /^(warning|warn)\b/i;
|
|
20
|
+
|
|
21
|
+
export interface BashInput {
|
|
22
|
+
output: string;
|
|
23
|
+
details:
|
|
24
|
+
| {
|
|
25
|
+
truncation?: {
|
|
26
|
+
truncated?: boolean;
|
|
27
|
+
truncatedBy?: "lines" | "bytes";
|
|
28
|
+
outputLines?: number;
|
|
29
|
+
totalLines?: number;
|
|
30
|
+
maxBytes?: number;
|
|
31
|
+
};
|
|
32
|
+
fullOutputPath?: string;
|
|
33
|
+
}
|
|
34
|
+
| undefined;
|
|
35
|
+
durationMs: number | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* A streaming result: the host keeps the full-output block in the body and the
|
|
38
|
+
* builder prints no timer, so the elapsed line stays with the live renderer.
|
|
39
|
+
*/
|
|
40
|
+
isPartial?: boolean;
|
|
41
|
+
theme: StyleTheme;
|
|
42
|
+
/** Injected in tests: `highlightCode` paints through the module-global theme. */
|
|
43
|
+
highlight?: HighlightFn;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface BashBody {
|
|
47
|
+
/** Styled body, without the leading newline the component wrapper adds. */
|
|
48
|
+
body: string;
|
|
49
|
+
/** Bracketed warning text, without the brackets. */
|
|
50
|
+
warnings?: string;
|
|
51
|
+
/** Duration text, without the "Took " prefix. */
|
|
52
|
+
timer?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Byte-identical to the built-in `formatToolDuration`: a diff here is a visible
|
|
56
|
+
// difference in the timer line, and `60.0s` at 59.999 ms is intended behavior.
|
|
57
|
+
export function formatDuration(ms: number): string {
|
|
58
|
+
const seconds = ms / 1000;
|
|
59
|
+
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
|
60
|
+
const totalSeconds = Math.floor(seconds);
|
|
61
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
62
|
+
const remainder = totalSeconds % 60;
|
|
63
|
+
return minutes < 60
|
|
64
|
+
? `${minutes}m ${remainder}s`
|
|
65
|
+
: `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// A diff is recognized by its header plus a hunk marker or several changed
|
|
69
|
+
// lines: a log line that merely starts with "--- " must not paint red/green.
|
|
70
|
+
function isDiffOutput(lines: string[]): boolean {
|
|
71
|
+
const first = lines.find((line) => line.trim() !== "");
|
|
72
|
+
if (first === undefined || !DIFF_HEADER.test(first)) return false;
|
|
73
|
+
let hunks = 0;
|
|
74
|
+
let changes = 0;
|
|
75
|
+
for (const line of lines) {
|
|
76
|
+
if (DIFF_HUNK.test(line)) hunks += 1;
|
|
77
|
+
else if (DIFF_CHANGE.test(line)) changes += 1;
|
|
78
|
+
}
|
|
79
|
+
return hunks > 0 || changes > 1;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Commands that print compiler or test output repeat grep's "path:line: text"
|
|
83
|
+
// shape, so it is parsed with the same function instead of a second regex.
|
|
84
|
+
function styleLine(line: string, theme: StyleTheme): string {
|
|
85
|
+
if (ERROR_LINE.test(line)) return theme.fg(TOKEN.broken, line);
|
|
86
|
+
if (WARNING_LINE.test(line)) return theme.fg(TOKEN.notice, line);
|
|
87
|
+
const entry = parseGrepLine(line);
|
|
88
|
+
if (entry.kind !== "match") return theme.fg(TOKEN.content, line);
|
|
89
|
+
const path = theme.fg(TOKEN.path, entry.path);
|
|
90
|
+
return `${colonPrefix(path, entry.line, theme)} ${theme.fg(TOKEN.content, entry.text)}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function styleOutput(output: string, theme: StyleTheme, highlight: HighlightFn): string {
|
|
94
|
+
const lines = output.split("\n");
|
|
95
|
+
if (isDiffOutput(lines)) return lines.map((line) => styleDiffLine(line, theme)).join("\n");
|
|
96
|
+
if (isJsonDocument(output)) {
|
|
97
|
+
// Whole-block highlighting keeps keys, strings and numbers distinct; the
|
|
98
|
+
// fallback protects readers when the tokenizer throws.
|
|
99
|
+
const fallback = (line: string): string => theme.fg(TOKEN.content, line);
|
|
100
|
+
return highlightLines(output, "json", fallback, highlight).join("\n");
|
|
101
|
+
}
|
|
102
|
+
return lines.map((line) => styleLine(line, theme)).join("\n");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
type BashTruncation = NonNullable<NonNullable<BashInput["details"]>["truncation"]>;
|
|
106
|
+
|
|
107
|
+
// Same wording as the built-in renderer, including the byte limit it falls back
|
|
108
|
+
// to when the host did not record one. The built-in treats a missing
|
|
109
|
+
// `truncatedBy` as byte truncation, so the default is spelled out here.
|
|
110
|
+
function truncationText(truncation: BashTruncation): string {
|
|
111
|
+
return truncationWarnings({
|
|
112
|
+
truncatedBy: truncation.truncatedBy ?? "bytes",
|
|
113
|
+
outputLines: truncation.outputLines,
|
|
114
|
+
totalLines: truncation.totalLines,
|
|
115
|
+
maxBytes: truncation.maxBytes,
|
|
116
|
+
}).join(". ");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// The built-in moves the trailing "[Full output: ...]" block out of the body and
|
|
120
|
+
// rebuilds it as a warning, so the path is not shown twice. A partial result may
|
|
121
|
+
// still be rewritten by the tool, so the block stays in place exactly as the
|
|
122
|
+
// built-in does (`!options.isPartial`), and its own blank line is the only
|
|
123
|
+
// separator that can start the block.
|
|
124
|
+
function stripFullOutputBlock(output: string, details: BashInput["details"], isPartial: boolean): string {
|
|
125
|
+
const truncation = details?.truncation;
|
|
126
|
+
const fullOutputPath = details?.fullOutputPath;
|
|
127
|
+
if (isPartial || !truncation?.truncated || !fullOutputPath || !output.endsWith("]")) return output;
|
|
128
|
+
const blockStart = output.lastIndexOf(FULL_OUTPUT_SEPARATOR);
|
|
129
|
+
if (blockStart === -1 || !output.slice(blockStart).includes(fullOutputPath)) return output;
|
|
130
|
+
return output.slice(0, blockStart).trimEnd();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// A partial result prints no timer: the elapsed line belongs to the live
|
|
134
|
+
// renderer.
|
|
135
|
+
export function buildBashBody(input: BashInput): BashBody {
|
|
136
|
+
const truncation = input.details?.truncation;
|
|
137
|
+
const fullOutputPath = input.details?.fullOutputPath;
|
|
138
|
+
const output = stripFullOutputBlock(input.output.trim(), input.details, input.isPartial === true);
|
|
139
|
+
|
|
140
|
+
const body = output === "" ? "" : styleOutput(output, input.theme, input.highlight ?? builtInHighlight);
|
|
141
|
+
|
|
142
|
+
const warnings: string[] = [];
|
|
143
|
+
if (fullOutputPath) warnings.push(`Full output: ${fullOutputPath}`);
|
|
144
|
+
if (truncation?.truncated) warnings.push(`Truncated: ${truncationText(truncation)}`);
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
body,
|
|
148
|
+
warnings: warnings.length === 0 ? undefined : warnings.join(". "),
|
|
149
|
+
timer: input.isPartial || input.durationMs === undefined ? undefined : formatDuration(input.durationMs),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Collapsed shell output is cut by visual line, not by logical line: a single
|
|
154
|
+
// long line (minified JSON, a build log without newlines) would otherwise fill
|
|
155
|
+
// the screen. The lines are cached per width because a component re-renders on
|
|
156
|
+
// every frame of the transcript.
|
|
157
|
+
export function createBashPreview(body: string, expandHint: string, theme: StyleTheme): Component {
|
|
158
|
+
let cachedWidth: number | undefined;
|
|
159
|
+
let cachedLines: string[] | undefined;
|
|
160
|
+
return {
|
|
161
|
+
render(width: number): string[] {
|
|
162
|
+
if (cachedLines !== undefined && cachedWidth === width) return cachedLines;
|
|
163
|
+
const { visualLines, skippedCount } = truncateToVisualLines(body, PREVIEW_LINES, width, 0, "end");
|
|
164
|
+
const lines = visualLines.map((line) => truncateToWidth(line, width));
|
|
165
|
+
if (skippedCount > 0) {
|
|
166
|
+
// Same hint format as the built-in preview, above the kept tail.
|
|
167
|
+
const hint = `${theme.fg("muted", `... (${skippedCount} earlier lines,`)} ${expandHint}${theme.fg("muted", ")")}`;
|
|
168
|
+
cachedLines = [truncateToWidth(hint, width), ...lines];
|
|
169
|
+
} else {
|
|
170
|
+
cachedLines = lines;
|
|
171
|
+
}
|
|
172
|
+
cachedWidth = width;
|
|
173
|
+
return cachedLines;
|
|
174
|
+
},
|
|
175
|
+
invalidate(): void {
|
|
176
|
+
cachedWidth = undefined;
|
|
177
|
+
cachedLines = undefined;
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { getLanguageFromPath } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { diffWords } from "diff";
|
|
3
|
+
import { applyEmphasis, type Range } from "./emphasis.ts";
|
|
4
|
+
import { highlightLines, type HighlightFn } from "./highlight.ts";
|
|
5
|
+
import { replaceTabs } from "./render-utils.ts";
|
|
6
|
+
import { INVERSE_OFF, INVERSE_ON, TOKEN, type StyleTheme } from "./tokens.ts";
|
|
7
|
+
|
|
8
|
+
// The display diff `edit` carries in its details: one marker, the line number
|
|
9
|
+
// right-aligned to the widest one, one space, then the content:
|
|
10
|
+
//
|
|
11
|
+
// +12 const b = 2;
|
|
12
|
+
// -12 const a = 1;
|
|
13
|
+
// 12 unchanged
|
|
14
|
+
// ...
|
|
15
|
+
//
|
|
16
|
+
// A line outside that grammar is passed through untouched, so nothing is lost if
|
|
17
|
+
// the host ever widens the shape.
|
|
18
|
+
const DIFF_LINE = /^([+-\s])(\s*\d*)\s(.*)$/;
|
|
19
|
+
|
|
20
|
+
const ELISION = "...";
|
|
21
|
+
|
|
22
|
+
const DIFF_KIND_TOKEN = {
|
|
23
|
+
added: "toolDiffAdded",
|
|
24
|
+
removed: "toolDiffRemoved",
|
|
25
|
+
context: "toolDiffContext",
|
|
26
|
+
} as const;
|
|
27
|
+
|
|
28
|
+
export type EditDiffKind = keyof typeof DIFF_KIND_TOKEN;
|
|
29
|
+
|
|
30
|
+
export type EditDiffLine =
|
|
31
|
+
| { kind: EditDiffKind; prefix: string; number: string; content: string }
|
|
32
|
+
| { kind: "elision"; prefix: string; number: string; content: string }
|
|
33
|
+
| { kind: "other"; raw: string };
|
|
34
|
+
|
|
35
|
+
type DiffBodyLine = Extract<EditDiffLine, { kind: EditDiffKind }>;
|
|
36
|
+
|
|
37
|
+
export interface EditDiffInput {
|
|
38
|
+
diff: string;
|
|
39
|
+
/** The argument's path, "" when the call does not carry one. */
|
|
40
|
+
path: string;
|
|
41
|
+
theme: StyleTheme;
|
|
42
|
+
highlight: HighlightFn;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function classifyEditDiffLine(line: string): EditDiffLine {
|
|
46
|
+
const match = DIFF_LINE.exec(line);
|
|
47
|
+
if (match === null) return { kind: "other", raw: line };
|
|
48
|
+
const [, prefix, number, content] = match;
|
|
49
|
+
// The elision the display diff uses between two hunks has no number and must
|
|
50
|
+
// not be read as a body line.
|
|
51
|
+
if (number.trim() === "" && content === ELISION) return { kind: "elision", prefix, number, content };
|
|
52
|
+
if (prefix === "+") return { kind: "added", prefix, number, content };
|
|
53
|
+
if (prefix === "-") return { kind: "removed", prefix, number, content };
|
|
54
|
+
return { kind: "context", prefix, number, content };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function bodyLine(line: EditDiffLine | undefined, kind?: EditDiffKind): DiffBodyLine | undefined {
|
|
58
|
+
if (line === undefined || line.kind === "elision" || line.kind === "other") return undefined;
|
|
59
|
+
return kind === undefined || line.kind === kind ? line : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// A number without digits is the placeholder of an elision: it is emitted as the
|
|
63
|
+
// spaces it is, because the surrounding padding is the alignment.
|
|
64
|
+
function paintedNumber(number: string, theme: StyleTheme): string {
|
|
65
|
+
return /\d/.test(number) ? theme.fg(TOKEN.lineNumber, number) : number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function renderLine(line: EditDiffLine, content: string, theme: StyleTheme): string {
|
|
69
|
+
if (line.kind === "other") return theme.fg(TOKEN.content, line.raw);
|
|
70
|
+
const color = DIFF_KIND_TOKEN[line.kind === "elision" ? "context" : line.kind];
|
|
71
|
+
return `${theme.fg(color, line.prefix)}${paintedNumber(line.number, theme)} ${content}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// One highlight call per contiguous run of the same kind: a per-line pass would
|
|
75
|
+
// break multi-line constructs, and the run is where the grammar's context ends
|
|
76
|
+
// anyway. Without a grammar every line keeps its kind's color.
|
|
77
|
+
function highlightRun(lines: DiffBodyLine[], language: string | undefined, input: EditDiffInput): string[] {
|
|
78
|
+
const contents = lines.map((line) => replaceTabs(line.content));
|
|
79
|
+
const kind = lines[0].kind;
|
|
80
|
+
const fallback = (line: string): string => input.theme.fg(DIFF_KIND_TOKEN[kind], line);
|
|
81
|
+
if (language === undefined) return contents.map(fallback);
|
|
82
|
+
return highlightLines(contents.join("\n"), language, fallback, input.highlight);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface ChangedRanges {
|
|
86
|
+
removed: Range[];
|
|
87
|
+
added: Range[];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function leadingWhitespace(value: string): number {
|
|
91
|
+
return value.length - value.trimStart().length;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function pushRange(ranges: Range[], start: number, end: number): void {
|
|
95
|
+
if (start < end) ranges.push({ start, end });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The visible columns the word diff marks on each side of a modification. The
|
|
99
|
+
// walk mirrors the built-in `renderIntraLineDiff`: an unchanged part advances
|
|
100
|
+
// both columns, a removed one exists on the old side only and an added one on the
|
|
101
|
+
// new side only, and the leading whitespace of the first change on either side is
|
|
102
|
+
// never marked because it is indentation, not a change.
|
|
103
|
+
function changedRanges(removedContent: string, addedContent: string): ChangedRanges {
|
|
104
|
+
const ranges: ChangedRanges = { removed: [], added: [] };
|
|
105
|
+
let removedColumn = 0;
|
|
106
|
+
let addedColumn = 0;
|
|
107
|
+
let firstRemoved = true;
|
|
108
|
+
let firstAdded = true;
|
|
109
|
+
for (const part of diffWords(removedContent, addedContent)) {
|
|
110
|
+
const length = part.value.length;
|
|
111
|
+
if (part.removed === true) {
|
|
112
|
+
pushRange(ranges.removed, removedColumn + (firstRemoved ? leadingWhitespace(part.value) : 0), removedColumn + length);
|
|
113
|
+
removedColumn += length;
|
|
114
|
+
firstRemoved = false;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (part.added === true) {
|
|
118
|
+
pushRange(ranges.added, addedColumn + (firstAdded ? leadingWhitespace(part.value) : 0), addedColumn + length);
|
|
119
|
+
addedColumn += length;
|
|
120
|
+
firstAdded = false;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
removedColumn += length;
|
|
124
|
+
addedColumn += length;
|
|
125
|
+
}
|
|
126
|
+
return ranges;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The pair the built-in marks intra-line: exactly one removed line directly
|
|
130
|
+
// followed by exactly one added one. Anything else (several removed lines, a
|
|
131
|
+
// standalone addition) keeps the per-kind colors only.
|
|
132
|
+
function modificationAt(lines: EditDiffLine[], index: number): { removed: DiffBodyLine; added: DiffBodyLine } | undefined {
|
|
133
|
+
const removed = bodyLine(lines[index], "removed");
|
|
134
|
+
if (removed === undefined) return undefined;
|
|
135
|
+
const added = bodyLine(lines[index + 1], "added");
|
|
136
|
+
if (added === undefined) return undefined;
|
|
137
|
+
if (bodyLine(lines[index + 2], "added") !== undefined) return undefined;
|
|
138
|
+
return { removed, added };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function renderModification(
|
|
142
|
+
pair: { removed: DiffBodyLine; added: DiffBodyLine },
|
|
143
|
+
language: string | undefined,
|
|
144
|
+
input: EditDiffInput,
|
|
145
|
+
): string[] {
|
|
146
|
+
// The word diff runs on the tab-expanded content, which is also what the
|
|
147
|
+
// highlighter receives, so the columns line up on screen.
|
|
148
|
+
const removedContent = replaceTabs(pair.removed.content);
|
|
149
|
+
const addedContent = replaceTabs(pair.added.content);
|
|
150
|
+
const [removedStyled] = highlightRun([{ ...pair.removed, content: removedContent }], language, input);
|
|
151
|
+
const [addedStyled] = highlightRun([{ ...pair.added, content: addedContent }], language, input);
|
|
152
|
+
const ranges = changedRanges(removedContent, addedContent);
|
|
153
|
+
return [
|
|
154
|
+
renderLine(pair.removed, applyEmphasis(removedStyled, ranges.removed, INVERSE_ON, INVERSE_OFF), input.theme),
|
|
155
|
+
renderLine(pair.added, applyEmphasis(addedStyled, ranges.added, INVERSE_ON, INVERSE_OFF), input.theme),
|
|
156
|
+
];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function runEnd(lines: EditDiffLine[], index: number, kind: EditDiffKind): number {
|
|
160
|
+
let end = index + 1;
|
|
161
|
+
while (end < lines.length && bodyLine(lines[end], kind) !== undefined) end += 1;
|
|
162
|
+
return end;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function buildEditDiffText(input: EditDiffInput): string {
|
|
166
|
+
if (input.diff === "") return "";
|
|
167
|
+
const lines = input.diff.split("\n").map(classifyEditDiffLine);
|
|
168
|
+
const language = input.path === "" ? undefined : getLanguageFromPath(input.path);
|
|
169
|
+
const styled: string[] = [];
|
|
170
|
+
let index = 0;
|
|
171
|
+
while (index < lines.length) {
|
|
172
|
+
const pair = modificationAt(lines, index);
|
|
173
|
+
if (pair !== undefined) {
|
|
174
|
+
styled.push(...renderModification(pair, language, input));
|
|
175
|
+
index += 2;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const line = lines[index];
|
|
179
|
+
if (line.kind === "elision") {
|
|
180
|
+
styled.push(renderLine(line, input.theme.fg(DIFF_KIND_TOKEN.context, line.content), input.theme));
|
|
181
|
+
index += 1;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
const body = bodyLine(line);
|
|
185
|
+
if (body === undefined) {
|
|
186
|
+
styled.push(renderLine(line, "", input.theme));
|
|
187
|
+
index += 1;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const end = runEnd(lines, index, body.kind);
|
|
191
|
+
// Every line of the run was matched by `bodyLine` above, so the cast loses
|
|
192
|
+
// nothing; the array is typed by what `runEnd` has already checked.
|
|
193
|
+
const run = lines.slice(index, end).map((entry) => entry as DiffBodyLine);
|
|
194
|
+
const highlighted = highlightRun(run, language, input);
|
|
195
|
+
run.forEach((entry, offset) => {
|
|
196
|
+
styled.push(renderLine(entry, highlighted[offset], input.theme));
|
|
197
|
+
});
|
|
198
|
+
index = end;
|
|
199
|
+
}
|
|
200
|
+
return styled.join("\n");
|
|
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
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { buildListBody, truncatedNotice } from "./render-utils.ts";
|
|
2
|
+
import { classifyPathLine, stylePath } from "./style-path.ts";
|
|
3
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
4
|
+
|
|
5
|
+
// The built-in find renderer shows 20 lines when collapsed; any other number
|
|
6
|
+
// is a visible difference against stock pi.
|
|
7
|
+
const COLLAPSED_LINES = 20;
|
|
8
|
+
|
|
9
|
+
export interface PathListInput {
|
|
10
|
+
output: string;
|
|
11
|
+
expanded: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* A failed search is painted flat: styling it by path family would read as a
|
|
14
|
+
* normal listing, and stock pi leaves the failure in the content color.
|
|
15
|
+
*/
|
|
16
|
+
isError: boolean;
|
|
17
|
+
details:
|
|
18
|
+
| {
|
|
19
|
+
resultLimitReached?: number;
|
|
20
|
+
truncation?: { truncated?: boolean; maxBytes?: number };
|
|
21
|
+
}
|
|
22
|
+
| undefined;
|
|
23
|
+
theme: StyleTheme;
|
|
24
|
+
expandHint: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function stylePathLine(line: string, theme: StyleTheme): string {
|
|
28
|
+
const entry = classifyPathLine(line);
|
|
29
|
+
switch (entry.kind) {
|
|
30
|
+
case "dir":
|
|
31
|
+
case "file":
|
|
32
|
+
return stylePath(entry.path, theme);
|
|
33
|
+
case "notice":
|
|
34
|
+
return theme.fg(TOKEN.notice, entry.text);
|
|
35
|
+
case "plain":
|
|
36
|
+
return theme.fg(TOKEN.empty, entry.text);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function buildFindResultText(input: PathListInput): string {
|
|
41
|
+
// `find` ends its output with its own "[N results limit reached. Use
|
|
42
|
+
// limit=...]" block, and stock pi counts it as one more body line: it is
|
|
43
|
+
// painted as a notice and it counts toward the collapsed cut.
|
|
44
|
+
let text = buildListBody({
|
|
45
|
+
body: input.output.trim(),
|
|
46
|
+
expanded: input.expanded,
|
|
47
|
+
collapsedLines: COLLAPSED_LINES,
|
|
48
|
+
theme: input.theme,
|
|
49
|
+
expandHint: input.expandHint,
|
|
50
|
+
styleLine: (line) =>
|
|
51
|
+
input.isError ? input.theme.fg(TOKEN.content, line) : stylePathLine(line, input.theme),
|
|
52
|
+
});
|
|
53
|
+
// Stock pi paints the details-derived warning last, so it is appended instead
|
|
54
|
+
// of passed into the body builder.
|
|
55
|
+
text += truncatedNotice(
|
|
56
|
+
{
|
|
57
|
+
limitCount: input.details?.resultLimitReached,
|
|
58
|
+
limitLabel: "results limit",
|
|
59
|
+
truncation: input.details?.truncation,
|
|
60
|
+
},
|
|
61
|
+
input.theme,
|
|
62
|
+
);
|
|
63
|
+
return text;
|
|
64
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { highlight as builtInHighlight, highlightLines, type HighlightFn } from "./highlight.ts";
|
|
2
|
+
import { DIFF_HEADER, isJsonDocument, moreLinesFooter, splitTrailingNotice, styleDiffLine } from "./render-utils.ts";
|
|
3
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
4
|
+
|
|
5
|
+
// Tools with no renderer of their own collapse to the line count the built-in
|
|
6
|
+
// fallback uses (`FALLBACK_PREVIEW_LINES`), so a large MCP payload does not
|
|
7
|
+
// flood the transcript.
|
|
8
|
+
const COLLAPSED_LINES = 10;
|
|
9
|
+
|
|
10
|
+
export interface GenericInput {
|
|
11
|
+
output: string;
|
|
12
|
+
expanded: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* A failed tool is painted flat: a diff or JSON body that happens to parse
|
|
15
|
+
* would otherwise disguise the failure as a normal result.
|
|
16
|
+
*/
|
|
17
|
+
isError: boolean;
|
|
18
|
+
theme: StyleTheme;
|
|
19
|
+
expandHint: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// What the body is decides the painter; anything else is painted as content.
|
|
23
|
+
type BodyKind = "json" | "diff" | "plain";
|
|
24
|
+
|
|
25
|
+
function firstNonBlank(lines: string[]): string | undefined {
|
|
26
|
+
return lines.find((line) => line.trim() !== "");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isDiffBody(lines: string[]): boolean {
|
|
30
|
+
const first = firstNonBlank(lines);
|
|
31
|
+
return first !== undefined && DIFF_HEADER.test(first);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Detection runs on the whole body, before the collapsed cut: a JSON document
|
|
35
|
+
// whose first twenty lines are an unterminated array does not parse on its own.
|
|
36
|
+
function detectBodyKind(body: string): BodyKind {
|
|
37
|
+
if (isJsonDocument(body)) return "json";
|
|
38
|
+
if (isDiffBody(body.split("\n"))) return "diff";
|
|
39
|
+
return "plain";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Styling happens after the cut, so a collapsed view tokenizes the visible lines
|
|
43
|
+
// regardless of how much the tool returned. JSON is the one batch call: a
|
|
44
|
+
// per-line pass would break multi-line strings and map keys out of context.
|
|
45
|
+
function styleLines(kind: BodyKind, lines: string[], theme: StyleTheme, highlightFn: HighlightFn): string[] {
|
|
46
|
+
if (lines.length === 0) return [];
|
|
47
|
+
const fallback = (line: string): string => theme.fg(TOKEN.content, line);
|
|
48
|
+
switch (kind) {
|
|
49
|
+
case "json":
|
|
50
|
+
return highlightLines(lines.join("\n"), "json", fallback, highlightFn);
|
|
51
|
+
case "diff":
|
|
52
|
+
return lines.map((line) => styleDiffLine(line, theme));
|
|
53
|
+
case "plain":
|
|
54
|
+
return lines.map(fallback);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 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.
|
|
62
|
+
*
|
|
63
|
+
* `highlightFn` is injected in tests, where `highlightCode` reads the
|
|
64
|
+
* module-global theme.
|
|
65
|
+
*/
|
|
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");
|
|
72
|
+
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}]`)}`;
|
|
85
|
+
return text;
|
|
86
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { getLanguageFromPath } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { applyEmphasis, findMatchRanges, type MatchOptions } from "./emphasis.ts";
|
|
3
|
+
import { UNREADABLE_TEXT, parseGrepLine, type GrepLine } from "./grep-parse.ts";
|
|
4
|
+
import { highlightLines, type HighlightFn } from "./highlight.ts";
|
|
5
|
+
import { colonPrefix, moreLinesFooter, truncatedNotice } from "./render-utils.ts";
|
|
6
|
+
import { BOLD_OFF, BOLD_ON, TOKEN, type StyleTheme } from "./tokens.ts";
|
|
7
|
+
|
|
8
|
+
const COLLAPSED_LINES = 15;
|
|
9
|
+
|
|
10
|
+
// The pattern as the arguments carry it, once validated. Anything that is not a
|
|
11
|
+
// non-empty string leaves the line as it is, which is also what grep does when
|
|
12
|
+
// it is called without a pattern.
|
|
13
|
+
interface EmphasisPattern extends MatchOptions {
|
|
14
|
+
pattern: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface GrepInput {
|
|
18
|
+
output: string;
|
|
19
|
+
expanded: boolean;
|
|
20
|
+
pattern: { pattern?: unknown; literal?: unknown; ignoreCase?: unknown };
|
|
21
|
+
details:
|
|
22
|
+
| {
|
|
23
|
+
matchLimitReached?: number;
|
|
24
|
+
linesTruncated?: boolean;
|
|
25
|
+
truncation?: { truncated?: boolean; maxBytes?: number };
|
|
26
|
+
}
|
|
27
|
+
| undefined;
|
|
28
|
+
theme: StyleTheme;
|
|
29
|
+
expandHint: string;
|
|
30
|
+
highlight: HighlightFn;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type MatchLine = Extract<GrepLine, { kind: "match" }>;
|
|
34
|
+
|
|
35
|
+
function languageOf(entry: GrepLine): string | undefined {
|
|
36
|
+
return entry.kind === "match" || entry.kind === "context" ? getLanguageFromPath(entry.path) : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function pathOf(entry: GrepLine): string | undefined {
|
|
40
|
+
return entry.kind === "match" || entry.kind === "context" ? entry.path : undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function entryText(entry: GrepLine): string {
|
|
44
|
+
return entry.kind === "match" || entry.kind === "context" ? entry.text : "";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function resolvePattern(pattern: GrepInput["pattern"]): EmphasisPattern | undefined {
|
|
48
|
+
if (typeof pattern.pattern !== "string" || pattern.pattern === "") return undefined;
|
|
49
|
+
return { pattern: pattern.pattern, literal: pattern.literal === true, ignoreCase: pattern.ignoreCase === true };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The ranges are computed on the plain text, so they address visible columns;
|
|
53
|
+
// `applyEmphasis` maps them onto the same columns of the highlighted string. The
|
|
54
|
+
// path and the line number are built afterwards, so they never carry a marker.
|
|
55
|
+
function emphasize(line: MatchLine, styled: string, pattern: EmphasisPattern | undefined): string {
|
|
56
|
+
if (pattern === undefined) return styled;
|
|
57
|
+
return applyEmphasis(styled, findMatchRanges(line.text, pattern.pattern, pattern), BOLD_ON, BOLD_OFF);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The path arrives already colored, so each line kind decides its own weight:
|
|
61
|
+
// the path of a match is bold, the path of an unreadable entry is not.
|
|
62
|
+
function styleLine(
|
|
63
|
+
entry: GrepLine,
|
|
64
|
+
highlighted: string | undefined,
|
|
65
|
+
theme: StyleTheme,
|
|
66
|
+
pattern: EmphasisPattern | undefined,
|
|
67
|
+
): string {
|
|
68
|
+
switch (entry.kind) {
|
|
69
|
+
case "plain":
|
|
70
|
+
return theme.fg(TOKEN.content, entry.text);
|
|
71
|
+
case "notice":
|
|
72
|
+
return theme.fg(TOKEN.notice, entry.text);
|
|
73
|
+
case "unreadable":
|
|
74
|
+
return `${colonPrefix(theme.fg(TOKEN.path, entry.path), entry.line, theme)} ${theme.fg(TOKEN.broken, UNREADABLE_TEXT)}`;
|
|
75
|
+
case "match": {
|
|
76
|
+
const content = highlighted ?? theme.fg(TOKEN.content, entry.text);
|
|
77
|
+
const path = theme.bold(theme.fg(TOKEN.path, entry.path));
|
|
78
|
+
return `${colonPrefix(path, entry.line, theme)} ${emphasize(entry, content, pattern)}`;
|
|
79
|
+
}
|
|
80
|
+
case "context":
|
|
81
|
+
return `${theme.fg(TOKEN.context, entry.path)}-${theme.fg(TOKEN.context, String(entry.line))}- ${highlighted ?? theme.fg(TOKEN.context, entry.text)}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Contiguous lines from the same file are highlighted in a single call: per-line
|
|
86
|
+
// tokenizing would break multi-line constructs, and a call per line costs a cache
|
|
87
|
+
// lookup per line. The run also stops at a path change, so a file's lines are
|
|
88
|
+
// never tokenized together with another file's.
|
|
89
|
+
function styleLines(entries: GrepLine[], input: GrepInput, pattern: EmphasisPattern | undefined): string[] {
|
|
90
|
+
const styled: string[] = [];
|
|
91
|
+
const fallback = (line: string): string => input.theme.fg(TOKEN.content, line);
|
|
92
|
+
let index = 0;
|
|
93
|
+
while (index < entries.length) {
|
|
94
|
+
const language = languageOf(entries[index]);
|
|
95
|
+
const path = pathOf(entries[index]);
|
|
96
|
+
if (language === undefined) {
|
|
97
|
+
styled.push(styleLine(entries[index], undefined, input.theme, pattern));
|
|
98
|
+
index += 1;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
let end = index + 1;
|
|
102
|
+
while (end < entries.length && languageOf(entries[end]) === language && pathOf(entries[end]) === path) end += 1;
|
|
103
|
+
const run = entries.slice(index, end);
|
|
104
|
+
const code = run.map((entry) => entryText(entry)).join("\n");
|
|
105
|
+
const highlighted = highlightLines(code, language, fallback, input.highlight);
|
|
106
|
+
run.forEach((entry, offset) => {
|
|
107
|
+
styled.push(styleLine(entry, highlighted[offset], input.theme, pattern));
|
|
108
|
+
});
|
|
109
|
+
index = end;
|
|
110
|
+
}
|
|
111
|
+
return styled;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function buildGrepResultText(input: GrepInput): string {
|
|
115
|
+
// grep appends its own "[N matches limit reached. …]" block, and stock pi
|
|
116
|
+
// counts it as one more body line: it is painted as a notice and it counts
|
|
117
|
+
// toward the collapsed cut like any other line.
|
|
118
|
+
const output = input.output.trim();
|
|
119
|
+
const bodyLines = output === "" ? [] : output.split("\n");
|
|
120
|
+
const visible = input.expanded ? bodyLines : bodyLines.slice(0, COLLAPSED_LINES);
|
|
121
|
+
const pattern = resolvePattern(input.pattern);
|
|
122
|
+
const styled = styleLines(visible.map((line) => parseGrepLine(line)), input, pattern);
|
|
123
|
+
|
|
124
|
+
let text = "";
|
|
125
|
+
if (styled.length > 0) {
|
|
126
|
+
text += `\n${styled.join("\n")}`;
|
|
127
|
+
const hidden = bodyLines.length - styled.length;
|
|
128
|
+
if (hidden > 0) text += moreLinesFooter(hidden, input.theme, input.expandHint);
|
|
129
|
+
}
|
|
130
|
+
// The details-derived warning is not part of the body, so it stays after the
|
|
131
|
+
// footer exactly as stock pi prints it.
|
|
132
|
+
text += truncatedNotice(
|
|
133
|
+
{
|
|
134
|
+
limitCount: input.details?.matchLimitReached,
|
|
135
|
+
limitLabel: "matches limit",
|
|
136
|
+
truncation: input.details?.truncation,
|
|
137
|
+
extra: input.details?.linesTruncated ? ["some lines truncated"] : [],
|
|
138
|
+
},
|
|
139
|
+
input.theme,
|
|
140
|
+
);
|
|
141
|
+
return text;
|
|
142
|
+
}
|