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.
- package/CHANGELOG.md +86 -0
- package/DEVELOPER.md +73 -0
- package/README.md +65 -2
- package/assets/icon.png +0 -0
- package/assets/icon.svg +36 -0
- package/extensions/index.ts +22 -0
- package/package.json +49 -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,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
|
+
}
|
package/src/render-ls.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
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 ls renderer shows 20 lines when collapsed; any other number is
|
|
6
|
+
// a visible difference against stock pi.
|
|
7
|
+
const COLLAPSED_LINES = 20;
|
|
8
|
+
|
|
9
|
+
export interface LsInput {
|
|
10
|
+
output: string;
|
|
11
|
+
expanded: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* A failed listing is painted flat: styling it by file 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
|
+
entryLimitReached?: number;
|
|
20
|
+
truncation?: { truncated?: boolean; maxBytes?: number };
|
|
21
|
+
}
|
|
22
|
+
| undefined;
|
|
23
|
+
theme: StyleTheme;
|
|
24
|
+
expandHint: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// ls prints bare entry names, so `dir/` has no leading segments to dim and every
|
|
28
|
+
// non-sentinel line is a single entry.
|
|
29
|
+
function styleLsLine(line: string, theme: StyleTheme): string {
|
|
30
|
+
const entry = classifyPathLine(line);
|
|
31
|
+
switch (entry.kind) {
|
|
32
|
+
case "dir":
|
|
33
|
+
case "file":
|
|
34
|
+
return stylePath(entry.path, theme);
|
|
35
|
+
case "notice":
|
|
36
|
+
return theme.fg(TOKEN.notice, entry.text);
|
|
37
|
+
case "plain":
|
|
38
|
+
return theme.fg(TOKEN.empty, entry.text);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function buildLsResultText(input: LsInput): string {
|
|
43
|
+
// `ls` ends its output with its own "[N entries limit reached. Use limit=...]"
|
|
44
|
+
// block, and stock pi counts it as one more body line: it is painted as a
|
|
45
|
+
// notice and it counts toward the collapsed cut.
|
|
46
|
+
let text = buildListBody({
|
|
47
|
+
body: input.output.trim(),
|
|
48
|
+
expanded: input.expanded,
|
|
49
|
+
collapsedLines: COLLAPSED_LINES,
|
|
50
|
+
theme: input.theme,
|
|
51
|
+
expandHint: input.expandHint,
|
|
52
|
+
styleLine: (line) =>
|
|
53
|
+
input.isError ? input.theme.fg(TOKEN.content, line) : styleLsLine(line, input.theme),
|
|
54
|
+
});
|
|
55
|
+
// Stock pi paints the details-derived warning last, so it is appended instead
|
|
56
|
+
// of passed into the body builder.
|
|
57
|
+
text += truncatedNotice(
|
|
58
|
+
{
|
|
59
|
+
limitCount: input.details?.entryLimitReached,
|
|
60
|
+
limitLabel: "entries limit",
|
|
61
|
+
truncation: input.details?.truncation,
|
|
62
|
+
},
|
|
63
|
+
input.theme,
|
|
64
|
+
);
|
|
65
|
+
return text;
|
|
66
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { getCapabilities, hyperlink } from "@earendil-works/pi-tui";
|
|
5
|
+
import { TOKEN, type StyleTheme } from "./tokens.ts";
|
|
6
|
+
|
|
7
|
+
// The path display the built-in tool headers share. The host does not export
|
|
8
|
+
// `renderToolPath`, `shortenPath` or `linkPath`, so a header of this package has
|
|
9
|
+
// to reproduce them from the primitives it does export (`hyperlink`, the
|
|
10
|
+
// terminal capabilities and the two colors below). Everything here is display:
|
|
11
|
+
// the text is shortened for the eye while the link still targets the absolute
|
|
12
|
+
// path, so a click opens the file the tool actually read.
|
|
13
|
+
|
|
14
|
+
// Only the home directory is shortened. The built-in never makes the path
|
|
15
|
+
// relative to the cwd, so a file outside the home directory keeps its full path.
|
|
16
|
+
export function shortenPath(path: string): string {
|
|
17
|
+
const home = homedir();
|
|
18
|
+
return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The target of the link: the argument as the tool itself resolves it, with `~`
|
|
22
|
+
// expanded and a relative path anchored at the cwd. A path that is already
|
|
23
|
+
// absolute passes through `resolve` untouched.
|
|
24
|
+
export function absolutePath(rawPath: string, cwd: string | undefined): string {
|
|
25
|
+
const expanded = rawPath === "~" || rawPath.startsWith("~/") ? `${homedir()}${rawPath.slice(1)}` : rawPath;
|
|
26
|
+
return resolve(cwd ?? process.cwd(), expanded);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// OSC 8, gated on the terminal capability exactly like the built-in, so a
|
|
30
|
+
// terminal without hyperlink support shows the styled text alone.
|
|
31
|
+
export function linkPath(styledText: string, rawPath: string, cwd: string | undefined): string {
|
|
32
|
+
if (!getCapabilities().hyperlinks) return styledText;
|
|
33
|
+
return hyperlink(styledText, pathToFileURL(absolutePath(rawPath, cwd)).href);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// An empty path is the argument that has not arrived yet, which the built-in
|
|
37
|
+
// renders as a placeholder instead of an empty slot.
|
|
38
|
+
export function renderToolPath(rawPath: string, theme: StyleTheme, cwd: string | undefined): string {
|
|
39
|
+
if (rawPath === "") return theme.fg(TOKEN.plain, "...");
|
|
40
|
+
return linkPath(theme.fg(TOKEN.path, shortenPath(rawPath)), rawPath, cwd);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The one cwd-relative form the built-in shows: a path inside the cwd becomes
|
|
44
|
+
// relative, anything else stays absolute, and the separators are made posix so
|
|
45
|
+
// the label reads the same on every platform.
|
|
46
|
+
export function relativeToCwdOrAbsolute(filePath: string, cwd: string | undefined): string {
|
|
47
|
+
const base = resolve(cwd ?? process.cwd());
|
|
48
|
+
const absolute = resolve(filePath);
|
|
49
|
+
const relativePath = relative(base, absolute);
|
|
50
|
+
const inside =
|
|
51
|
+
relativePath === "" ||
|
|
52
|
+
(relativePath !== ".." && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));
|
|
53
|
+
return (inside ? relativePath || "." : absolute).split(sep).join("/");
|
|
54
|
+
}
|