Skip to content

Commit

Permalink
feat(2d): code range helpers (#947)
Browse files Browse the repository at this point in the history
  • Loading branch information
aarthificial committed Feb 9, 2024
1 parent 26e55a3 commit 044c9ac
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
51 changes: 51 additions & 0 deletions packages/2d/src/lib/code/CodeRange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,54 @@ export function inverseCodeRange(ranges: CodeRange[]): CodeRange[] {
[lastRange[1], [Infinity, Infinity]],
];
}

/**
* Find all code ranges that match the given pattern.
*
* @param code - The code to search in.
* @param pattern - Either a string or a regular expression to search for.
* @param limit - An optional limit on the number of ranges to find.
*/
export function findAllCodeRanges(
code: string,
pattern: string | RegExp,
limit = Infinity,
): CodeRange[] {
if (typeof pattern === 'string') {
pattern = new RegExp(pattern, 'g');
}

const matches = code.matchAll(pattern);
const ranges: CodeRange[] = [];
let index = 0;
let line = 0;
let column = 0;

for (const match of matches) {
if (match.index === undefined || ranges.length >= limit) {
continue;
}

let from: CodePoint = [line, column];
while (index <= code.length) {
if (index === match.index) {
from = [line, column];
}

if (index === match.index + match[0].length) {
ranges.push([from, [line, column]]);
break;
}

if (code[index] === '\n') {
line++;
column = 0;
} else {
column++;
}
index++;
}
}

return ranges;
}
28 changes: 28 additions & 0 deletions packages/2d/src/lib/components/Code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
codeSignal,
CodeSignalContext,
DefaultHighlightStyle,
findAllCodeRanges,
LezerHighlighter,
lines,
parseCodeSelection,
Expand Down Expand Up @@ -343,6 +344,33 @@ export class Code extends Shape {
).toSignal();
}

/**
* Find all code ranges that match the given pattern.
*
* @param pattern - Either a string or a regular expression to match.
*/
public findAllRanges(pattern: string | RegExp): CodeRange[] {
return findAllCodeRanges(this.parsed(), pattern);
}

/**
* Find the first code range that matches the given pattern.
*
* @param pattern - Either a string or a regular expression to match.
*/
public findFirstRange(pattern: string | RegExp): CodeRange {
return findAllCodeRanges(this.parsed(), pattern, 1)[0] ?? [[0, 0], [0, 0]];
}

/**
* Find the last code range that matches the given pattern.
*
* @param pattern - Either a string or a regular expression to match.
*/
public findLastRange(pattern: string | RegExp): CodeRange {
return findAllCodeRanges(this.parsed(), pattern).at(-1) ?? [[0, 0], [0, 0]];
}

protected override desiredSize(): SerializedVector2<DesiredLength> {
this.requestFontUpdate();
const context = this.cacheCanvas();
Expand Down

0 comments on commit 044c9ac

Please sign in to comment.