diff --git a/src/helpers.ts b/src/helpers.ts index 122c8922..edfeaa69 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -32,12 +32,20 @@ export function escapeHtmlEntities(html: string, encode?: boolean) { * replacement character. */ export function decodeNumericCharacterReferences(text: string) { - return text.replace(other.numericCharacterReference, (_, dec: string, hex: string) => { - const code = dec === undefined ? Number.parseInt(hex, 16) : Number.parseInt(dec, 10); + if (!other.numericCharacterReference.test(text)) { + return text; + } + // A decoded character must not join its neighbours into a new reference, + // so every `&` that is not already one is escaped here. + return text.replace(other.numericCharacterReferenceOrAmpersand, (ref: string, dec?: string, hex?: string) => { + if (dec === undefined && hex === undefined) { + return '&'; + } + const code = dec === undefined ? Number.parseInt(hex!, 16) : Number.parseInt(dec, 10); if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) { return '�'; } - return String.fromCodePoint(code); + return code === 38 ? '&' : String.fromCodePoint(code); }); } diff --git a/src/rules.ts b/src/rules.ts index ab939199..81da76a9 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -79,7 +79,8 @@ export const other = { endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, - numericCharacterReference: /(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/g, + numericCharacterReference: /(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/, + numericCharacterReferenceOrAmpersand: /(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, diff --git a/test/specs/new/numeric_character_references.html b/test/specs/new/numeric_character_references.html index 4a165f18..21736d57 100644 --- a/test/specs/new/numeric_character_references.html +++ b/test/specs/new/numeric_character_references.html @@ -3,3 +3,5 @@
�
&#abcdef0;
#
& <
+# © &
diff --git a/test/specs/new/numeric_character_references.md b/test/specs/new/numeric_character_references.md index 48441018..feadf1e9 100644 --- a/test/specs/new/numeric_character_references.md +++ b/test/specs/new/numeric_character_references.md @@ -10,3 +10,7 @@ renderExact: true abcdef0; `#` + +& < + +# © &