MCPcopy Create free account
hub / github.com/sourcebot-dev/sourcebot / highlightCode

Function highlightCode

packages/web/src/lib/codeHighlight.ts:38–127  ·  view source on GitHub ↗
(
    languageName: string,
    input: string,
    highlighter: Highlighter,
    highlightRanges: { from: number; to: number }[] = [],
    callback: (
        text: string,
        style: string | null,
        from: number,
        to: number,
    ) => Output,
)

Source from the content-addressed store, hash-verified

36};
37
38export async function highlightCode<Output>(
39 languageName: string,
40 input: string,
41 highlighter: Highlighter,
42 highlightRanges: { from: number; to: number }[] = [],
43 callback: (
44 text: string,
45 style: string | null,
46 from: number,
47 to: number,
48 ) => Output,
49): Promise<Output[]> {
50 const parser = await getCodeParserByLanguageName(languageName);
51
52 const convertRangeToHighlightedSubranges = (
53 from: number,
54 to: number,
55 classes: string | null,
56 cb: (from: number, to: number, classes: string | null) => void,
57 ) => {
58 type HighlightRange = {
59 from: number;
60 to: number;
61 isHighlighted: boolean;
62 };
63
64 const highlightClasses = classes
65 ? `${classes} searchMatch-selected`
66 : 'searchMatch-selected';
67
68 let currentRange: HighlightRange | null = null;
69 for (let i = from; i < to; i++) {
70 const isHighlighted = isIndexHighlighted(i, highlightRanges);
71
72 if (currentRange) {
73 if (currentRange.isHighlighted === isHighlighted) {
74 currentRange.to = i + 1;
75 } else {
76 cb(
77 currentRange.from,
78 currentRange.to,
79 currentRange.isHighlighted ? highlightClasses : classes,
80 );
81
82 currentRange = { from: i, to: i + 1, isHighlighted };
83 }
84 } else {
85 currentRange = { from: i, to: i + 1, isHighlighted };
86 }
87 }
88
89 if (currentRange) {
90 cb(
91 currentRange.from,
92 currentRange.to,
93 currentRange.isHighlighted ? highlightClasses : classes,
94 );
95 }

Callers 1

Tested by

no test coverage detected