Skip to content

Commit

Permalink
Serialization: Do not escape Autolinks
Browse files Browse the repository at this point in the history
As stated in the Commonmark specs backslash escapes do not work in Autolinks,
so this prevents escaping Autolinks.

FIX: Don't escape characters in autolinks.

Closes #65
  • Loading branch information
susnux authored and marijnh committed Jun 23, 2022
1 parent 6099ce7 commit 48170d4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/to_markdown.ts
Expand Up @@ -112,18 +112,21 @@ export const defaultMarkdownSerializer = new MarkdownSerializer({
}
},
text(state, node) {
state.text(node.text!)
state.text(node.text!, !state.isAutolink)
}
}, {
em: {open: "*", close: "*", mixable: true, expelEnclosingWhitespace: true},
strong: {open: "**", close: "**", mixable: true, expelEnclosingWhitespace: true},
link: {
open(_state, mark, parent, index) {
return isPlainURL(mark, parent, index, 1) ? "<" : "["
_state.isAutolink = isPlainURL(mark, parent, index, 1)
return _state.isAutolink ? "<" : "["
},
close(_state, mark, parent, index) {
return isPlainURL(mark, parent, index, -1) ? ">"
const cont = _state.isAutolink ? ">"
: "](" + mark.attrs.href + (mark.attrs.title ? ' "' + mark.attrs.title.replace(/"/g, '\\"') + '"' : "") + ")"
_state.isAutolink = undefined
return cont
}
},
code: {open(_state, _mark, parent, index) { return backticksFor(parent.child(index), -1) },
Expand Down Expand Up @@ -159,6 +162,8 @@ export class MarkdownSerializerState {
out: string = ""
/// @internal
closed: Node | null = null
/// @intermal
isAutolink?: boolean = undefined
/// @internal
inTightList: boolean = false

Expand Down
14 changes: 14 additions & 0 deletions test/test-parse.ts
Expand Up @@ -184,6 +184,20 @@ describe("markdown", () => {
)
)

it("ensure no escapes in url", () =>
parse(
"[text](https://example.com/_file/#~anchor)",
doc(p(a({href: "https://example.com/_file/#~anchor"}, "text")))
)
)

it("ensure no escapes in autolinks", () =>
same(
"<https://example.com/_file/#~anchor>",
doc(p(a({href: "https://example.com/_file/#~anchor"}, "https://example.com/_file/#~anchor")))
)
)

it("escapes extra characters from options", () => {
let markdownSerializer = new MarkdownSerializer(defaultMarkdownSerializer.nodes,
defaultMarkdownSerializer.marks,
Expand Down

0 comments on commit 48170d4

Please sign in to comment.