Open History to see the last commit
1import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName";
2import {
3 parse,
4 type Command,
5 type DoubleQuotedChild,
6 type HereDoc,
7 type Word,
8 type WordPart,
9} from "unbash";
10
11/** starts[i]..ends[i] spans the original spelling of text[i], including escapes. */
12export interface EmbeddedScript {
13 readonly language: string;
14 readonly text: string;
15 readonly starts: ReadonlyArray<number>;
16 readonly ends: ReadonlyArray<number>;
17}
18
19export interface SyntaxToken {
20 readonly content: string;
21 readonly offset: number;
22 readonly color?: string;
23 readonly fontStyle?: number;
24}
25
26type TokenLines = ReadonlyArray<ReadonlyArray<SyntaxToken>>;
27
28interface MappedText {
29 readonly text: string;
30 readonly starts: ReadonlyArray<number>;
31 readonly ends: ReadonlyArray<number>;
32}
33
34interface Interpreter {
35 readonly language: string;
36 readonly inline: (flag: string) => boolean;
37 readonly shortFlags?: RegExp;
38 readonly valueOptions?: ReadonlySet<string>;
39 readonly scriptFileOptions?: ReadonlySet<string>;
40 /** A script file named `-` is read from stdin. */
41 readonly stdinScriptFile?: boolean;
42 readonly stdin: "always" | "without-script-file" | "never";
43 readonly positionalScript?: number;
44 readonly repeatable?: boolean;
45 readonly subcommand?: string;
46 /** PowerShell matches parameters case-insensitively; the lists above are lowercase. */
47 readonly ignoreCase?: boolean;
48}
49
50const MAX_DEPTH = 4;
51
52const flagIn =
53 (...flags: string[]) =>
54 (flag: string) =>
55 flags.includes(flag);
56
57const SHELL: Interpreter = {
58 language: "shellscript",
59 inline: (flag) => /^-[a-zA-Z]*c[a-zA-Z]*$/u.test(flag),
60 valueOptions: new Set(["-o", "-O", "--rcfile", "--init-file"]),
61 stdin: "without-script-file",
62};
63
64const PYTHON: Interpreter = {
65 language: "python",
66 // Bundles like -uc and -IBc; -W and -X take a value, so a c after them is that value.
67 inline: flagIn("-c"),
68 shortFlags: /^-(?!-)[bBdEiIOPqRsStuvx]*/u,
69 valueOptions: new Set(["-W", "-X"]),
70 scriptFileOptions: new Set(["-m"]),
71 stdin: "without-script-file",
72};
73
74const SQL_SHELL = {
75 language: "sql",
76 valueOptions: new Set([
77 "-d",
78 "-h",
79 "-u",
80 "-U",
81 "--dbname",
82 "--host",
83 "--user",
84 "--username",
85 "-separator",
86 "-nullvalue",
87 "-init",
88 ]),
89 stdin: "always",
90 repeatable: true,
91} satisfies Omit<Interpreter, "inline">;
92
93const INTERPRETERS: Record<string, Interpreter> = {
94 sh: SHELL,
95 bash: SHELL,
96 zsh: SHELL,
97 dash: SHELL,
98 ash: SHELL,
99 ksh: SHELL,
100 fish: {
101 language: "fish",
102 inline: flagIn("-c", "--command"),
103 // Bundles like -lc and -ic; a c after -C, -d, -o or -p is that option's value.
104 shortFlags: /^-(?!-)[hilnNPv]*/u,
105 stdin: "without-script-file",
106 },
107 node: {
108 language: "javascript",
109 inline: flagIn("-e", "--eval", "-p", "--print", "-pe"),
110 valueOptions: new Set([
111 "-r",
112 "--require",
113 "--import",
114 "--loader",
115 "-C",
116 "--conditions",
117 "--input-type",
118 "--env-file",
119 "--env-file-if-exists",
120 "--experimental-loader",
121 ]),
122 stdin: "without-script-file",
123 },
124 bun: { language: "typescript", inline: flagIn("-e", "--eval", "-p", "--print"), stdin: "never" },
125 deno: {
126 language: "typescript",
127 inline: () => false,
128 // `--env-file` takes its optional path only as `--env-file=path`.
129 valueOptions: new Set(["-c", "--config", "--import-map", "--ext"]),
130 stdin: "never",
131 subcommand: "eval",
132 },
133 ruby: {
134 language: "ruby",
135 // Bundles like -ne and -lane; -i, -I, -r and -C take a value, so an e after them is that value.
136 inline: flagIn("-e"),
137 shortFlags: /^-(?!-)(?:[acdlnpsSUvwy]|0[0-7]{0,3}|W[0-7]?|K[\x20-\x7e]?)*/u,
138 valueOptions: new Set(["-r", "-I", "-C"]),
139 stdin: "without-script-file",
140 repeatable: true,
141 },
142 perl: {
143 language: "perl",
144 // Bundles like -pe and -0777ne; in -pie or -Me the e is the value of -i or -M.
145 inline: flagIn("-e", "-E"),
146 shortFlags: /^-(?!-)(?:[acdfgnpsStTuUwWX]|0[0-7]{0,3}|l0?[0-7]{0,3})*/u,
147 // -M and -m take their module only attached (`-Mstrict`).
148 valueOptions: new Set(["-I"]),
149 stdin: "without-script-file",
150 repeatable: true,
151 },
152 osascript: {
153 language: "applescript",
154 inline: flagIn("-e"),
155 valueOptions: new Set(["-l", "-s"]),
156 stdin: "without-script-file",
157 },
158 pwsh: {
159 language: "powershell",
160 inline: flagIn("-c", "-command"),
161 valueOptions: new Set(["-executionpolicy", "-workingdirectory", "-windowstyle"]),
162 scriptFileOptions: new Set(["-f", "-file", "-encodedcommand"]),
163 stdin: "never",
164 ignoreCase: true,
165 },
166 psql: {
167 ...SQL_SHELL,
168 inline: flagIn("-c", "--command"),
169 // Bundles like -Atc and -Xtf; a c or f after -d, -h, -U and the like is that option's value.
170 shortFlags: /^-(?!-)[aAbeEHlnqsStwWxXz01]*/u,
171 scriptFileOptions: new Set(["-f", "--file"]),
172 stdinScriptFile: true,
173 },
174 mysql: {
175 ...SQL_SHELL,
176 inline: flagIn("-e", "--execute"),
177 // Bundles like -Ne and -sNe; an e after -D, -h, -u and the like is that option's value.
178 shortFlags: /^-(?!-)[AbBcCEfGHinNoqrstUvVwWX]*/u,
179 },
180 sqlite3: { ...SQL_SHELL, inline: flagIn("-cmd"), positionalScript: 1 },
181 duckdb: {
182 ...SQL_SHELL,
183 inline: flagIn("-c", "-cmd"),
184 scriptFileOptions: new Set(["-f"]),
185 positionalScript: 1,
186 },
187};
188INTERPRETERS.powershell = INTERPRETERS.pwsh!;
189INTERPRETERS.mariadb = INTERPRETERS.mysql!;
190
191const JXA: Interpreter = { ...INTERPRETERS.osascript!, language: "javascript" };
192
193/** `osascript -l JavaScript` runs JXA; the last `-l` option wins, and the name is case-sensitive. */
194function isJxa(args: ReadonlyArray<Word>): boolean {
195 let language = "AppleScript";
196 for (let index = 0; index < args.length; index += 1) {
197 const value = args[index]!.value;
198 if (value === "-l") language = args[++index]?.value ?? language;
199 else if (value.startsWith("-l")) language = value.slice(2);
200 else if (value === "-e" || value === "-s") index += 1;
201 else if (!value.startsWith("-") || value === "-" || value === "--") break;
202 }
203 return language === "JavaScript";
204}
205
206const PROGRAM_WRAPPERS: Record<string, ReadonlySet<string>> = {
207 env: new Set(["-u", "--unset", "-C", "--chdir"]),
208 sudo: new Set(["-u", "--user", "-g", "--group", "-C", "-D", "--chdir"]),
209 nice: new Set(["-n", "--adjustment"]),
210 nohup: new Set(),
211 exec: new Set(["-a"]),
212 command: new Set(),
213 builtin: new Set(),
214 timeout: new Set(["-k", "--kill-after", "-s", "--signal"]),
215};
216PROGRAM_WRAPPERS.gtimeout = PROGRAM_WRAPPERS.timeout!;
217
218const DELIMITER_LANGUAGES: Record<string, string> = {
219 py: "python",
220 python: "python",
221 js: "javascript",
222 javascript: "javascript",
223 ts: "typescript",
224 typescript: "typescript",
225 sql: "sql",
226 json: "json",
227 yaml: "yaml",
228 yml: "yaml",
229 toml: "toml",
230 sh: "shellscript",
231 bash: "shellscript",
232 shell: "shellscript",
233 rb: "ruby",
234 ruby: "ruby",
235 html: "html",
236 css: "css",
237 md: "markdown",
238 markdown: "markdown",
239 xml: "xml",
240 diff: "diff",
241 patch: "diff",
242};
243
244/** Returns nothing for commands that do not parse cleanly. */
245export function embeddedScripts(command: string): EmbeddedScript[] {
246 const identity = Array.from({ length: command.length }, (_, index) => index);
247 return scriptsIn(
248 { text: command, starts: identity, ends: identity.map((index) => index + 1) },
249 0,
250 );
251}
252
253function scriptsIn(source: MappedText, depth: number): EmbeddedScript[] {
254 const script = parse(source.text);
255 if (script.errors?.length) return [];
256 const found: EmbeddedScript[] = [];
257 forEachCommand(script.commands, (command) => {
258 for (const { language, mapped } of commandScripts(command, source.text)) {
259 if (mapped.text.trim() === "") continue;
260 const embedded: EmbeddedScript = {
261 language,
262 text: mapped.text,
263 starts: mapped.starts.map((start) => source.starts[start]!),
264 ends: mapped.ends.map((end) => source.ends[end - 1]!),
265 };
266 found.push(embedded);
267 if (language === "shellscript" && depth + 1 < MAX_DEPTH) {
268 found.push(...scriptsIn(embedded, depth + 1));
269 }
270 }
271 });
272 return found;
273}
274
275function isNode(value: unknown): value is { readonly type: string } {
276 return typeof value === "object" && value !== null && "type" in value;
277}
278
279function forEachCommand(
280 node: unknown,
281 visit: (command: Command) => void,
282 seen = new WeakSet<object>(),
283): void {
284 if (Array.isArray(node)) {
285 for (const child of node) forEachCommand(child, visit, seen);
286 return;
287 }
288 if (!isNode(node) || seen.has(node)) return;
289 seen.add(node);
290 switch (node.type) {
291 case "Command":
292 visit(node as Command);
293 break;
294 case "CommandExpansion":
295 case "ProcessSubstitution": {
296 const { script } = node as Extract<WordPart, { type: "CommandExpansion" }>;
297 if (script && !script.errors?.length && script.source === undefined) {
298 forEachCommand(script.commands, visit, seen);
299 }
300 return;
301 }
302 }
303 // Word parts are lazy getters, which Object.values skips.
304 if ("parts" in node) forEachCommand(node.parts, visit, seen);
305 for (const value of Object.values(node)) {
306 if (typeof value === "object") forEachCommand(value, visit, seen);
307 }
308}
309
310function programName(word: Word): string {
311 // Bash reads `C:\Python312\python.exe` unquoted as escapes; Windows meant a path.
312 const path = /\\/u.test(word.text) ? word.text.replace(/^["']|["']$/gu, "") : word.value;
313 return (path.split(/[\\/]/u).at(-1) ?? "").toLowerCase().replace(/\.exe$/u, "");
314}
315
316function interpreterFor(name: string): Interpreter | undefined {
317 if (/^python(?:\d+(?:\.\d+)?)?$|^pypy3?$|^py$/u.test(name)) return PYTHON;
318 return Object.hasOwn(INTERPRETERS, name) ? INTERPRETERS[name] : undefined;
319}
320
321function programIndex(words: ReadonlyArray<Word>): number {
322 let index = 0;
323 while (index < words.length) {
324 const name = programName(words[index]!);
325 if (!Object.hasOwn(PROGRAM_WRAPPERS, name)) return index;
326 const valueOptions = PROGRAM_WRAPPERS[name]!;
327 const isTimeout = name === "timeout" || name === "gtimeout";
328 index += 1;
329 let optionsEnded = false;
330 while (index < words.length) {
331 const value = words[index]!.value;
332 const isOption = !optionsEnded && value.startsWith("-");
333 if (isOption && value === "--") optionsEnded = true;
334 // `env -- FOO=1 cmd` still takes assignments after the options end.
335 if (isOption || /^[A-Za-z_]\w*=/u.test(value)) {
336 const takesValue =
337 isOption && (valueOptions.has(value) || (isTimeout && /^-[fpv]*[ks]$/u.test(value)));
338 index += takesValue ? 2 : 1;
339 } else {
340 break;
341 }
342 }
343 if (isTimeout) index += 1;
344 }
345 return index;
346}
347
348function commandScripts(
349 command: Command,
350 source: string,
351): Array<{ language: string; mapped: MappedText }> {
352 if (!command.name) return [];
353 const words = [command.name, ...command.args.filter((arg): arg is Word => arg.type === "Word")];
354 const index = programIndex(words);
355 const program = words[index];
356 if (!program) return [];
357 const name = programName(program);
358 const args = words.slice(index + 1);
359 const interpreter = name === "osascript" && isJxa(args) ? JXA : interpreterFor(name);
360 const scripts: Array<{ language: string; mapped: MappedText }> = [];
361
362 let readsStdinScript = false;
363 if (interpreter) {
364 const found = interpreterArgs(interpreter, args, name);
365 for (const script of found.scripts) {
366 const mapped = wordText(script.word, source);
367 if (!mapped) continue;
368 scripts.push({ language: interpreter.language, mapped: sliceMapped(mapped, script.start) });
369 }
370 readsStdinScript =
371 interpreter.stdin !== "never" &&
372 (found.useStdin || (found.scripts.length === 0 && !found.scriptFromFile));
373 }
374
375 const stdinLanguage = readsStdinScript ? interpreter?.language : undefined;
376 const writtenLanguage = writtenFileLanguage(name, command, args);
377 for (const redirect of command.redirects) {
378 const toStdin = isDescriptor(redirect.descriptor, 0);
379 if (redirect.type === "HereString" && toStdin && stdinLanguage && redirect.target) {
380 const mapped = wordText(redirect.target, source);
381 if (mapped) scripts.push({ language: stdinLanguage, mapped });
382 }
383 if (redirect.type === "HereDoc") {
384 const language =
385 (toStdin ? (stdinLanguage ?? writtenLanguage) : undefined) ?? delimiterLanguage(redirect);
386 if (language) scripts.push({ language, mapped: hereDocText(redirect, source) });
387 }
388 }
389 return scripts;
390}
391
392function isDescriptor(descriptor: HereDoc["descriptor"], fd: number): boolean {
393 return (
394 descriptor === undefined || (descriptor.type === "FileDescriptor" && descriptor.value === fd)
395 );
396}
397
398interface ScriptArgument {
399 readonly word: Word;
400 readonly start: number;
401}
402
403function interpreterArgs(
404 interpreter: Interpreter,
405 args: ReadonlyArray<Word>,
406 program: string,
407): { scripts: ScriptArgument[]; scriptFromFile: boolean; useStdin?: boolean } {
408 const positionals: Word[] = [];
409 const scripts: ScriptArgument[] = [];
410 const whole = (word: Word): ScriptArgument => ({ word, start: 0 });
411 let optionsEnded = false;
412 let scriptFromFile = false;
413 let shellInline = false;
414 let useStdin = false;
415 for (let index = 0; index < args.length; index += 1) {
416 const arg = args[index]!;
417 const flag = interpreter.ignoreCase ? arg.value.toLowerCase() : arg.value;
418 if (!optionsEnded && (flag === "--" || (shellInline && flag === "-"))) {
419 optionsEnded = true;
420 continue;
421 }
422 if (
423 !optionsEnded &&
424 (flag.startsWith("-") || (interpreter === SHELL && flag.startsWith("+"))) &&
425 flag !== "-"
426 ) {
427 let [name = flag, value] = flag.startsWith("--") ? flag.split(/=(.*)/su) : [flag];
428 const at = interpreter.shortFlags?.exec(flag)?.[0].length;
429 if (at && at < flag.length) [name, value] = [`-${flag[at]}`, flag.slice(at + 1) || undefined];
430 if (interpreter.scriptFileOptions?.has(name)) {
431 if (!interpreter.repeatable) return { scripts, scriptFromFile: true };
432 const file = value ?? args[index + 1]?.value;
433 if (file === undefined) return { scripts, scriptFromFile: true };
434 if (interpreter.stdinScriptFile && file === "-") useStdin = true;
435 // SQL shells run `-f` files and `-c` statements alike, in order.
436 scriptFromFile = true;
437 if (value === undefined) index += 1;
438 continue;
439 }
440 if (interpreter === SHELL) {
441 // bash, dash, and sh accept `--long` options only before `-c` or `-s`.
442 if ((shellInline || useStdin) && name.startsWith("--") && LONG_OPTIONS_FIRST.has(program)) {
443 return { scripts, scriptFromFile: true };
444 }
445 // zsh and ksh attach `-o` names (`-oshwordsplit`).
446 const opts = program === "zsh" || program === "ksh" ? flag.split("o", 1)[0]! : flag;
447 // `-c` makes the first operand the script, so more options may follow it.
448 if (interpreter.inline(opts)) shellInline = true;
449 // `-s` reads the script from stdin even with operands.
450 if (/^[+-][a-zA-Z]*s[a-zA-Z]*$/u.test(opts)) useStdin = opts[0] === "-";
451 if (value === undefined) index += shellOptionValues(program, flag);
452 continue;
453 }
454 if (interpreter.inline(name)) {
455 const next = args[index + 1];
456 if (value !== undefined) scripts.push({ word: arg, start: flag.length - value.length });
457 else if (next) scripts.push(whole(next));
458 else return { scripts, scriptFromFile: true };
459 if (!interpreter.repeatable) return { scripts, scriptFromFile };
460 if (value === undefined) index += 1;
461 continue;
462 }
463 if (value === undefined && interpreter.valueOptions?.has(name)) index += 1;
464 continue;
465 }
466 if (shellInline) return { scripts: [whole(arg)], scriptFromFile: false };
467 positionals.push(arg);
468 if (interpreter.stdin === "without-script-file" && !interpreter.subcommand) break;
469 }
470 if (shellInline) return { scripts, scriptFromFile: true };
471
472 if (interpreter.subcommand) {
473 if (positionals[0]?.value !== interpreter.subcommand) return { scripts, scriptFromFile: true };
474 return { scripts: positionals.slice(1, 2).map(whole), scriptFromFile: false };
475 }
476 if (interpreter.positionalScript !== undefined) {
477 scripts.push(...positionals.slice(interpreter.positionalScript).map(whole));
478 }
479 // SQL shells take databases as positional arguments, not script files.
480 if (interpreter.stdin === "always" || useStdin) return { scripts, scriptFromFile, useStdin };
481 const first = positionals[0];
482 return { scripts, scriptFromFile: first !== undefined && first.value !== "-" };
483}
484
485const LONG_OPTIONS_FIRST = new Set(["bash", "dash", "sh"]);
486
487/** How many following words a shell option consumes as values. */
488function shellOptionValues(program: string, flag: string): number {
489 if (flag.startsWith("--")) {
490 return (program === "bash" || program === "sh") && SHELL.valueOptions?.has(flag) ? 1 : 0;
491 }
492 // zsh and ksh take an `-o` value attached (`-oextendedglob`); other shells read one word per o or O in a bundle (`-oe pipefail`).
493 if (program === "zsh" || program === "ksh") {
494 return /^[-+][a-zA-Z]+$/u.test(flag) && flag.indexOf("o") === flag.length - 1 ? 1 : 0;
495 }
496 return /^[-+][a-zA-Z]+$/u.test(flag) ? (flag.match(/[oO]/gu)?.length ?? 0) : 0;
497}
498
499function sliceMapped(mapped: MappedText, start: number): MappedText {
500 if (start === 0) return mapped;
501 return {
502 text: mapped.text.slice(start),
503 starts: mapped.starts.slice(start),
504 ends: mapped.ends.slice(start),
505 };
506}
507
508function writtenFileLanguage(
509 name: string,
510 command: Command,
511 args: ReadonlyArray<Word>,
512): string | undefined {
513 let path: string | undefined;
514 if (name === "cat") {
515 for (const redirect of command.redirects) {
516 if (
517 redirect.type === "Redirect" &&
518 [">", ">>", ">|", "&>", "&>>"].includes(redirect.operator) &&
519 isDescriptor(redirect.descriptor, 1)
520 ) {
521 path = redirect.target?.value;
522 }
523 }
524 } else if (name === "tee") {
525 path = args.find((arg) => !arg.value.startsWith("-"))?.value;
526 }
527 if (!path) return undefined;
528 const language = getFiletypeFromFileName(path);
529 return language === "text" ? undefined : language;
530}
531
532function delimiterLanguage(hereDoc: HereDoc): string | undefined {
533 const name = hereDoc.delimiter?.value.toLowerCase();
534 return name && Object.hasOwn(DELIMITER_LANGUAGES, name) ? DELIMITER_LANGUAGES[name] : undefined;
535}
536
537function hereDocText(hereDoc: HereDoc, source: string): MappedText {
538 const { pos, end } = hereDoc.body;
539 const starts = Array.from({ length: end - pos }, (_, index) => pos + index);
540 return {
541 text: source.slice(pos, end),
542 starts,
543 ends: starts.map((start) => start + 1),
544 };
545}
546
547// Preserve literal expansions; return undefined for unmappable spellings.
548function wordText(word: Word, source: string): MappedText | undefined {
549 const builder = new MappedTextBuilder();
550 const parts: ReadonlyArray<WordPart> = word.parts ?? [
551 { type: "Literal", pos: word.pos, end: word.end, text: word.text, value: word.value },
552 ];
553 for (const part of parts) {
554 switch (part.type) {
555 case "Literal":
556 if (!builder.addEscaped(part, false)) return undefined;
557 break;
558 case "SingleQuoted":
559 builder.addRaw(part.value, part.pos + 1);
560 break;
561 case "DoubleQuoted":
562 case "LocaleString":
563 for (const child of part.parts) {
564 if (!builder.addDoubleQuotedChild(child)) return undefined;
565 }
566 break;
567 case "AnsiCQuoted":
568 // $'…' escapes such as \x41 do not map character for character.
569 if (part.value !== part.text.slice(2, -1)) return undefined;
570 builder.addRaw(part.value, part.pos + 2);
571 break;
572 default:
573 builder.addRaw(source.slice(part.pos, part.end), part.pos);
574 }
575 }
576 return builder.build();
577}
578
579class MappedTextBuilder {
580 private text = "";
581 private readonly starts: number[] = [];
582 private readonly ends: number[] = [];
583
584 addRaw(text: string, pos: number) {
585 for (let index = 0; index < text.length; index += 1) this.push(text[index]!, pos + index, 1);
586 }
587
588 addDoubleQuotedChild(child: DoubleQuotedChild): boolean {
589 if (child.type === "Literal") return this.addEscaped(child, true);
590 this.addRaw(child.text, child.pos);
591 return true;
592 }
593
594 addEscaped(literal: { pos: number; text: string; value: string }, doubleQuoted: boolean) {
595 const before = this.text.length;
596 const { text, pos } = literal;
597 for (let index = 0; index < text.length; index += 1) {
598 const next = text[index + 1];
599 if (
600 text[index] === "\\" &&
601 next !== undefined &&
602 (!doubleQuoted || '$`"\\\n'.includes(next))
603 ) {
604 // A backslash-newline joins lines and spells nothing.
605 if (next !== "\n") this.push(next, pos + index, 2);
606 index += 1;
607 } else {
608 this.push(text[index]!, pos + index, 1);
609 }
610 }
611 return this.text.slice(before) === literal.value;
612 }
613
614 build(): MappedText {
615 return { text: this.text, starts: this.starts, ends: this.ends };
616 }
617
618 private push(character: string, start: number, length: number) {
619 this.text += character;
620 this.starts.push(start);
621 this.ends.push(start + length);
622 }
623}
624
625export function withEmbeddedScripts(
626 code: string,
627 lines: TokenLines,
628 embedded: ReadonlyArray<EmbeddedScript>,
629 tokenize: (text: string, language: string) => TokenLines,
630): TokenLines {
631 if (embedded.length === 0) return lines;
632 const styles = Array.from<SyntaxToken | undefined>({ length: code.length });
633 for (const token of lines.flat()) {
634 styles.fill(token, token.offset, token.offset + token.content.length);
635 }
636 for (const script of embedded) {
637 let scriptLines: TokenLines;
638 try {
639 scriptLines = tokenize(script.text, script.language);
640 } catch {
641 continue;
642 }
643 for (const token of scriptLines.flat()) {
644 if (token.content === "") continue;
645 const last = token.offset + token.content.length - 1;
646 styles.fill(token, script.starts[token.offset], script.ends[last]);
647 }
648 }
649 return restyledLines(code, styles);
650}
651
652function restyledLines(
653 code: string,
654 styles: ReadonlyArray<SyntaxToken | undefined>,
655): SyntaxToken[][] {
656 const lines: SyntaxToken[][] = [];
657 let start = 0;
658 for (const lineBreak of [...code.matchAll(/\r?\n/gu), undefined]) {
659 const end = lineBreak?.index ?? code.length;
660 const tokens: SyntaxToken[] = [];
661 for (let index = start; index < end;) {
662 const style = styles[index];
663 let next = index + 1;
664 while (
665 next < end &&
666 styles[next]?.color === style?.color &&
667 styles[next]?.fontStyle === style?.fontStyle
668 ) {
669 next += 1;
670 }
671 tokens.push({
672 content: code.slice(index, next),
673 offset: index,
674 ...(style?.color ? { color: style.color } : {}),
675 ...(style?.fontStyle ? { fontStyle: style.fontStyle } : {}),
676 });
677 index = next;
678 }
679 lines.push(tokens);
680 if (lineBreak) start = lineBreak.index + lineBreak[0].length;
681 }
682 return lines;
683}