Skip to content

Commit 4da018f

Browse files
BenKoncsikclaude
andcommitted
Add IDE-style syntax highlighting to the diff view (highlight.js)
Pick the language from the file extension/name (all highlight.js languages bundled) and colour the diff like an IDE. The whole file is highlighted in one pass so multi-line constructs (block comments, template strings) stay coloured, then split into per-line fragments that drop into the existing one-cell-per-line diff grid. Lives entirely in the shared graph-webview renderer, so all three hosts (VS Code, VS, browser demo) get it for free. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 588059e commit 4da018f

5 files changed

Lines changed: 322 additions & 14 deletions

File tree

‎package-lock.json‎

Lines changed: 11 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/graph-webview/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
},
1010
"dependencies": {
1111
"@rev-graph/graph-core": "0.1.0",
12-
"@rev-graph/protocol": "0.1.0"
12+
"@rev-graph/protocol": "0.1.0",
13+
"highlight.js": "^11.11.1"
1314
}
1415
}

‎packages/graph-webview/src/diffView.ts‎

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { t } from "./i18n.js";
22
import { computeLineDiff, type DiffRow } from "@rev-graph/graph-core";
33
import type { FileDiff } from "@rev-graph/protocol";
4+
import { highlightToLines } from "./highlight.js";
45

56
/**
67
* The side-by-side file-diff renderer, shared by the "View changes" dialog and
@@ -52,10 +53,11 @@ export function buildContentView(filePath: string, text: string, minimap: boolea
5253
wrap.appendChild(headerCell(filePath, 2));
5354
if (minimap) wrap.appendChild(spacerCell("end"));
5455
const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
56+
const html = highlightToLines(text, filePath);
5557
const mini: MiniRow[] = [];
5658
lines.forEach((line, i) => {
5759
wrap.appendChild(numCell(i + 1, "ctx"));
58-
wrap.appendChild(codeCell(line, "ctx"));
60+
wrap.appendChild(codeCell(html[i] ?? "", "ctx"));
5961
if (minimap) wrap.appendChild(spacerCell());
6062
mini.push({ kind: "ctx", text: line });
6163
});
@@ -73,9 +75,11 @@ export function buildContentView(filePath: string, text: string, minimap: boolea
7375
* the old (left) side for a deletion.
7476
*/
7577
export function buildDiffView(d: FileDiff, minimap: boolean): DiffView {
76-
if (d.status === "added") return singleColumn(d.newText, "add", "changes.changed", minimap);
77-
if (d.status === "deleted") return singleColumn(d.oldText, "del", "changes.original", minimap);
78-
return sideBySide(computeLineDiff(d.oldText, d.newText), minimap);
78+
if (d.status === "added") return singleColumn(d.newText, d.path, "add", "changes.changed", minimap);
79+
if (d.status === "deleted") return singleColumn(d.oldText, d.path, "del", "changes.original", minimap);
80+
const oldHtml = highlightToLines(d.oldText, d.path);
81+
const newHtml = highlightToLines(d.newText, d.path);
82+
return sideBySide(computeLineDiff(d.oldText, d.newText), oldHtml, newHtml, minimap);
7983
}
8084

8185
/** Append a fixed-width gutter cell reserving room for a minimap strip. */
@@ -88,6 +92,7 @@ function spacerCell(anchor?: "mid" | "end"): HTMLElement {
8892
/** A one-sided view (added → new only, deleted → old only). */
8993
function singleColumn(
9094
text: string,
95+
path: string,
9196
kind: "add" | "del",
9297
headerKey: "changes.original" | "changes.changed",
9398
minimap: boolean,
@@ -100,14 +105,15 @@ function singleColumn(
100105
wrap.appendChild(headerCell(t(headerKey), 2));
101106
if (minimap) wrap.appendChild(spacerCell("end"));
102107
const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
108+
const html = highlightToLines(text, path);
103109
// Every line is a change here, so the whole file is a single contiguous block.
104110
const blocks: HTMLElement[] = [];
105111
const mini: MiniRow[] = [];
106112
lines.forEach((line, i) => {
107113
const num = numCell(i + 1, kind);
108114
if (i === 0) blocks.push(num);
109115
wrap.appendChild(num);
110-
wrap.appendChild(codeCell(line, kind));
116+
wrap.appendChild(codeCell(html[i] ?? "", kind));
111117
if (minimap) wrap.appendChild(spacerCell());
112118
mini.push({ kind, text: line });
113119
});
@@ -116,8 +122,11 @@ function singleColumn(
116122
return { view: wrap, blocks, minimaps };
117123
}
118124

119-
/** A two-column side-by-side view aligned by computeLineDiff. */
120-
function sideBySide(rows: DiffRow[], minimap: boolean): DiffView {
125+
/**
126+
* A two-column side-by-side view aligned by computeLineDiff. `leftHtml`/`rightHtml`
127+
* are the syntax-highlighted lines of the old/new file, indexed by line number−1.
128+
*/
129+
function sideBySide(rows: DiffRow[], leftHtml: string[], rightHtml: string[], minimap: boolean): DiffView {
121130
const wrap = el("div", "diff-grid diff-grid-split");
122131
if (minimap) {
123132
wrap.classList.add("has-minimap");
@@ -138,11 +147,11 @@ function sideBySide(rows: DiffRow[], minimap: boolean): DiffView {
138147
// The leftmost cell of this row, used as the scroll anchor for a new block.
139148
const anchor = row.left ? numCell(row.left.num, leftKind) : fillerCell();
140149
wrap.appendChild(anchor);
141-
wrap.appendChild(row.left ? codeCell(row.left.text, leftKind) : fillerCell());
150+
wrap.appendChild(row.left ? codeCell(leftHtml[row.left.num - 1] ?? "", leftKind) : fillerCell());
142151
if (minimap) wrap.appendChild(spacerCell());
143152
if (row.right) {
144153
wrap.appendChild(numCell(row.right.num, rightKind));
145-
wrap.appendChild(codeCell(row.right.text, rightKind));
154+
wrap.appendChild(codeCell(rightHtml[row.right.num - 1] ?? "", rightKind));
146155
} else {
147156
wrap.appendChild(fillerCell());
148157
wrap.appendChild(fillerCell());
@@ -380,9 +389,13 @@ function headerCell(text: string, span: number): HTMLElement {
380389
function numCell(num: number, kind: CellKind): HTMLElement {
381390
return el("div", `diff-num diff-${kind}`, String(num));
382391
}
383-
function codeCell(text: string, kind: CellKind): HTMLElement {
384-
// Render an empty line as a non-breaking space so the row keeps its height.
385-
return el("div", `diff-code diff-${kind}`, text === "" ? " " : text);
392+
function codeCell(html: string, kind: CellKind): HTMLElement {
393+
// `html` is highlight.js output (or "" for a blank line). Its source text is
394+
// already escaped and the only tags are highlight.js's own spans, so assigning
395+
// via innerHTML is safe. A blank line gets a non-breaking space to keep height.
396+
const c = el("div", `diff-code diff-${kind}`);
397+
c.innerHTML = html === "" ? " " : html;
398+
return c;
386399
}
387400
function fillerCell(): HTMLElement {
388401
return el("div", "diff-num diff-empty");
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
import hljs from "highlight.js";
2+
3+
/**
4+
* Syntax highlighting for the diff view, powered by highlight.js (all bundled
5+
* languages). The language is picked from the file's extension/name — exactly
6+
* like an IDE — and the whole file is highlighted in one pass so multi-line
7+
* constructs (block comments, template strings) colour correctly, then the
8+
* coloured HTML is split into per-line fragments that drop straight into the
9+
* existing one-cell-per-line diff grid.
10+
*
11+
* The returned strings are HTML: every bit of source text is escaped by
12+
* highlight.js, and the only tags are highlight.js's own `<span class="hljs-…">`
13+
* wrappers, so it is safe to assign via `innerHTML`.
14+
*/
15+
16+
/**
17+
* Extensions whose highlight.js language id differs from the extension itself.
18+
* Extensions that already equal a known language alias (js, ts, py, rb, cs,
19+
* cpp, rs, go, php, sql, json, xml, css, scss, yaml, md, …) are resolved
20+
* directly by {@link hljs.getLanguage} and need no entry here.
21+
*/
22+
const EXT_TO_LANG: Record<string, string> = {
23+
// JS/TS family
24+
mjs: "javascript",
25+
cjs: "javascript",
26+
jsx: "javascript",
27+
tsx: "typescript",
28+
mts: "typescript",
29+
cts: "typescript",
30+
// C / C++ headers and variants
31+
h: "cpp",
32+
hpp: "cpp",
33+
hh: "cpp",
34+
hxx: "cpp",
35+
cc: "cpp",
36+
cxx: "cpp",
37+
"c++": "cpp",
38+
// web / markup
39+
htm: "xml",
40+
xhtml: "xml",
41+
vue: "xml",
42+
svg: "xml",
43+
svelte: "xml",
44+
cshtml: "xml",
45+
razor: "xml",
46+
// shells
47+
sh: "bash",
48+
zsh: "bash",
49+
bash: "bash",
50+
ksh: "bash",
51+
// config / data
52+
yml: "yaml",
53+
toml: "ini",
54+
cfg: "ini",
55+
conf: "ini",
56+
jsonc: "json",
57+
json5: "json",
58+
// misc languages
59+
kt: "kotlin",
60+
kts: "kotlin",
61+
rs: "rust",
62+
py: "python",
63+
pyw: "python",
64+
rb: "ruby",
65+
pl: "perl",
66+
pm: "perl",
67+
ps1: "powershell",
68+
psm1: "powershell",
69+
gradle: "groovy",
70+
groovy: "groovy",
71+
scala: "scala",
72+
ex: "elixir",
73+
exs: "elixir",
74+
erl: "erlang",
75+
clj: "clojure",
76+
cljs: "clojure",
77+
dart: "dart",
78+
hs: "haskell",
79+
lua: "lua",
80+
r: "r",
81+
jl: "julia",
82+
m: "objectivec",
83+
mm: "objectivec",
84+
swift: "swift",
85+
vb: "vbnet",
86+
fs: "fsharp",
87+
fsx: "fsharp",
88+
proto: "protobuf",
89+
tf: "terraform",
90+
tsv: "plaintext",
91+
md: "markdown",
92+
markdown: "markdown",
93+
tex: "latex",
94+
styl: "stylus",
95+
less: "less",
96+
bat: "dos",
97+
cmd: "dos",
98+
ino: "cpp",
99+
};
100+
101+
/** Bare filenames (no useful extension) that map to a language. */
102+
const NAME_TO_LANG: Record<string, string> = {
103+
dockerfile: "dockerfile",
104+
containerfile: "dockerfile",
105+
makefile: "makefile",
106+
"cmakelists.txt": "cmake",
107+
gnumakefile: "makefile",
108+
"gemfile": "ruby",
109+
"rakefile": "ruby",
110+
"vagrantfile": "ruby",
111+
".gitignore": "bash",
112+
".gitattributes": "bash",
113+
".bashrc": "bash",
114+
".zshrc": "bash",
115+
".profile": "bash",
116+
".env": "bash",
117+
};
118+
119+
/** Resolve a file path to a highlight.js language id, or null if unknown. */
120+
export function languageForPath(path: string): string | null {
121+
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
122+
const base = path.slice(slash + 1).toLowerCase();
123+
124+
const byName = NAME_TO_LANG[base];
125+
if (byName && hljs.getLanguage(byName)) return byName;
126+
127+
const dot = base.lastIndexOf(".");
128+
if (dot <= 0) {
129+
// No extension (e.g. "Dockerfile" already handled, "LICENSE" → none).
130+
return hljs.getLanguage(base) ? base : null;
131+
}
132+
const ext = base.slice(dot + 1);
133+
134+
const mapped = EXT_TO_LANG[ext];
135+
if (mapped && hljs.getLanguage(mapped)) return mapped;
136+
// Many extensions are themselves registered language ids/aliases.
137+
if (hljs.getLanguage(ext)) return ext;
138+
return null;
139+
}
140+
141+
/** HTML-escape a raw source line (used when no language is known). */
142+
function escapeHtml(s: string): string {
143+
return s.replace(/[&<>]/g, (c) => (c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&gt;"));
144+
}
145+
146+
/** Split text into lines the same way the diff does: "" → none, drop one trailing "\n". */
147+
function splitLines(text: string): string[] {
148+
if (text === "") return [];
149+
const lines = text.split("\n");
150+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
151+
return lines;
152+
}
153+
154+
/**
155+
* Split a highlight.js HTML string into one self-contained fragment per source
156+
* line. highlight.js emits literal "\n" between lines and never splits a tag
157+
* across one, so we walk the string tracking the stack of open `<span>` tags:
158+
* at each newline we close every open span (so the line is valid on its own)
159+
* and re-open the same stack on the next line. This keeps multi-line tokens
160+
* (block comments, template literals) coloured on every line they span.
161+
*/
162+
function splitHighlightedLines(html: string): string[] {
163+
const lines: string[] = [];
164+
const open: string[] = []; // stack of opening "<span …>" tags currently in effect
165+
let cur = "";
166+
let i = 0;
167+
while (i < html.length) {
168+
const ch = html[i];
169+
if (ch === "<") {
170+
const end = html.indexOf(">", i);
171+
const tag = end < 0 ? html.slice(i) : html.slice(i, end + 1);
172+
if (tag.startsWith("</")) open.pop();
173+
else open.push(tag);
174+
cur += tag;
175+
i += tag.length;
176+
} else if (ch === "\n") {
177+
cur += "</span>".repeat(open.length); // close open spans to end the line cleanly
178+
lines.push(cur);
179+
cur = open.join(""); // re-open them so the next line continues the same tokens
180+
i++;
181+
} else {
182+
let j = i;
183+
while (j < html.length && html[j] !== "<" && html[j] !== "\n") j++;
184+
cur += html.slice(i, j);
185+
i = j;
186+
}
187+
}
188+
lines.push(cur);
189+
return lines;
190+
}
191+
192+
/**
193+
* Highlight a file's text and return one HTML fragment per line, aligned with
194+
* the diff's line numbering ({@link splitLines}). Falls back to plain escaped
195+
* lines when the language is unknown or highlighting throws.
196+
*/
197+
export function highlightToLines(text: string, path: string): string[] {
198+
if (text === "") return [];
199+
const body = text.replace(/\n$/, "");
200+
const lang = languageForPath(path);
201+
if (!lang) return splitLines(text).map(escapeHtml);
202+
try {
203+
const value = hljs.highlight(body, { language: lang, ignoreIllegal: true }).value;
204+
return splitHighlightedLines(value);
205+
} catch {
206+
return splitLines(text).map(escapeHtml);
207+
}
208+
}

0 commit comments

Comments
 (0)