Last active
August 26, 2020 22:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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