Skip to content

Instantly share code, notes, and snippets.

@dceddia
Last active August 26, 2020 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dceddia/d1d81e832989b3362a17a72b35184ddf to your computer and use it in GitHub Desktop.
Save dceddia/d1d81e832989b3362a17a72b35184ddf to your computer and use it in GitHub Desktop.
Given a code block, use the first few lines to infer what to highlight when generating syntax-highlighted HTML via Shiki
/* If the block begins with the `highlightLines: []` directive, strip that off,
parse the array as JSON, and pass the lines to Shiki.
Replaces single quotes with doubles, because I know I'm gonna screw that up.
Valid formats include:
highlightLines:[]
highlightLines []
// highlightLines: []
/// highlightLines: []
*/
function extractLineHighlights(codeBlock) {
// Remove highlight directives from the code block
// (there can be more than one)
const HIGHLIGHT_REGEX = /^\/{0,3}?\s*(highlightLines|highlight|addLines|add|deleteLines|delete|focusLines|focus).*(\[.*\])/;
let match;
let result = {};
let remainingCodeLines = codeBlock.split('\n');
// Look for highlight directives
while (
(match = (remainingCodeLines[0] && remainingCodeLines[0]).match(
HIGHLIGHT_REGEX
))
) {
// Pull off the first line
const highlightSpec = remainingCodeLines.shift();
// Parse the array of line numbers
let [fullMatch, highlightType, linesJSON] = match;
result[highlightType] = JSON.parse(linesJSON);
}
// Put the rest of the lines back together
result.codeBlock = remainingCodeLines.join('\n');
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment