Assessor_2.0/server/gpo/xml-source-lines.ts

27 lines
849 B
TypeScript

export function xmlElementStartLines(text: string, pattern: RegExp): number[] {
if (!pattern.global) throw new Error('Der XML-Zeilenmatcher muss global sein.');
const masked = text.replace(/<!--[\s\S]*?-->/g, value => value.replace(/[^\r\n]/g, ' '));
const lines: number[] = [];
let cursor = 0;
let line = 1;
pattern.lastIndex = 0;
for (const match of masked.matchAll(pattern)) {
const matchIndex = match.index;
if (matchIndex === undefined) continue;
while (cursor < matchIndex) {
if (masked.charCodeAt(cursor) === 13) {
line += 1;
cursor += masked.charCodeAt(cursor + 1) === 10 ? 2 : 1;
} else if (masked.charCodeAt(cursor) === 10) {
line += 1;
cursor += 1;
} else {
cursor += 1;
}
}
lines.push(line);
}
pattern.lastIndex = 0;
return lines;
}