Skip to content

Commit d5dbd70

Browse files
authoredMay 11, 2024··
fix(markdown): entities and escapes not working properly (#3882)
1 parent 99c0cec commit d5dbd70

File tree

1 file changed

+48
-6
lines changed

1 file changed

+48
-6
lines changed
 
+48-6
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,53 @@
11
import type MarkdownIt from 'markdown-it'
2+
import type StateCore from 'markdown-it/lib/rules_core/state_core.mjs'
3+
import type Token from 'markdown-it/lib/token.mjs'
24

35
export function restoreEntities(md: MarkdownIt): void {
4-
md.core.ruler.disable('text_join')
5-
md.renderer.rules.text_special = (tokens, idx) => {
6-
if (tokens[idx].info === 'entity') {
7-
return tokens[idx].markup // leave as is so Vue can handle it
8-
}
9-
return md.utils.escapeHtml(tokens[idx].content)
6+
md.core.ruler.at('text_join', text_join)
7+
md.renderer.rules.text = (tokens, idx) => escapeHtml(tokens[idx].content)
8+
}
9+
10+
function text_join(state: StateCore): void {
11+
let curr, last
12+
const blockTokens = state.tokens
13+
const l = blockTokens.length
14+
15+
for (let j = 0; j < l; ++j) {
16+
if (blockTokens[j].type !== 'inline') continue
17+
18+
const tokens = blockTokens[j].children || []
19+
const max = tokens.length
20+
21+
for (curr = 0; curr < max; ++curr)
22+
if (tokens[curr].type === 'text_special') tokens[curr].type = 'text'
23+
24+
for (curr = last = 0; curr < max; ++curr)
25+
if (
26+
tokens[curr].type === 'text' &&
27+
curr + 1 < max &&
28+
tokens[curr + 1].type === 'text'
29+
) {
30+
tokens[curr + 1].content =
31+
getContent(tokens[curr]) + getContent(tokens[curr + 1])
32+
tokens[curr + 1].info = ''
33+
tokens[curr + 1].markup = ''
34+
} else {
35+
if (curr !== last) tokens[last] = tokens[curr]
36+
++last
37+
}
38+
39+
if (curr !== last) tokens.length = last
1040
}
1141
}
42+
43+
function getContent(token: Token): string {
44+
return token.info === 'entity'
45+
? token.markup
46+
: token.info === 'escape' && token.content === '&'
47+
? '&amp;'
48+
: token.content
49+
}
50+
51+
function escapeHtml(str: string): string {
52+
return str.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
53+
}

0 commit comments

Comments
 (0)
Please sign in to comment.