in packages/docusaurus-theme-common/src/utils/codeBlockUtils.ts [106:171]
export function parseLines(
content: string,
metastring?: string,
language?: string,
): {
/**
* The highlighted lines, 0-indexed. e.g. `[0, 1, 4]` means the 1st, 2nd, and
* 5th lines are highlighted.
*/
highlightLines: number[];
/**
* The clean code without any magic comments (only if highlight range isn't
* present in the metastring).
*/
code: string;
} {
let code = content.replace(/\n$/, '');
// Highlighted lines specified in props: don't parse the content
if (metastring && highlightLinesRangeRegex.test(metastring)) {
const highlightLinesRange = metastring.match(highlightLinesRangeRegex)!
.groups!.range!;
const highlightLines = rangeParser(highlightLinesRange)
.filter((n) => n > 0)
.map((n) => n - 1);
return {highlightLines, code};
}
if (language === undefined) {
return {highlightLines: [], code};
}
const directiveRegex = getAllMagicCommentDirectiveStyles(language);
// go through line by line
const lines = code.split('\n');
let highlightBlockStart: number;
let highlightRange = '';
// loop through lines
for (let lineNumber = 0; lineNumber < lines.length; ) {
const line = lines[lineNumber]!;
const match = line.match(directiveRegex);
if (match !== null) {
const directive = match.slice(1).find((item) => item !== undefined);
switch (directive) {
case 'highlight-next-line':
highlightRange += `${lineNumber},`;
break;
case 'highlight-start':
highlightBlockStart = lineNumber;
break;
case 'highlight-end':
highlightRange += `${highlightBlockStart!}-${lineNumber - 1},`;
break;
default:
break;
}
lines.splice(lineNumber, 1);
} else {
// lines without directives are unchanged
lineNumber += 1;
}
}
const highlightLines = rangeParser(highlightRange);
code = lines.join('\n');
return {highlightLines, code};
}