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
Expand Up @@ -324,9 +324,10 @@ public void visit(Code code) {
@Override
public void visit(Emphasis emphasis) {
String delimiter = emphasis.getOpeningDelimiter();
// Use delimiter that was parsed if available
if (delimiter == null) {
// When emphasis is nested, a different delimiter needs to be used
// Use delimiter that was parsed if available, but not if it would directly follow the same
// character (e.g. a literal "*" or an adjacent emphasis). Writing it then would merge the
// delimiter runs and change the meaning, so a different delimiter needs to be used.
if (delimiter == null || writer.getLastChar() == delimiter.charAt(0)) {
delimiter = writer.getLastChar() == '*' ? "_" : "*";
}
writer.raw(delimiter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.NodeRenderer;
import org.commonmark.renderer.html.HtmlRenderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
Expand Down Expand Up @@ -272,6 +273,14 @@ public void testStrongEmphasis() {
assertRoundTrip("foo**bar**\n");
}

@Test
public void testEmphasisDelimiterNextToSameLiteralCharacter() {
// When emphasis directly follows the same literal delimiter character (here a literal "*"),
// reusing the parsed delimiter would merge the delimiter runs and change the meaning on a
// re-parse. A different delimiter needs to be chosen so the Markdown round-trips.
assertStableRendering("*****Hello*world****\n");
}

@Test
public void testLinks() {
assertRoundTrip("[link](/uri)\n");
Expand Down Expand Up @@ -411,6 +420,17 @@ private void assertRoundTrip(String input) {
assertThat(rendered).isEqualTo(input);
}

// Checks that rendering to Markdown and parsing it again produces the same HTML, i.e. that the
// Markdown round-trip preserves the meaning even if the rendered Markdown differs from the
// input.
private void assertStableRendering(String input) {
HtmlRenderer htmlRenderer = HtmlRenderer.builder().build();
String expectedHtml = htmlRenderer.render(parse(input));
String markdown = parseAndRender(input);
String actualHtml = htmlRenderer.render(parse(markdown));
assertThat(actualHtml).isEqualTo(expectedHtml);
}

private String parseAndRender(String source) {
Node parsed = parse(source);
return render(parsed);
Expand Down