Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MdNode, CodeBlockMdNode } from '@toast-ui/editor';
import type { HTMLToken } from '@toast-ui/toastmark';
import { PrismJs } from '@t/index';
import { escapeXml } from '@/utils/common';

const BACKTICK_COUNT = 3;

Expand All @@ -17,6 +18,7 @@ export function getHTMLRenderers(prism: PrismJs) {
}

let content = node.literal!;
let contentEscaped = false;

if (infoWords.length && infoWords[0].length) {
const [lang] = infoWords;
Expand All @@ -28,9 +30,12 @@ export function getHTMLRenderers(prism: PrismJs) {

if (registeredLang) {
content = prism.highlight(node.literal!, registeredLang, lang);
contentEscaped = true;
}
}

content = contentEscaped ? content : escapeXml(content);

return [
{ type: 'openTag', tagName: 'pre', classNames: preClasses },
{ type: 'openTag', tagName: 'code', attributes: codeAttrs },
Expand Down
25 changes: 25 additions & 0 deletions plugins/code-syntax-highlight/src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
export function flatten<T>(arr: T[]): T[] {
return arr.reduce<T[]>((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
}

const XMLSPECIAL = '[&<>"]';
const reXmlSpecial = new RegExp(XMLSPECIAL, 'g');

function replaceUnsafeChar(char: string) {
switch (char) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
default:
return char;
}
}

export function escapeXml(text: string) {
if (reXmlSpecial.test(text)) {
return text.replace(reXmlSpecial, replaceUnsafeChar);
}
return text;
}