Getting the highlighted code with CodeBlockLowlight and editor.getHTML() #6055
Unanswered
ile
asked this question in
Questions & Help
Replies: 1 comment
-
I was able to highlight the code with this. Would it be better to include something in the actual const getHighlightedHTML = (html) => {
// helper function to prevent XSS attacks when adding code as HTML
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "")
.replace(/'/g, "'");
}
function renderLowlightTree(nodes) {
let html = '';
nodes.forEach(node => {
if (node.type === 'text') {
html += escapeHtml(node.value);
} else if (node.type === 'element') {
let classNames = node.properties.className ? node.properties.className.join(' ') : '';
html += `<span class="${classNames}">${renderLowlightTree(node.children)}</span>`;
}
});
return html;
}
function highlightCodeBlocks(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const codeBlocks = doc.querySelectorAll('pre code');
codeBlocks.forEach(codeBlock => {
const language = codeBlock.className.replace('language-', '');
// const highlighted = lowlight.highlight(language, codeBlock.textContent);
let highlighted;
const languages = lowlight.listLanguages()
highlighted = (languages.includes(language) || lowlight.registered?.(language))
? lowlight.highlight(language, codeBlock.textContent)
: lowlight.highlightAuto(codeBlock.textContent)
const highlightedHTML = renderLowlightTree(highlighted.children);
codeBlock.innerHTML = highlightedHTML; // Replace the old content with the highlighted content.
});
return doc.body.innerHTML;
}
return highlightCodeBlocks(html);
}
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Using
CodeBlockLowlight
the code block is highlighted nicely in the editor view.But, getting the HTML from the editor with
editor.getHTML()
the code block has only the code, not a highlighted version.Is there a way to get the highlighted version with
editor.getHTML()
– or by creating a custom extension, extendingCodeBlockLowlight
?Seems like there isn't an easy way to do this, as AI struggled quite a bit with this? I'm new here also, so i may be missing something.
Beta Was this translation helpful? Give feedback.
All reactions