diff --git a/.idea/google-java-format.xml b/.idea/google-java-format.xml
new file mode 100644
index 000000000..05946a82a
--- /dev/null
+++ b/.idea/google-java-format.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkExtension.java b/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkExtension.java
index 7d5a74f30..14222121c 100644
--- a/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkExtension.java
+++ b/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkExtension.java
@@ -2,7 +2,6 @@
import java.util.EnumSet;
import java.util.Set;
-
import org.commonmark.Extension;
import org.commonmark.ext.autolink.internal.AutolinkPostProcessor;
import org.commonmark.parser.Parser;
@@ -10,14 +9,12 @@
/**
* Extension for automatically turning plain URLs and email addresses into links.
- *
- * Create it with {@link #create()} and then configure it on the builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
- *
- * The parsed links are turned into normal {@link org.commonmark.node.Link} nodes.
- *
+ *
+ *
Create it with {@link #create()} and then configure it on the builders ({@link
+ * org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
+ *
+ *
The parsed links are turned into normal {@link org.commonmark.node.Link} nodes.
*/
public class AutolinkExtension implements Parser.ParserExtension {
@@ -51,8 +48,8 @@ public static class Builder {
private Set linkTypes = EnumSet.allOf(AutolinkType.class);
/**
- * @param linkTypes the link types that should be converted. By default,
- * all {@link AutolinkType}s are converted.
+ * @param linkTypes the link types that should be converted. By default, all {@link
+ * AutolinkType}s are converted.
* @return {@code this}
*/
public Builder linkTypes(AutolinkType... linkTypes) {
@@ -64,8 +61,8 @@ public Builder linkTypes(AutolinkType... linkTypes) {
}
/**
- * @param linkTypes the link types that should be converted. By default,
- * all {@link AutolinkType}s are converted.
+ * @param linkTypes the link types that should be converted. By default, all {@link
+ * AutolinkType}s are converted.
* @return {@code this}
*/
public Builder linkTypes(Set linkTypes) {
diff --git a/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkType.java b/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkType.java
index 2c8c6574f..24249ef88 100644
--- a/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkType.java
+++ b/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/AutolinkType.java
@@ -1,19 +1,11 @@
package org.commonmark.ext.autolink;
-/**
- * The types of strings that can be automatically turned into links.
- */
+/** The types of strings that can be automatically turned into links. */
public enum AutolinkType {
- /**
- * URL such as {@code http://example.com}
- */
+ /** URL such as {@code http://example.com} */
URL,
- /**
- * Email address such as {@code foo@example.com}
- */
+ /** Email address such as {@code foo@example.com} */
EMAIL,
- /**
- * URL such as {@code www.example.com}
- */
+ /** URL such as {@code www.example.com} */
WWW
}
diff --git a/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/internal/AutolinkPostProcessor.java b/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/internal/AutolinkPostProcessor.java
index a381c2f19..124870fd2 100644
--- a/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/internal/AutolinkPostProcessor.java
+++ b/commonmark-ext-autolink/src/main/java/org/commonmark/ext/autolink/internal/AutolinkPostProcessor.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.autolink.internal;
+import java.util.*;
import org.commonmark.ext.autolink.AutolinkType;
import org.commonmark.node.*;
import org.commonmark.parser.PostProcessor;
@@ -8,8 +9,6 @@
import org.nibor.autolink.LinkType;
import org.nibor.autolink.Span;
-import java.util.*;
-
public class AutolinkPostProcessor implements PostProcessor {
private final LinkExtractor linkExtractor;
@@ -38,9 +37,7 @@ public AutolinkPostProcessor(Set linkTypes) {
}
}
- this.linkExtractor = LinkExtractor.builder()
- .linkTypes(types)
- .build();
+ this.linkExtractor = LinkExtractor.builder().linkTypes(types).build();
}
@Override
diff --git a/commonmark-ext-autolink/src/test/java/org/commonmark/ext/autolink/AutolinkTest.java b/commonmark-ext-autolink/src/test/java/org/commonmark/ext/autolink/AutolinkTest.java
index 82c3899fc..fb79dfd60 100644
--- a/commonmark-ext-autolink/src/test/java/org/commonmark/ext/autolink/AutolinkTest.java
+++ b/commonmark-ext-autolink/src/test/java/org/commonmark/ext/autolink/AutolinkTest.java
@@ -1,5 +1,9 @@
package org.commonmark.ext.autolink;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.*;
import org.commonmark.parser.IncludeSourceSpans;
@@ -8,64 +12,69 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class AutolinkTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(AutolinkExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
-
- private static final Set NO_WWW_EXTENSIONS = Set.of(AutolinkExtension.builder()
- .linkTypes(AutolinkType.URL, AutolinkType.EMAIL)
- .build());
- private static final Parser NO_WWW_PARSER = Parser.builder().extensions(NO_WWW_EXTENSIONS).build();
- private static final HtmlRenderer NO_WWW_RENDERER = HtmlRenderer.builder().extensions(NO_WWW_EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
+
+ private static final Set NO_WWW_EXTENSIONS =
+ Set.of(
+ AutolinkExtension.builder()
+ .linkTypes(AutolinkType.URL, AutolinkType.EMAIL)
+ .build());
+ private static final Parser NO_WWW_PARSER =
+ Parser.builder().extensions(NO_WWW_EXTENSIONS).build();
+ private static final HtmlRenderer NO_WWW_RENDERER =
+ HtmlRenderer.builder().extensions(NO_WWW_EXTENSIONS).build();
@Test
public void oneTextNode() {
- assertRendering("foo http://one.org/ bar http://two.org/",
+ assertRendering(
+ "foo http://one.org/ bar http://two.org/",
"
\n");
}
@Test
public void tricky() {
- assertRendering("http://example.com/one. Example 2 (see http://example.com/two). Example 3: http://example.com/foo_(bar)",
- "
- * The {@link #getLabel() label} is the text in brackets after {@code ^}, so {@code foo} in the example. The contents
- * of the footnote are child nodes of the definition, a {@link org.commonmark.node.Paragraph} in the example.
- *
- * Footnote definitions are parsed even if there's no corresponding {@link FootnoteReference}.
+ *
+ * The {@link #getLabel() label} is the text in brackets after {@code ^}, so {@code foo} in the
+ * example. The contents of the footnote are child nodes of the definition, a {@link
+ * org.commonmark.node.Paragraph} in the example.
+ *
+ *
Footnote definitions are parsed even if there's no corresponding {@link FootnoteReference}.
*/
public class FootnoteDefinition extends CustomBlock {
@@ -24,4 +27,3 @@ public String getLabel() {
return label;
}
}
-
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnoteReference.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnoteReference.java
index 61dcf8626..c0382fff1 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnoteReference.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnoteReference.java
@@ -4,9 +4,10 @@
/**
* A footnote reference, e.g. [^foo] in Some text with a footnote[^foo]
- *
- * The {@link #getLabel() label} is the text within brackets after {@code ^}, so {@code foo} in the example. It needs to
- * match the label of a corresponding {@link FootnoteDefinition} for the footnote to be parsed.
+ *
+ *
The {@link #getLabel() label} is the text within brackets after {@code ^}, so {@code foo} in
+ * the example. It needs to match the label of a corresponding {@link FootnoteDefinition} for the
+ * footnote to be parsed.
*/
public class FootnoteReference extends CustomNode {
private String label;
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnotesExtension.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnotesExtension.java
index dd532fa34..4517d14d6 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnotesExtension.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/FootnotesExtension.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.footnotes;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.ext.footnotes.internal.*;
import org.commonmark.parser.Parser;
@@ -9,32 +10,37 @@
import org.commonmark.renderer.markdown.MarkdownNodeRendererFactory;
import org.commonmark.renderer.markdown.MarkdownRenderer;
-import java.util.Set;
-
/**
* Extension for footnotes with syntax like GitHub Flavored Markdown:
+ *
*
* Some text with a footnote[^1].
*
* [^1]: The text of the footnote.
*
+ *
* The [^1] is a {@link FootnoteReference}, with "1" being the label.
- *
- * The line with [^1]: ... is a {@link FootnoteDefinition}, with the contents as child nodes (can be a
- * paragraph like in the example, or other blocks like lists).
- *
- * All the footnotes (definitions) will be rendered in a list at the end of a document, no matter where they appear in
- * the source. The footnotes will be numbered starting from 1, then 2, etc, depending on the order in which they appear
- * in the text (and not dependent on the label). The footnote reference is a link to the footnote, and from the footnote
- * there is a link back to the reference (or multiple).
- *
- * There is also optional support for inline footnotes, use {@link #builder()} and then set {@link Builder#inlineFootnotes}.
*
- * @see GitHub docs for footnotes
+ *
The line with [^1]: ... is a {@link FootnoteDefinition}, with the contents as
+ * child nodes (can be a paragraph like in the example, or other blocks like lists).
+ *
+ *
All the footnotes (definitions) will be rendered in a list at the end of a document, no matter
+ * where they appear in the source. The footnotes will be numbered starting from 1, then 2, etc,
+ * depending on the order in which they appear in the text (and not dependent on the label). The
+ * footnote reference is a link to the footnote, and from the footnote there is a link back to the
+ * reference (or multiple).
+ *
+ *
There is also optional support for inline footnotes, use {@link #builder()} and then set
+ * {@link Builder#inlineFootnotes}.
+ *
+ * @see GitHub
+ * docs for footnotes
*/
-public class FootnotesExtension implements Parser.ParserExtension,
- HtmlRenderer.HtmlRendererExtension,
- MarkdownRenderer.MarkdownRendererExtension {
+public class FootnotesExtension
+ implements Parser.ParserExtension,
+ HtmlRenderer.HtmlRendererExtension,
+ MarkdownRenderer.MarkdownRendererExtension {
private final boolean inlineFootnotes;
@@ -42,9 +48,7 @@ private FootnotesExtension(boolean inlineFootnotes) {
this.inlineFootnotes = inlineFootnotes;
}
- /**
- * The extension with the default configuration (no support for inline footnotes).
- */
+ /** The extension with the default configuration (no support for inline footnotes). */
public static Extension create() {
return builder().build();
}
@@ -70,17 +74,18 @@ public void extend(HtmlRenderer.Builder rendererBuilder) {
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
- @Override
- public NodeRenderer create(MarkdownNodeRendererContext context) {
- return new FootnoteMarkdownNodeRenderer(context);
- }
+ rendererBuilder.nodeRendererFactory(
+ new MarkdownNodeRendererFactory() {
+ @Override
+ public NodeRenderer create(MarkdownNodeRendererContext context) {
+ return new FootnoteMarkdownNodeRenderer(context);
+ }
- @Override
- public Set getSpecialCharacters() {
- return Set.of();
- }
- });
+ @Override
+ public Set getSpecialCharacters() {
+ return Set.of();
+ }
+ });
}
public static class Builder {
@@ -89,6 +94,7 @@ public static class Builder {
/**
* Enable support for inline footnotes without definitions, e.g.:
+ *
*
* Some text^[this is an inline footnote]
*
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/InlineFootnote.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/InlineFootnote.java
index 665d01936..cb16c45f6 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/InlineFootnote.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/InlineFootnote.java
@@ -2,5 +2,4 @@
import org.commonmark.node.CustomNode;
-public class InlineFootnote extends CustomNode {
-}
+public class InlineFootnote extends CustomNode {}
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteBlockParser.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteBlockParser.java
index 110bdef20..db11b906a 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteBlockParser.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteBlockParser.java
@@ -1,16 +1,13 @@
package org.commonmark.ext.footnotes.internal;
+import java.util.List;
import org.commonmark.ext.footnotes.FootnoteDefinition;
import org.commonmark.node.Block;
import org.commonmark.node.DefinitionMap;
import org.commonmark.parser.block.*;
import org.commonmark.text.Characters;
-import java.util.List;
-
-/**
- * Parser for a single {@link FootnoteDefinition} block.
- */
+/** Parser for a single {@link FootnoteDefinition} block. */
public class FootnoteBlockParser extends AbstractBlockParser {
private final FootnoteDefinition block;
@@ -37,16 +34,18 @@ public boolean canContain(Block childBlock) {
@Override
public BlockContinue tryContinue(ParserState parserState) {
if (parserState.getIndent() >= 4) {
- // It looks like content needs to be indented by 4 so that it's part of a footnote (instead of starting a new block).
+ // It looks like content needs to be indented by 4 so that it's part of a footnote
+ // (instead of starting a new block).
return BlockContinue.atColumn(4);
} else if (parserState.isBlank()) {
- // A blank line doesn't finish a footnote yet. If there's another line with indent >= 4 after it,
- // that should result in another paragraph in this footnote definition.
+ // A blank line doesn't finish a footnote yet. If there's another line with indent >= 4
+ // after it, that should result in another paragraph in this footnote definition.
return BlockContinue.atIndex(parserState.getIndex());
} else {
- // We're not continuing to give other block parsers a chance to interrupt this definition.
- // But if no other block parser applied (including another FootnotesBlockParser), we will
- // accept the line via lazy continuation (same as a block quote).
+ // We're not continuing to give other block parsers a chance to interrupt this
+ // definition. But if no other block parser applied (including another
+ // FootnotesBlockParser), we will accept the line via lazy continuation (same as a block
+ // quote).
return BlockContinue.none();
}
}
@@ -82,11 +81,16 @@ public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockPar
var c = content.charAt(index);
switch (c) {
case ']':
- if (index > labelStart && index + 1 < content.length() && content.charAt(index + 1) == ':') {
+ if (index > labelStart
+ && index + 1 < content.length()
+ && content.charAt(index + 1) == ':') {
var label = content.subSequence(labelStart, index).toString();
- // After the colon, any number of spaces is skipped (not part of the content)
- var afterSpaces = Characters.skipSpaceTab(content, index + 2, content.length());
- return BlockStart.of(new FootnoteBlockParser(label)).atIndex(afterSpaces);
+ // After the colon, any number of spaces is skipped (not part of the
+ // content)
+ var afterSpaces =
+ Characters.skipSpaceTab(content, index + 2, content.length());
+ return BlockStart.of(new FootnoteBlockParser(label))
+ .atIndex(afterSpaces);
} else {
return BlockStart.none();
}
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteHtmlNodeRenderer.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteHtmlNodeRenderer.java
index 70eb048a3..db88a8269 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteHtmlNodeRenderer.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteHtmlNodeRenderer.java
@@ -1,5 +1,7 @@
package org.commonmark.ext.footnotes.internal;
+import java.util.*;
+import java.util.function.Consumer;
import org.commonmark.ext.footnotes.FootnoteDefinition;
import org.commonmark.ext.footnotes.FootnoteReference;
import org.commonmark.ext.footnotes.InlineFootnote;
@@ -8,64 +10,68 @@
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;
-import java.util.*;
-import java.util.function.Consumer;
-
/**
* HTML rendering for footnotes.
- *
- * Aims to match the rendering of cmark-gfm (which is slightly different from GitHub's when it comes to class
- * attributes, not sure why).
- *
- * Some notes on how rendering works:
+ *
+ *
Aims to match the rendering of cmark-gfm (which is slightly different from GitHub's when it
+ * comes to class attributes, not sure why).
+ *
+ *
Some notes on how rendering works:
+ *
*
- *
Footnotes are numbered according to the order of references, starting at 1
- *
Definitions are rendered at the end of the document, regardless of where the definition was in the source
- *
Definitions are ordered by number
- *
Definitions have links back to their references (one or more)
+ *
Footnotes are numbered according to the order of references, starting at 1
+ *
Definitions are rendered at the end of the document, regardless of where the definition was
+ * in the source
+ *
Definitions are ordered by number
+ *
Definitions have links back to their references (one or more)
*
*
*
Nested footnotes
- * Text in footnote definitions can reference other footnotes, even ones that aren't referenced in the main text.
- * This makes them tricky because it's not enough to just go through the main text for references.
- * And before we can render a definition, we need to know all references (because we add links back to references).
- *
- * In other words, footnotes form a directed graph. Footnotes can reference each other so cycles are possible too.
- *
- * One way to implement it, which is what cmark-gfm does, is to go through the whole document (including definitions)
- * and find all references in order. That guarantees that all definitions are found, but it has strange results for
- * ordering or when the reference is in an unreferenced definition, see tests. In graph terms, it renders all
- * definitions that have an incoming edge, no matter whether they are connected to the main text or not.
- *
- * The way we implement it:
+ *
+ * Text in footnote definitions can reference other footnotes, even ones that aren't referenced in
+ * the main text. This makes them tricky because it's not enough to just go through the main text
+ * for references. And before we can render a definition, we need to know all references (because we
+ * add links back to references).
+ *
+ *
In other words, footnotes form a directed graph. Footnotes can reference each other so cycles
+ * are possible too.
+ *
+ *
One way to implement it, which is what cmark-gfm does, is to go through the whole document
+ * (including definitions) and find all references in order. That guarantees that all definitions
+ * are found, but it has strange results for ordering or when the reference is in an unreferenced
+ * definition, see tests. In graph terms, it renders all definitions that have an incoming edge, no
+ * matter whether they are connected to the main text or not.
+ *
+ *
The way we implement it:
+ *
*
- *
Start with the references in the main text; we can render them as we go
- *
After the main text is rendered, we have the referenced definitions, but there might be more from definition text
- *
To find the remaining definitions, we visit the definitions from before to look at references
- *
Repeat (breadth-first search) until we've found all definitions (note that we can't render before that's done because of backrefs)
- *
Now render the definitions (and any references inside)
+ *
Start with the references in the main text; we can render them as we go
+ *
After the main text is rendered, we have the referenced definitions, but there might be
+ * more from definition text
+ *
To find the remaining definitions, we visit the definitions from before to look at
+ * references
+ *
Repeat (breadth-first search) until we've found all definitions (note that we can't render
+ * before that's done because of backrefs)
+ *
Now render the definitions (and any references inside)
*
- * This means we only render definitions whose references are actually rendered, and in a meaningful order (all main
- * text footnotes first, then any nested ones).
+ *
+ * This means we only render definitions whose references are actually rendered, and in a meaningful
+ * order (all main text footnotes first, then any nested ones).
*/
public class FootnoteHtmlNodeRenderer implements NodeRenderer {
private final HtmlWriter html;
private final HtmlNodeRendererContext context;
- /**
- * All definitions (even potentially unused ones), for looking up references
- */
+ /** All definitions (even potentially unused ones), for looking up references */
private DefinitionMap definitionMap;
- /**
- * Definitions that were referenced, in order in which they should be rendered.
- */
+ /** Definitions that were referenced, in order in which they should be rendered. */
private final Map referencedDefinitions = new LinkedHashMap<>();
/**
- * Information about references that should be rendered as footnotes. This doesn't contain all references, just the
- * ones from inside definitions.
+ * Information about references that should be rendered as footnotes. This doesn't contain all
+ * references, just the ones from inside definitions.
*/
private final Map references = new HashMap<>();
@@ -81,7 +87,8 @@ public Set> getNodeTypes() {
@Override
public void beforeRoot(Node rootNode) {
- // Collect all definitions first, so we can look them up when encountering a reference later.
+ // Collect all definitions first, so we can look them up when encountering a reference
+ // later.
var visitor = new DefinitionVisitor();
rootNode.accept(visitor);
definitionMap = visitor.definitions;
@@ -90,11 +97,12 @@ public void beforeRoot(Node rootNode) {
@Override
public void render(Node node) {
if (node instanceof FootnoteReference) {
- // This is called for all references, even ones inside definitions that we render at the end.
- // Inside definitions, we have registered the reference already.
+ // This is called for all references, even ones inside definitions that we render at the
+ // end. Inside definitions, we have registered the reference already.
var ref = (FootnoteReference) node;
// Use containsKey because if value is null, we don't need to try registering again.
- var info = references.containsKey(ref) ? references.get(ref) : tryRegisterReference(ref);
+ var info =
+ references.containsKey(ref) ? references.get(ref) : tryRegisterReference(ref);
if (info != null) {
renderReference(ref, info);
} else {
@@ -126,26 +134,30 @@ public void afterRoot(Node rootNode) {
html.tag("ol");
html.line();
- // Check whether there are any footnotes inside the definitions that we're about to render. For those, we might
- // need to render more definitions. So do a breadth-first search to find all relevant definitions.
+ // Check whether there are any footnotes inside the definitions that we're about to render.
+ // For those, we might need to render more definitions. So do a breadth-first search to find
+ // all relevant definitions.
var check = new LinkedList<>(referencedDefinitions.keySet());
while (!check.isEmpty()) {
var def = check.removeFirst();
- def.accept(new ShallowReferenceVisitor(def, node -> {
- if (node instanceof FootnoteReference) {
- var ref = (FootnoteReference) node;
- var d = definitionMap.get(ref.getLabel());
- if (d != null) {
- if (!referencedDefinitions.containsKey(d)) {
- check.addLast(d);
- }
- references.put(ref, registerReference(d, d.getLabel()));
- }
- } else if (node instanceof InlineFootnote) {
- check.addLast(node);
- references.put(node, registerReference(node, null));
- }
- }));
+ def.accept(
+ new ShallowReferenceVisitor(
+ def,
+ node -> {
+ if (node instanceof FootnoteReference) {
+ var ref = (FootnoteReference) node;
+ var d = definitionMap.get(ref.getLabel());
+ if (d != null) {
+ if (!referencedDefinitions.containsKey(d)) {
+ check.addLast(d);
+ }
+ references.put(ref, registerReference(d, d.getLabel()));
+ }
+ } else if (node instanceof InlineFootnote) {
+ check.addLast(node);
+ references.put(node, registerReference(node, null));
+ }
+ }));
}
for (var entry : referencedDefinitions.entrySet()) {
@@ -169,15 +181,19 @@ private ReferenceInfo tryRegisterReference(FootnoteReference ref) {
private ReferenceInfo registerReference(Node node, String label) {
// The first referenced definition gets number 1, second one 2, etc.
- var referencedDef = referencedDefinitions.computeIfAbsent(node, k -> {
- var num = referencedDefinitions.size() + 1;
- var key = definitionKey(label, num);
- return new ReferencedDefinition(num, key);
- });
+ var referencedDef =
+ referencedDefinitions.computeIfAbsent(
+ node,
+ k -> {
+ var num = referencedDefinitions.size() + 1;
+ var key = definitionKey(label, num);
+ return new ReferencedDefinition(num, key);
+ });
var definitionNumber = referencedDef.definitionNumber;
- // The reference number for that particular definition. E.g. if there's two references for the same definition,
- // the first one is 1, the second one 2, etc. This is needed to give each reference a unique ID so that each
- // reference can get its own backlink from the definition.
+ // The reference number for that particular definition. E.g. if there's two references for
+ // the same definition, the first one is 1, the second one 2, etc. This is needed to give
+ // each reference a unique ID so that each reference can get its own backlink from the
+ // definition.
var refNumber = referencedDef.references.size() + 1;
var definitionKey = referencedDef.definitionKey;
var id = referenceId(definitionKey, refNumber);
@@ -212,8 +228,9 @@ private void renderDefinition(Node def, ReferencedDefinition referencedDefinitio
var node = def.getFirstChild();
while (node != lastParagraph) {
if (node instanceof Paragraph) {
- // Because we're manually rendering the
for the last paragraph, do the same for all other
- // paragraphs for consistency (Paragraph rendering might be overwritten by a custom renderer).
+ // Because we're manually rendering the
for the last paragraph, do the same
+ // for all other paragraphs for consistency (Paragraph rendering might be
+ // overwritten by a custom renderer).
html.tag("p", context.extendAttributes(node, "p", Map.of()));
renderChildren(node);
html.tag("/p");
@@ -252,7 +269,9 @@ private void renderBackrefs(Node def, ReferencedDefinition referencedDefinition)
for (int i = 0; i < refs.size(); i++) {
var ref = refs.get(i);
var refNumber = i + 1;
- var idx = referencedDefinition.definitionNumber + (refNumber > 1 ? ("-" + refNumber) : "");
+ var idx =
+ referencedDefinition.definitionNumber
+ + (refNumber > 1 ? ("-" + refNumber) : "");
var attrs = new LinkedHashMap();
attrs.put("href", "#" + ref);
@@ -262,7 +281,9 @@ private void renderBackrefs(Node def, ReferencedDefinition referencedDefinition)
attrs.put("aria-label", "Back to reference " + idx);
html.tag("a", context.extendAttributes(def, "a", attrs));
if (refNumber > 1) {
- html.tag("sup", context.extendAttributes(def, "sup", Map.of("class", "footnote-ref")));
+ html.tag(
+ "sup",
+ context.extendAttributes(def, "sup", Map.of("class", "footnote-ref")));
html.raw(String.valueOf(refNumber));
html.tag("/sup");
}
@@ -280,8 +301,9 @@ private String referenceId(String definitionKey, int number) {
}
private String definitionKey(String label, int number) {
- // Named definitions use the pattern "fn-{name}" and inline definitions use "fn{number}" so as not to conflict.
- // "fn{number}" is also what pandoc uses (for all types), starting with number 1.
+ // Named definitions use the pattern "fn-{name}" and inline definitions use "fn{number}" so
+ // as not to conflict. "fn{number}" is also what pandoc uses (for all types), starting with
+ // number 1.
if (label != null) {
return "-" + label;
} else {
@@ -304,7 +326,8 @@ private void renderChildren(Node parent) {
private static class DefinitionVisitor extends AbstractVisitor {
- private final DefinitionMap definitions = new DefinitionMap<>(FootnoteDefinition.class);
+ private final DefinitionMap definitions =
+ new DefinitionMap<>(FootnoteDefinition.class);
@Override
public void visit(CustomBlock customBlock) {
@@ -318,8 +341,8 @@ public void visit(CustomBlock customBlock) {
}
/**
- * Visit footnote references/inline footnotes inside the parent (but not the parent itself). We want a shallow visit
- * because the caller wants to control when to descend.
+ * Visit footnote references/inline footnotes inside the parent (but not the parent itself). We
+ * want a shallow visit because the caller wants to control when to descend.
*/
private static class ShallowReferenceVisitor extends AbstractVisitor {
private final Node parent;
@@ -349,17 +372,16 @@ public void visit(CustomNode customNode) {
}
private static class ReferencedDefinition {
- /**
- * The definition number, starting from 1, and in order in which they're referenced.
- */
+ /** The definition number, starting from 1, and in order in which they're referenced. */
final int definitionNumber;
+
/**
- * The unique key of the definition. Together with a static prefix it forms the ID used in the HTML.
+ * The unique key of the definition. Together with a static prefix it forms the ID used in
+ * the HTML.
*/
final String definitionKey;
- /**
- * The IDs of references for this definition, for backrefs.
- */
+
+ /** The IDs of references for this definition, for backrefs. */
final List references = new ArrayList<>();
ReferencedDefinition(int definitionNumber, String definitionKey) {
@@ -370,16 +392,15 @@ private static class ReferencedDefinition {
private static class ReferenceInfo {
/**
- * The ID of the reference; in the corresponding definition, a link back to this reference will be rendered.
+ * The ID of the reference; in the corresponding definition, a link back to this reference
+ * will be rendered.
*/
private final String id;
- /**
- * The ID of the definition, for linking to the definition.
- */
+
+ /** The ID of the definition, for linking to the definition. */
private final String definitionId;
- /**
- * The definition number, rendered in superscript.
- */
+
+ /** The definition number, rendered in superscript. */
private final int definitionNumber;
private ReferenceInfo(String id, String definitionId, int definitionNumber) {
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteLinkProcessor.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteLinkProcessor.java
index 07b008576..66a889855 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteLinkProcessor.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteLinkProcessor.java
@@ -11,17 +11,18 @@
import org.commonmark.parser.beta.Scanner;
/**
- * For turning e.g. [^foo] into a {@link FootnoteReference},
- * and ^[foo] into an {@link InlineFootnote}.
+ * For turning e.g. [^foo] into a {@link FootnoteReference}, and ^[foo]
+ * into an {@link InlineFootnote}.
*/
public class FootnoteLinkProcessor implements LinkProcessor {
@Override
public LinkResult process(LinkInfo linkInfo, Scanner scanner, InlineParserContext context) {
if (linkInfo.marker() != null && linkInfo.marker().getLiteral().equals("^")) {
- // An inline footnote like ^[footnote text]. Note that we only get the marker here if the option is enabled
- // on the extension.
- return LinkResult.wrapTextIn(new InlineFootnote(), linkInfo.afterTextBracket()).includeMarker();
+ // An inline footnote like ^[footnote text]. Note that we only get the marker here if
+ // the option is enabled on the extension.
+ return LinkResult.wrapTextIn(new InlineFootnote(), linkInfo.afterTextBracket())
+ .includeMarker();
}
if (linkInfo.destination() != null) {
@@ -35,21 +36,25 @@ public LinkResult process(LinkInfo linkInfo, Scanner scanner, InlineParserContex
return LinkResult.none();
}
- if (linkInfo.label() != null && context.getDefinition(LinkReferenceDefinition.class, linkInfo.label()) != null) {
- // If there's a label after the text and the label has a definition -> it's a link, and it should take
- // preference, e.g. in `[^foo][bar]` if `[bar]` has a definition, `[^foo]` won't be a footnote reference.
+ if (linkInfo.label() != null
+ && context.getDefinition(LinkReferenceDefinition.class, linkInfo.label()) != null) {
+ // If there's a label after the text and the label has a definition -> it's a link, and
+ // it should take preference, e.g. in `[^foo][bar]` if `[bar]` has a definition,
+ // `[^foo]` won't be a footnote reference.
return LinkResult.none();
}
var label = text.substring(1);
- // Check if we have a definition, otherwise ignore (same behavior as for link reference definitions).
- // Note that the definition parser already checked the syntax of the label, we don't need to check again.
+ // Check if we have a definition, otherwise ignore (same behavior as for link reference
+ // definitions). Note that the definition parser already checked the syntax of the label, we
+ // don't need to check again.
var def = context.getDefinition(FootnoteDefinition.class, label);
if (def == null) {
return LinkResult.none();
}
- // For footnotes, we only ever consume the text part of the link, not the label part (if any)
+ // For footnotes, we only ever consume the text part of the link, not the label part (if
+ // any)
var position = linkInfo.afterTextBracket();
// If the marker is `![`, we don't want to include the `!`, so start from bracket
return LinkResult.replaceWith(new FootnoteReference(label), position);
diff --git a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteMarkdownNodeRenderer.java b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteMarkdownNodeRenderer.java
index 3dcf4fc83..0e654cf5e 100644
--- a/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteMarkdownNodeRenderer.java
+++ b/commonmark-ext-footnotes/src/main/java/org/commonmark/ext/footnotes/internal/FootnoteMarkdownNodeRenderer.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.footnotes.internal;
+import java.util.Set;
import org.commonmark.ext.footnotes.FootnoteDefinition;
import org.commonmark.ext.footnotes.FootnoteReference;
import org.commonmark.ext.footnotes.InlineFootnote;
@@ -8,8 +9,6 @@
import org.commonmark.renderer.markdown.MarkdownNodeRendererContext;
import org.commonmark.renderer.markdown.MarkdownWriter;
-import java.util.Set;
-
public class FootnoteMarkdownNodeRenderer implements NodeRenderer {
private final MarkdownWriter writer;
diff --git a/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteHtmlRendererTest.java b/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteHtmlRendererTest.java
index bc7d4f74c..1a89693b4 100644
--- a/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteHtmlRendererTest.java
+++ b/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteHtmlRendererTest.java
@@ -1,5 +1,7 @@
package org.commonmark.ext.footnotes;
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.Document;
import org.commonmark.node.Paragraph;
@@ -10,40 +12,40 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Set;
-
public class FootnoteHtmlRendererTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(FootnotesExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void testOne() {
- assertRendering("Test [^foo]\n\n[^foo]: note\n",
- "
\n"
+ + "\n"
+ + "\n");
}
@Test
public void testLabelNormalization() {
- // Labels match via their normalized form. For the href and IDs to match, rendering needs to use the
- // label from the definition consistently.
- assertRendering("Test [^bar]\n\n[^BAR]: note\n",
- "
\n" +
- "\n" +
- "\n");
+ // Labels match via their normalized form. For the href and IDs to match, rendering needs to
+ // use the label from the definition consistently.
+ assertRendering(
+ "Test [^bar]\n\n[^BAR]: note\n",
+ "
\n"
+ + "\n"
+ + "\n");
}
@Test
@@ -52,254 +54,251 @@ public void testMultipleReferences() {
// - Numbering is based on the reference order, not the definition order
// - The same number is used when a definition is referenced multiple times
// - Multiple backrefs are rendered
- assertRendering("First [^foo]\n\nThen [^bar]\n\nThen [^foo] again\n\n[^bar]: b\n[^foo]: f\n",
- "
\n"
+ + "\n"
+ + "\n");
}
@Test
public void testNestedFootnotesOrder() {
// GitHub has a strange result here, the definitions are in order: 1. bar, 2. foo.
- // The reason is that the number is done based on all references in document order, including references in
- // definitions. So [^bar] from the first line is first.
- assertRendering("[^foo]: foo [^bar]\n" +
- "\n" +
- "[^foo]\n" +
- "\n" +
- "[^bar]: bar\n", "
\n" +
- "\n" +
- "\n");
+ // The reason is that the number is done based on all references in document order,
+ // including references in definitions. So [^bar] from the first line is first.
+ assertRendering(
+ "[^foo]: foo [^bar]\n" + "\n" + "[^foo]\n" + "\n" + "[^bar]: bar\n",
+ "
\n"
+ + "\n"
+ + "\n");
}
@Test
public void testNestedFootnotesUnreferenced() {
// This should not result in any footnotes, as baz itself isn't referenced.
// But GitHub renders bar only, with a broken backref, because bar is referenced from foo.
- assertRendering("[^foo]: foo[^bar]\n" +
- "[^bar]: bar\n", "");
+ assertRendering("[^foo]: foo[^bar]\n" + "[^bar]: bar\n", "");
// And here only 1 is rendered.
- assertRendering("[^1]\n" +
- "\n" +
- "[^1]: one\n" +
- "[^foo]: foo[^bar]\n" +
- "[^bar]: bar\n", "
\n"
+ + "\n"
+ + "\n");
}
@Test
public void testInlineFootnoteWithReference() {
// This is a bit tricky because the IDs need to be unique.
- assertRenderingInline("Test ^[inline [^1]]\n" +
- "\n" +
- "[^1]: normal",
- "
\n"
+ + "\n"
+ + "\n");
}
-
@Test
public void testRenderNodesDirectly() {
// Everything should work as expected when rendering from nodes directly (no parsing step).
@@ -314,14 +313,15 @@ public void testRenderNodesDirectly() {
doc.appendChild(p);
doc.appendChild(def);
- var expected = "
\n"
+ + "\n"
+ + "\n";
Asserts.assertRendering("", expected, RENDERER.render(doc));
}
diff --git a/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteMarkdownRendererTest.java b/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteMarkdownRendererTest.java
index 2f1125a02..3c6febe7b 100644
--- a/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteMarkdownRendererTest.java
+++ b/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnoteMarkdownRendererTest.java
@@ -1,19 +1,20 @@
package org.commonmark.ext.footnotes;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class FootnoteMarkdownRendererTest {
- private static final Set EXTENSIONS = Set.of(FootnotesExtension.builder().inlineFootnotes(true).build());
+ private static final Set EXTENSIONS =
+ Set.of(FootnotesExtension.builder().inlineFootnotes(true).build());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final MarkdownRenderer RENDERER = MarkdownRenderer.builder().extensions(EXTENSIONS).build();
+ private static final MarkdownRenderer RENDERER =
+ MarkdownRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void testSimple() {
@@ -22,7 +23,8 @@ public void testSimple() {
@Test
public void testUnreferenced() {
- // Whether a reference has a corresponding definition or vice versa shouldn't matter for Markdown rendering.
+ // Whether a reference has a corresponding definition or vice versa shouldn't matter for
+ // Markdown rendering.
assertRoundTrip("Test [^foo]\n\n[^foo]: one\n\n[^bar]: two\n");
}
@@ -43,8 +45,8 @@ public void testMultipleLines() {
@Test
public void testMultipleParagraphs() {
- // Note that the line between p1 and p2 could be blank too (instead of 4 spaces), but we currently don't
- // preserve that information.
+ // Note that the line between p1 and p2 could be blank too (instead of 4 spaces), but we
+ // currently don't preserve that information.
assertRoundTrip("Test [^1]\n\n[^1]: footnote p1\n \n footnote p2\n");
}
diff --git a/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnotesTest.java b/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnotesTest.java
index 7763cedb4..ca76e47cd 100644
--- a/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnotesTest.java
+++ b/commonmark-ext-footnotes/src/test/java/org/commonmark/ext/footnotes/FootnotesTest.java
@@ -1,17 +1,16 @@
package org.commonmark.ext.footnotes;
-import org.commonmark.Extension;
-import org.commonmark.node.*;
-import org.commonmark.parser.IncludeSourceSpans;
-import org.commonmark.parser.Parser;
-import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
+import org.commonmark.Extension;
+import org.commonmark.node.*;
+import org.commonmark.parser.IncludeSourceSpans;
+import org.commonmark.parser.Parser;
+import org.junit.jupiter.api.Test;
public class FootnotesTest {
@@ -35,7 +34,8 @@ public void testDefBlockStart() {
@Test
public void testDefBlockStartInterrupts() {
- // This is different from a link reference definition, which can only be at the start of paragraphs.
+ // This is different from a link reference definition, which can only be at the start of
+ // paragraphs.
var doc = PARSER.parse("test\n[^1]: footnote\n");
var paragraph = find(doc, Paragraph.class);
var def = find(doc, FootnoteDefinition.class);
@@ -172,7 +172,8 @@ public void testRefWithEmphasisInside() {
@Test
public void testRefWithEmphasisAround() {
- // Emphasis around footnote reference, the * inside needs to be removed from emphasis processing
+ // Emphasis around footnote reference, the * inside needs to be removed from emphasis
+ // processing
var doc = PARSER.parse("Test *abc [^foo*] def*\n\n[^foo*]: def\n");
var ref = find(doc, FootnoteReference.class);
assertThat(ref.getLabel()).isEqualTo("foo*");
@@ -193,8 +194,9 @@ public void testRefAfterBang() {
@Test
public void testRefAsLabelOnly() {
- // [^bar] is a footnote but [foo] is just text, because full reference links (text `foo`, label `^bar`) don't
- // resolve as footnotes. If `[foo][^bar]` fails to parse as a bracket, `[^bar]` by itself needs to be tried.
+ // [^bar] is a footnote but [foo] is just text, because full reference links (text `foo`,
+ // label `^bar`) don't resolve as footnotes. If `[foo][^bar]` fails to parse as a bracket,
+ // `[^bar]` by itself needs to be tried.
var doc = PARSER.parse("Test [foo][^bar]\n\n[^bar]: footnote\n");
var ref = find(doc, FootnoteReference.class);
assertThat(ref.getLabel()).isEqualTo("bar");
@@ -204,7 +206,8 @@ public void testRefAsLabelOnly() {
@Test
public void testRefWithEmptyLabel() {
- // [^bar] is a footnote but [] is just text, because collapsed reference links don't resolve as footnotes
+ // [^bar] is a footnote but [] is just text, because collapsed reference links don't resolve
+ // as footnotes
var doc = PARSER.parse("Test [^bar][]\n\n[^bar]: footnote\n");
var ref = find(doc, FootnoteReference.class);
assertThat(ref.getLabel()).isEqualTo("bar");
@@ -237,8 +240,8 @@ public void testPreferInlineLink() {
@Test
public void testPreferReferenceLink() {
- // This is tricky because `[^*foo*][foo]` is a valid link already. If `[foo]` was not defined, the first bracket
- // would be a footnote.
+ // This is tricky because `[^*foo*][foo]` is a valid link already. If `[foo]` was not
+ // defined, the first bracket would be a footnote.
var doc = PARSER.parse("Test [^*foo*][foo]\n\n[^*foo*]: /url\n\n[foo]: /url");
assertNone(doc, FootnoteReference.class);
}
@@ -256,10 +259,13 @@ public void testReferenceLinkWithoutDefinition() {
@Test
public void testFootnoteInLink() {
- // Expected to behave the same way as a link within a link, see https://spec.commonmark.org/0.31.2/#example-518
- // i.e. the first (inner) link is parsed, which means the outer one becomes plain text, as nesting links is not
- // allowed.
- var doc = PARSER.parse("[link with footnote ref [^1]](https://example.com)\n\n[^1]: footnote\n");
+ // Expected to behave the same way as a link within a link, see
+ // https://spec.commonmark.org/0.31.2/#example-518
+ // i.e. the first (inner) link is parsed, which means the outer one becomes plain text, as
+ // nesting links is not allowed.
+ var doc =
+ PARSER.parse(
+ "[link with footnote ref [^1]](https://example.com)\n\n[^1]: footnote\n");
var ref = find(doc, FootnoteReference.class);
assertThat(ref.getLabel()).isEqualTo("1");
var paragraph = doc.getFirstChild();
@@ -269,7 +275,9 @@ public void testFootnoteInLink() {
@Test
public void testFootnoteWithMarkerInLink() {
- var doc = PARSER.parse("[link with footnote ref ![^1]](https://example.com)\n\n[^1]: footnote\n");
+ var doc =
+ PARSER.parse(
+ "[link with footnote ref ![^1]](https://example.com)\n\n[^1]: footnote\n");
var ref = find(doc, FootnoteReference.class);
assertThat(ref.getLabel()).isEqualTo("1");
var paragraph = doc.getFirstChild();
@@ -325,7 +333,11 @@ public void testInlineFootnote() {
@Test
public void testSourcePositions() {
- var parser = Parser.builder().extensions(EXTENSIONS).includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES).build();
+ var parser =
+ Parser.builder()
+ .extensions(EXTENSIONS)
+ .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
+ .build();
var doc = parser.parse("Test [^foo]\n\n[^foo]: /url\n");
var ref = find(doc, FootnoteReference.class);
@@ -336,11 +348,15 @@ public void testSourcePositions() {
}
private static void assertNone(Node parent, Class> nodeClass) {
- assertThat(tryFind(parent, nodeClass)).as(() -> "Node " + parent + " containing " + nodeClass).isNull();
+ assertThat(tryFind(parent, nodeClass))
+ .as(() -> "Node " + parent + " containing " + nodeClass)
+ .isNull();
}
private static T find(Node parent, Class nodeClass) {
- return Objects.requireNonNull(tryFind(parent, nodeClass), "Could not find a " + nodeClass.getSimpleName() + " node in " + parent);
+ return Objects.requireNonNull(
+ tryFind(parent, nodeClass),
+ "Could not find a " + nodeClass.getSimpleName() + " node in " + parent);
}
private static T tryFind(Node parent, Class nodeClass) {
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/Alert.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/Alert.java
index 71c35d24d..5725d53cd 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/Alert.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/Alert.java
@@ -21,31 +21,32 @@ public String getType() {
/**
* @return Whether this alert has any body content (not including the title).
- *
+ *
- Examples where this would be {@code true}:
+ *
{@code
+ * > [!NOTE]
+ * > Body text
*
- * - Examples where this would be {@code true}:
- *
{@code
- * > [!NOTE]
- * > Body text
- * }
- *
{@code
- * > [!NOTE] Custom title
- * > Body text
- * }
+ * }
+ *
{@code
+ * > [!NOTE] Custom title
+ * > Body text
*
- * - Examples where this would be {@code false}:
+ * }
+ * - Examples where this would be {@code false}:
+ *
{@code
+ * > [!NOTE]
*
- *
{@code
- * > [!NOTE]
- * }
- *
{@code
- * > [!NOTE]
- * >
- * >
- * }
- *
{@code
- * > [!NOTE] Custom title
- * }
+ * }
+ *
{@code
+ * > [!NOTE]
+ * >
+ * >
+ *
+ * }
+ *
{@code
+ * > [!NOTE] Custom title
+ *
+ * }
*/
public boolean hasBody() {
var first = this.getFirstChild();
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertTitle.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertTitle.java
index c085af746..fc537759c 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertTitle.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertTitle.java
@@ -5,20 +5,18 @@
/**
* Inline content container for the optional custom title of an {@link Alert}.
*
- *
- * When present, an {@code AlertTitle} is always the first child of an {@link Alert}.
- * Its own children are the parsed inline nodes of the title (i.e., the text after
- * the {@code [!TYPE]} marker on the same line). For example, in
+ *
When present, an {@code AlertTitle} is always the first child of an {@link Alert}. Its own
+ * children are the parsed inline nodes of the title (i.e., the text after the {@code [!TYPE]}
+ * marker on the same line). For example, in
*
*
{@code
* > [!NOTE] Custom _title_
* > Body text
* }
*
- * the {@code AlertTitle} contains a {@code Text} node ({@code "Custom "}) followed
- * by an {@code Emphasis} node wrapping {@code "title"}.
+ * the {@code AlertTitle} contains a {@code Text} node ({@code "Custom "}) followed by an {@code
+ * Emphasis} node wrapping {@code "title"}.
*
* @see AlertsExtension.Builder#allowCustomTitles(boolean)
*/
-public class AlertTitle extends CustomNode {
-}
+public class AlertTitle extends CustomNode {}
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertsExtension.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertsExtension.java
index ed81a2c3f..3035c9952 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertsExtension.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/AlertsExtension.java
@@ -1,5 +1,11 @@
package org.commonmark.ext.gfm.alerts;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.alerts.internal.AlertBlockParser;
import org.commonmark.ext.gfm.alerts.internal.AlertHtmlNodeRenderer;
@@ -13,61 +19,60 @@
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.commonmark.renderer.text.TextContentRenderer;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-
/**
* Extension for GFM alerts using {@code [!TYPE]} syntax (GitHub Flavored Markdown).
- *
- * Create with {@link #create()} or {@link #builder()} and configure on builders
- * ({@link Parser.Builder#extensions(Iterable)}, {@link HtmlRenderer.Builder#extensions(Iterable)}).
- * Parsed alerts become {@link Alert} blocks. If custom alert titles are allowed
- * via {@link Builder#allowCustomTitles(boolean)}, the inline formatting of those
- * titles will be parsed into {@link AlertTitle} nodes.
*
- * The {@link #create() default configuration} of this extension will match GFM
- * exactly, with the following exceptions:
+ *
Create with {@link #create()} or {@link #builder()} and configure on builders ({@link
+ * Parser.Builder#extensions(Iterable)}, {@link HtmlRenderer.Builder#extensions(Iterable)}). Parsed
+ * alerts become {@link Alert} blocks. If custom alert titles are allowed via {@link
+ * Builder#allowCustomTitles(boolean)}, the inline formatting of those titles will be parsed into
+ * {@link AlertTitle} nodes.
+ *
+ *
The {@link #create() default configuration} of this extension will match GFM exactly, with the
+ * following exceptions:
*
- * - Alert markers take precedence over shortcut reference links.
+ *
- Alert markers take precedence over shortcut reference links.
* - Alerts with no content are allowed. Example:
*
- *
* - Lazy continuation is not allowed between the marker and the body text. Example:
*
- *
{@code
- * > [!NOTE]
- * Lazy body text will be parsed as a new paragraph
- * }
+ *
{@code
+ * > [!NOTE]
+ * Lazy body text will be parsed as a new paragraph
+ *
+ * }
*/
-public class AlertsExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension,
- TextContentRenderer.TextContentRendererExtension, MarkdownRenderer.MarkdownRendererExtension {
-
- /**
- * The standard GitHub Flavored Markdown (GFM) types that the extension
- * enables by default. These can be overwritten with {@link Builder#setAllowedTypes(Map)}.
- */
- public static final Map STANDARD_TYPES = Map.ofEntries(
- Map.entry("NOTE", "Note"),
- Map.entry("TIP", "Tip"),
- Map.entry("IMPORTANT", "Important"),
- Map.entry("WARNING", "Warning"),
- Map.entry("CAUTION", "Caution")
- );
+public class AlertsExtension
+ implements Parser.ParserExtension,
+ HtmlRenderer.HtmlRendererExtension,
+ TextContentRenderer.TextContentRendererExtension,
+ MarkdownRenderer.MarkdownRendererExtension {
/**
- * A map of alert marker ({@code [!TYPE]}) to the default title for that marker.
+ * The standard GitHub Flavored Markdown (GFM) types that the extension enables by default.
+ * These can be overwritten with {@link Builder#setAllowedTypes(Map)}.
*/
+ public static final Map STANDARD_TYPES =
+ Map.ofEntries(
+ Map.entry("NOTE", "Note"),
+ Map.entry("TIP", "Tip"),
+ Map.entry("IMPORTANT", "Important"),
+ Map.entry("WARNING", "Warning"),
+ Map.entry("CAUTION", "Caution"));
+
+ /** A map of alert marker ({@code [!TYPE]}) to the default title for that marker. */
private final Map allowedTypes;
+
private final boolean customTitlesAllowed;
private final boolean nestedAlertsAllowed;
@@ -89,37 +94,39 @@ public static Builder builder() {
public void extend(Parser.Builder parserBuilder) {
var allowedTypesSet = new HashSet<>(allowedTypes.keySet());
parserBuilder.customBlockParserFactory(
- new AlertBlockParser.Factory(allowedTypesSet, customTitlesAllowed, nestedAlertsAllowed));
+ new AlertBlockParser.Factory(
+ allowedTypesSet, customTitlesAllowed, nestedAlertsAllowed));
}
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(context -> new AlertHtmlNodeRenderer(context, allowedTypes));
+ rendererBuilder.nodeRendererFactory(
+ context -> new AlertHtmlNodeRenderer(context, allowedTypes));
}
@Override
public void extend(TextContentRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(context -> new AlertTextContentNodeRenderer(context, allowedTypes));
+ rendererBuilder.nodeRendererFactory(
+ context -> new AlertTextContentNodeRenderer(context, allowedTypes));
}
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
- @Override
- public NodeRenderer create(MarkdownNodeRendererContext context) {
- return new AlertMarkdownNodeRenderer(context);
- }
-
- @Override
- public Set getSpecialCharacters() {
- return Set.of();
- }
- });
+ rendererBuilder.nodeRendererFactory(
+ new MarkdownNodeRendererFactory() {
+ @Override
+ public NodeRenderer create(MarkdownNodeRendererContext context) {
+ return new AlertMarkdownNodeRenderer(context);
+ }
+
+ @Override
+ public Set getSpecialCharacters() {
+ return Set.of();
+ }
+ });
}
- /**
- * Builder for configuring the alerts extension.
- */
+ /** Builder for configuring the alerts extension. */
public static class Builder {
private Map allowedTypes = new HashMap<>(STANDARD_TYPES);
private boolean customTitlesAllowed = false;
@@ -128,12 +135,12 @@ public static class Builder {
/**
* Sets which alert types will be recognized and parsed into {@link Alert} blocks,
* completely overwriting any previous configuration.
- *
- * By default, {@link AlertsExtension#STANDARD_TYPES} are used.
*
- * @param allowedTypes A map of alert type to the default title for that type.
- * Must not be null/empty or contain any null/empty keys or
- * values. Additionally, all alert types must be uppercase.
+ *
By default, {@link AlertsExtension#STANDARD_TYPES} are used.
+ *
+ * @param allowedTypes A map of alert type to the default title for that type. Must not be
+ * null/empty or contain any null/empty keys or values. Additionally, all alert types
+ * must be uppercase.
* @return {@code this}
* @see Builder#addCustomType(String, String)
*/
@@ -153,9 +160,9 @@ public Builder setAllowedTypes(Map allowedTypes) {
/**
* Adds a custom alert type with a default title.
- *
- * This can also be used to override the default title of standard GFM types
- * (e.g., for localization).
+ *
+ *
This can also be used to override the default title of standard GFM types (e.g., for
+ * localization).
*
* @param type the alert type (must be uppercase)
* @param title the default title for this alert type
@@ -169,8 +176,8 @@ public Builder addCustomType(String type, String title) {
}
/**
- * Allows or disallows custom titles on alerts. Inline formatting is supported
- * within these titles.
+ * Allows or disallows custom titles on alerts. Inline formatting is supported within these
+ * titles.
*
* @param allow Whether to allow or disallow custom titles on alerts.
* @return {@code this}
@@ -183,11 +190,11 @@ public Builder allowCustomTitles(boolean allow) {
/**
* Allows or disallows parsing alerts within non-root blocks ({@code Document}).
- *
- * When disallowed, if an alert appears within another block, it will be parsed as
- * a regular {@code BlockQuote}.
- *
- * Note that even when this is allowed, {@link Parser.Builder#maxOpenBlockParsers(int)}
+ *
+ *
When disallowed, if an alert appears within another block, it will be parsed as a
+ * regular {@code BlockQuote}.
+ *
+ *
Note that even when this is allowed, {@link Parser.Builder#maxOpenBlockParsers(int)}
* will be respected.
*
* @param allow Whether to allow or disallow parsing alerts within non-root blocks.
@@ -208,10 +215,7 @@ public Extension build() {
/**
* Checks whether an alert type and default title are valid.
*
- * @param type The type to validate:
- *
- * - Must not be null or empty
- * - Must be uppercase
+ * @param type The type to validate. Must be uppercase.
* @param title The default title to validate. Must not be null or empty.
*/
private void validateTypeAndTitle(String type, String title) {
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertBlockParser.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertBlockParser.java
index e7a9f402e..67acbe475 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertBlockParser.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertBlockParser.java
@@ -4,7 +4,6 @@
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
-
import org.commonmark.ext.gfm.alerts.Alert;
import org.commonmark.ext.gfm.alerts.AlertTitle;
import org.commonmark.node.Block;
@@ -23,8 +22,10 @@
public class AlertBlockParser extends AbstractBlockParser {
- private static final Pattern ALERT_PATTERN_NO_CUSTOM_TITLE = Pattern.compile("^\\[!([a-zA-Z]+)]\\s*$");
- private static final Pattern ALERT_PATTERN_CUSTOM_TITLE = Pattern.compile("^\\[!([a-zA-Z]+)](.*)$");
+ private static final Pattern ALERT_PATTERN_NO_CUSTOM_TITLE =
+ Pattern.compile("^\\[!([a-zA-Z]+)]\\s*$");
+ private static final Pattern ALERT_PATTERN_CUSTOM_TITLE =
+ Pattern.compile("^\\[!([a-zA-Z]+)](.*)$");
private final Alert block;
private final SourceLine titleLine;
@@ -103,7 +104,10 @@ public static class Factory extends AbstractBlockParserFactory {
private final boolean customTitlesAllowed;
private final boolean nestedAlertsAllowed;
- public Factory(Set allowedTypes, boolean customTitlesAllowed, boolean nestedAlertsAllowed) {
+ public Factory(
+ Set allowedTypes,
+ boolean customTitlesAllowed,
+ boolean nestedAlertsAllowed) {
this.allowedTypes = allowedTypes;
this.customTitlesAllowed = customTitlesAllowed;
this.nestedAlertsAllowed = nestedAlertsAllowed;
@@ -116,7 +120,8 @@ public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockPar
return BlockStart.none();
}
- if (!nestedAlertsAllowed && !isAtRoot(matchedBlockParser.getMatchedBlockParser().getBlock())) {
+ if (!nestedAlertsAllowed
+ && !isAtRoot(matchedBlockParser.getMatchedBlockParser().getBlock())) {
return BlockStart.none();
}
@@ -176,7 +181,10 @@ private BlockStart tryStartFresh(CharSequence line, int nextNonSpace, ParserStat
afterGt = state.getIndex();
}
- var pattern = customTitlesAllowed ? ALERT_PATTERN_CUSTOM_TITLE : ALERT_PATTERN_NO_CUSTOM_TITLE;
+ var pattern =
+ customTitlesAllowed
+ ? ALERT_PATTERN_CUSTOM_TITLE
+ : ALERT_PATTERN_NO_CUSTOM_TITLE;
var matcher = pattern.matcher(line.subSequence(afterGt, line.length()));
if (!matcher.matches()) {
@@ -215,7 +223,8 @@ private BlockStart tryStartFresh(CharSequence line, int nextNonSpace, ParserStat
// If we got here via the promotion path, replace the empty BlockQuote.
var matched = state.getActiveBlockParser().getBlock();
- if (matched instanceof BlockQuote && matched.getFirstChild() == null
+ if (matched instanceof BlockQuote
+ && matched.getFirstChild() == null
&& (nextNonSpace >= line.length() || line.charAt(nextNonSpace) != '>')) {
start = start.replaceActiveBlockParser();
}
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertHtmlNodeRenderer.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertHtmlNodeRenderer.java
index 6b9ba6da9..30aea6f04 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertHtmlNodeRenderer.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertHtmlNodeRenderer.java
@@ -1,21 +1,21 @@
package org.commonmark.ext.gfm.alerts.internal;
+import java.util.LinkedHashMap;
+import java.util.Map;
import org.commonmark.ext.gfm.alerts.Alert;
import org.commonmark.ext.gfm.alerts.AlertTitle;
import org.commonmark.node.Node;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
public class AlertHtmlNodeRenderer extends AlertNodeRenderer {
private final HtmlWriter htmlWriter;
private final HtmlNodeRendererContext context;
private final Map allowedTypes;
- public AlertHtmlNodeRenderer(HtmlNodeRendererContext context, Map allowedTypes) {
+ public AlertHtmlNodeRenderer(
+ HtmlNodeRendererContext context, Map allowedTypes) {
this.htmlWriter = context.getWriter();
this.context = context;
this.allowedTypes = allowedTypes;
@@ -39,7 +39,8 @@ protected void renderAlert(Alert alert) {
htmlWriter.line();
// Render alert title
- htmlWriter.tag("p", context.extendAttributes(alert, "p", Map.of("class", "markdown-alert-title")));
+ htmlWriter.tag(
+ "p", context.extendAttributes(alert, "p", Map.of("class", "markdown-alert-title")));
var first = alert.getFirstChild();
if (first instanceof AlertTitle) {
renderChildren(first);
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertNodeRenderer.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertNodeRenderer.java
index 42e505cb7..ff4bdf6ad 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertNodeRenderer.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertNodeRenderer.java
@@ -1,12 +1,11 @@
package org.commonmark.ext.gfm.alerts.internal;
+import java.util.Set;
import org.commonmark.ext.gfm.alerts.Alert;
import org.commonmark.ext.gfm.alerts.AlertTitle;
import org.commonmark.node.Node;
import org.commonmark.renderer.NodeRenderer;
-import java.util.Set;
-
public abstract class AlertNodeRenderer implements NodeRenderer {
@Override
@@ -23,8 +22,8 @@ public void render(Node node) {
protected abstract void renderAlert(Alert alert);
/**
- * Renders the children of a parent node, excluding {@link AlertTitle} nodes.
- * {@link AlertTitle} is rendered separately from other content.
+ * Renders the children of a parent node, excluding {@link AlertTitle} nodes. {@link AlertTitle}
+ * is rendered separately from other content.
*
* @param parent the parent node whose children should be rendered
*/
@@ -42,8 +41,8 @@ protected final void renderChildren(Node parent) {
}
/**
- * Renders a single node. Subclasses must implement this to delegate
- * to their context's render method.
+ * Renders a single node. Subclasses must implement this to delegate to their context's render
+ * method.
*
* @param node the node to render
*/
diff --git a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertTextContentNodeRenderer.java b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertTextContentNodeRenderer.java
index c14ea36a4..f494f5812 100644
--- a/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertTextContentNodeRenderer.java
+++ b/commonmark-ext-gfm-alerts/src/main/java/org/commonmark/ext/gfm/alerts/internal/AlertTextContentNodeRenderer.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.gfm.alerts.internal;
+import java.util.Map;
import org.commonmark.ext.gfm.alerts.Alert;
import org.commonmark.ext.gfm.alerts.AlertTitle;
import org.commonmark.node.Node;
@@ -7,15 +8,14 @@
import org.commonmark.renderer.text.TextContentNodeRendererContext;
import org.commonmark.renderer.text.TextContentWriter;
-import java.util.Map;
-
public class AlertTextContentNodeRenderer extends AlertNodeRenderer {
private final TextContentNodeRendererContext context;
private final TextContentWriter textContent;
private final Map allowedTypes;
- public AlertTextContentNodeRenderer(TextContentNodeRendererContext context, Map allowedTypes) {
+ public AlertTextContentNodeRenderer(
+ TextContentNodeRendererContext context, Map allowedTypes) {
this.context = context;
this.textContent = context.getWriter();
this.allowedTypes = allowedTypes;
diff --git a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsMarkdownRendererTest.java b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsMarkdownRendererTest.java
index e31059ed2..f8e73cc06 100644
--- a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsMarkdownRendererTest.java
+++ b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsMarkdownRendererTest.java
@@ -1,27 +1,26 @@
package org.commonmark.ext.gfm.alerts;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class AlertsMarkdownRendererTest {
private static final Set EXTENSIONS = Set.of(AlertsExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final MarkdownRenderer RENDERER = MarkdownRenderer.builder().extensions(EXTENSIONS).build();
+ private static final MarkdownRenderer RENDERER =
+ MarkdownRenderer.builder().extensions(EXTENSIONS).build();
- private static final Set EXTENSIONS_CUSTOM_TITLES = Set.of(AlertsExtension.builder().allowCustomTitles(true).build());
- private static final Parser PARSER_CUSTOM_TITLES = Parser.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES)
- .build();
- private static final MarkdownRenderer RENDERER_CUSTOM_TITLES = MarkdownRenderer.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES)
- .build();
+ private static final Set EXTENSIONS_CUSTOM_TITLES =
+ Set.of(AlertsExtension.builder().allowCustomTitles(true).build());
+ private static final Parser PARSER_CUSTOM_TITLES =
+ Parser.builder().extensions(EXTENSIONS_CUSTOM_TITLES).build();
+ private static final MarkdownRenderer RENDERER_CUSTOM_TITLES =
+ MarkdownRenderer.builder().extensions(EXTENSIONS_CUSTOM_TITLES).build();
@Test
public void alertRoundTrip() {
@@ -61,9 +60,7 @@ public void alertWithMultipleParagraphs() {
@Test
public void customTypeRoundTrip() {
- var extension = AlertsExtension.builder()
- .addCustomType("INFO", "Information")
- .build();
+ var extension = AlertsExtension.builder().addCustomType("INFO", "Information").build();
var parser = Parser.builder().extensions(Set.of(extension)).build();
var renderer = MarkdownRenderer.builder().extensions(Set.of(extension)).build();
@@ -99,14 +96,17 @@ public void customTitleRoundTrip() {
@Test
public void customTitleWithFormattingRoundTrip() {
- assertRoundTripCustomTitles("> [!WARNING] Custom _title **with `formatting`**_\n> Be careful\n");
+ assertRoundTripCustomTitles(
+ "> [!WARNING] Custom _title **with `formatting`**_\n> Be careful\n");
}
@Test
public void customTitleWithMultipleBlocks() {
- var input = "> [!NOTE]Title\n> First paragraph\n>\n> Second paragraph\n>\n> - > Nested blocks\n";
+ var input =
+ "> [!NOTE]Title\n> First paragraph\n>\n> Second paragraph\n>\n> - > Nested blocks\n";
// MarkdownWriter always writes the prefix including trailing space
- var expected = "> [!NOTE] Title\n> First paragraph\n> \n> Second paragraph\n> \n> - > Nested blocks\n";
+ var expected =
+ "> [!NOTE] Title\n> First paragraph\n> \n> Second paragraph\n> \n> - > Nested blocks\n";
var rendered = RENDERER_CUSTOM_TITLES.render(PARSER_CUSTOM_TITLES.parse(input));
assertThat(rendered).isEqualTo(expected);
}
diff --git a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsSpecTest.java b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsSpecTest.java
index d85aa1d2a..2836db3ac 100644
--- a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsSpecTest.java
+++ b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsSpecTest.java
@@ -1,5 +1,8 @@
package org.commonmark.ext.gfm.alerts;
+import java.net.URL;
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
@@ -11,16 +14,12 @@
import org.junit.jupiter.params.ParameterizedClass;
import org.junit.jupiter.params.provider.MethodSource;
-import java.net.URL;
-import java.util.List;
-import java.util.Set;
-
/**
- * Tests the default configuration of {@link AlertsExtension} against how
- * GitHub Flavored Markdown (GFM) parses and renders {@link Alert}s.
- *
- * This test should only be used for the default configuration of
- * {@link AlertsExtension}. Other configurations cause deviation from GFM.
+ * Tests the default configuration of {@link AlertsExtension} against how GitHub Flavored Markdown
+ * (GFM) parses and renders {@link Alert}s.
+ *
+ *
This test should only be used for the default configuration of {@link AlertsExtension}. Other
+ * configurations cause deviation from GFM.
*/
@ParameterizedClass
@MethodSource("data")
@@ -28,11 +27,12 @@ public class AlertsSpecTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(AlertsExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- // Use softbreak(" ") to match GitHub's rendering for easier comparison with GitHub API output.
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).softbreak(" \n").build();
+ // Use softbreak(" ") to match GitHub's rendering for easier comparison with GitHub API
+ // output.
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).softbreak(" \n").build();
- @Parameter
- Example example;
+ @Parameter Example example;
static List data() {
URL spec = AlertsSpecTest.class.getResource("/alerts-spec.txt");
diff --git a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTest.java b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTest.java
index d98e0e2cf..99c0e8d7a 100644
--- a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTest.java
+++ b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTest.java
@@ -1,5 +1,11 @@
package org.commonmark.ext.gfm.alerts;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.Emphasis;
import org.commonmark.node.SourceSpan;
@@ -11,27 +17,26 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
public class AlertsTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(AlertsExtension.create());
- private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES).build();
- private static final HtmlRenderer HTML_RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
-
- private static final Set EXTENSIONS_CUSTOM_TITLES = Set.of(AlertsExtension.builder().allowCustomTitles(true).build());
- private static final Parser PARSER_CUSTOM_TITLES = Parser.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES)
- .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
- .build();
- private static final HtmlRenderer HTML_RENDERER_CUSTOM_TITLES = HtmlRenderer.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES)
- .build();
+ private static final Parser PARSER =
+ Parser.builder()
+ .extensions(EXTENSIONS)
+ .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
+ .build();
+ private static final HtmlRenderer HTML_RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
+
+ private static final Set EXTENSIONS_CUSTOM_TITLES =
+ Set.of(AlertsExtension.builder().allowCustomTitles(true).build());
+ private static final Parser PARSER_CUSTOM_TITLES =
+ Parser.builder()
+ .extensions(EXTENSIONS_CUSTOM_TITLES)
+ .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
+ .build();
+ private static final HtmlRenderer HTML_RENDERER_CUSTOM_TITLES =
+ HtmlRenderer.builder().extensions(EXTENSIONS_CUSTOM_TITLES).build();
@Override
protected String render(String source) {
@@ -39,103 +44,109 @@ protected String render(String source) {
}
private void assertRenderingCustomTitles(String source, String expectedResult) {
- assertThat(HTML_RENDERER_CUSTOM_TITLES.render(PARSER_CUSTOM_TITLES.parse(source))).isEqualTo(expectedResult);
+ assertThat(HTML_RENDERER_CUSTOM_TITLES.render(PARSER_CUSTOM_TITLES.parse(source)))
+ .isEqualTo(expectedResult);
}
// Custom types
@Test
public void customType() {
- var extension = AlertsExtension.builder()
- .addCustomType("INFO", "Information")
- .build();
+ var extension = AlertsExtension.builder().addCustomType("INFO", "Information").build();
var parser = Parser.builder().extensions(Set.of(extension)).build();
var renderer = HtmlRenderer.builder().extensions(Set.of(extension)).build();
- assertThat(renderer.render(parser.parse("> [!INFO]\n> Custom alert"))).isEqualTo(
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE] Custom title\n> Note with a custom title",
+ "
\n"
+ + "
Custom title
\n"
+ + "
Note with a custom title
\n"
+ + "
\n");
}
@Test
public void customTitleNoSpace() {
- assertRenderingCustomTitles("> [!NOTE]Custom title\n> Note with a custom title",
- "
\n" +
- "
Custom title
\n" +
- "
Note with a custom title
\n" +
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE]Custom title\n> Note with a custom title",
+ "
\n"
+ + "
Custom title
\n"
+ + "
Note with a custom title
\n"
+ + "
\n");
}
@Test
public void customTitleExtraSpace() {
- assertRenderingCustomTitles("> [!NOTE] Custom title \n> Note with a custom title",
- "
\n" +
- "
Custom title
\n" +
- "
Note with a custom title
\n" +
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE] Custom title \n> Note with a custom title",
+ "
\n"
+ + "
Custom title
\n"
+ + "
Note with a custom title
\n"
+ + "
\n");
}
@Test
public void customTitleNoHardLineBreak() {
- assertRenderingCustomTitles("> [!NOTE] Custom title\\\n> Note with a custom title",
- "
\n" +
- "
Custom title\\
\n" +
- "
Note with a custom title
\n" +
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE] Custom title\\\n> Note with a custom title",
+ "
\n"
+ + "
Custom title\\
\n"
+ + "
Note with a custom title
\n"
+ + "
\n");
}
@Test
public void customTitleWithComment() {
- assertRenderingCustomTitles("> [!NOTE] Custom title \n> Note with a custom title",
- "
\n" +
- "
Custom title
\n" +
- "
Note with a custom title
\n" +
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE] Custom title \n> Note with a custom title",
+ "
\n"
+ + "
Custom title
\n"
+ + "
Note with a custom title
\n"
+ + "
\n");
}
@Test
public void customTitleWithInlineFormatting() {
- assertRenderingCustomTitles("> [!NOTE] Custom _title with **formatting**_\n> Note with a custom title",
- "
\n" +
- "
Custom title with formatting
\n" +
- "
Note with a custom title
\n" +
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE] Custom _title with **formatting**_\n> Note with a custom title",
+ "
\n"
+ + "
Custom title with formatting
\n"
+ + "
Note with a custom title
\n"
+ + "
\n");
}
@Test
public void customTitleWithLinkAndCode() {
- assertRenderingCustomTitles("> [!IMPORTANT] See [docs](https://example.com) or `run()`\n> Note with a custom title",
- "
\n");
}
@Test
public void customTitleIgnoresBlockContent() {
- assertRenderingCustomTitles("> [!NOTE] ## Custom title looks like an ATX heading\n>But it's not",
- "
\n" +
- "
## Custom title looks like an ATX heading
\n" +
- "
But it's not
\n" +
- "
\n");
+ assertRenderingCustomTitles(
+ "> [!NOTE] ## Custom title looks like an ATX heading\n>But it's not",
+ "
\n"
+ + "
## Custom title looks like an ATX heading
\n"
+ + "
But it's not
\n"
+ + "
\n");
}
@Test
public void customTitleNoBody() {
// Alerts with no body are allowed.
- assertRenderingCustomTitles("> [!NOTE] Custom _title_\n> \n>\n>",
- "
\n");
}
// Alert markers take precedence over link reference definitions
@Test
public void alertTakesPrecedence() {
- assertRenderingCustomTitles("> [!NOTE]: https://example.com\n> Body text\n\n[!NOTE]",
- "
\n");
assertThat(renderer.render(parser.parse(source))).isEqualTo(expected);
}
@@ -465,9 +508,7 @@ public void alertParsedAsAlertNode() {
@Test
public void customTypeParsedAsAlertNode() {
- var extension = AlertsExtension.builder()
- .addCustomType("INFO", "Information")
- .build();
+ var extension = AlertsExtension.builder().addCustomType("INFO", "Information").build();
var parser = Parser.builder().extensions(Set.of(extension)).build();
@@ -578,5 +619,4 @@ public void titleWithNestedInlineFormattingSourcePosition() {
assertThat(((Text) italicText).getLiteral()).isEqualTo("and italic");
assertThat(italicText.getSourceSpans()).isEqualTo(List.of(SourceSpan.of(0, 28, 28, 10)));
}
-
}
diff --git a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTextContentRendererTest.java b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTextContentRendererTest.java
index 9bc69677c..3979b0488 100644
--- a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTextContentRendererTest.java
+++ b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/AlertsTextContentRendererTest.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.gfm.alerts;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.text.LineBreakRendering;
@@ -7,33 +8,45 @@
import org.commonmark.testutil.Asserts;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
public class AlertsTextContentRendererTest {
private static final Set EXTENSIONS = Set.of(AlertsExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final TextContentRenderer COMPACT_RENDERER = TextContentRenderer.builder()
- .extensions(EXTENSIONS).build();
- private static final TextContentRenderer SEPARATE_RENDERER = TextContentRenderer.builder()
- .extensions(EXTENSIONS).lineBreakRendering(LineBreakRendering.SEPARATE_BLOCKS).build();
- private static final TextContentRenderer STRIPPED_RENDERER = TextContentRenderer.builder()
- .extensions(EXTENSIONS).lineBreakRendering(LineBreakRendering.STRIP).build();
-
- private static final Set EXTENSIONS_CUSTOM_TITLES = Set.of(
- AlertsExtension.builder().allowCustomTitles(true).allowNestedAlerts(true).build());
- private static final Parser PARSER_CUSTOM_TITLES = Parser.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES).build();
-
- private static final TextContentRenderer COMPACT_RENDERER_CUSTOM = TextContentRenderer.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES).build();
- private static final TextContentRenderer SEPARATE_RENDERER_CUSTOM = TextContentRenderer.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES)
- .lineBreakRendering(LineBreakRendering.SEPARATE_BLOCKS).build();
- private static final TextContentRenderer STRIPPED_RENDERER_CUSTOM = TextContentRenderer.builder()
- .extensions(EXTENSIONS_CUSTOM_TITLES)
- .lineBreakRendering(LineBreakRendering.STRIP).build();
+ private static final TextContentRenderer COMPACT_RENDERER =
+ TextContentRenderer.builder().extensions(EXTENSIONS).build();
+ private static final TextContentRenderer SEPARATE_RENDERER =
+ TextContentRenderer.builder()
+ .extensions(EXTENSIONS)
+ .lineBreakRendering(LineBreakRendering.SEPARATE_BLOCKS)
+ .build();
+ private static final TextContentRenderer STRIPPED_RENDERER =
+ TextContentRenderer.builder()
+ .extensions(EXTENSIONS)
+ .lineBreakRendering(LineBreakRendering.STRIP)
+ .build();
+
+ private static final Set EXTENSIONS_CUSTOM_TITLES =
+ Set.of(
+ AlertsExtension.builder()
+ .allowCustomTitles(true)
+ .allowNestedAlerts(true)
+ .build());
+ private static final Parser PARSER_CUSTOM_TITLES =
+ Parser.builder().extensions(EXTENSIONS_CUSTOM_TITLES).build();
+
+ private static final TextContentRenderer COMPACT_RENDERER_CUSTOM =
+ TextContentRenderer.builder().extensions(EXTENSIONS_CUSTOM_TITLES).build();
+ private static final TextContentRenderer SEPARATE_RENDERER_CUSTOM =
+ TextContentRenderer.builder()
+ .extensions(EXTENSIONS_CUSTOM_TITLES)
+ .lineBreakRendering(LineBreakRendering.SEPARATE_BLOCKS)
+ .build();
+ private static final TextContentRenderer STRIPPED_RENDERER_CUSTOM =
+ TextContentRenderer.builder()
+ .extensions(EXTENSIONS_CUSTOM_TITLES)
+ .lineBreakRendering(LineBreakRendering.STRIP)
+ .build();
@Test
public void alertNoBody() {
@@ -123,7 +136,8 @@ public void alertWithinBlockQuote() {
public void alertWithinAlert() {
var source = "> [!NOTE] Custom title\n> Body text\n> > [!WARNING]\n> > Nested body text";
assertCompactCustomTitles(source, "Custom title\nBody text\nWarning\nNested body text");
- assertSeparateCustomTitles(source, "Custom title\n\nBody text\n\nWarning\n\nNested body text");
+ assertSeparateCustomTitles(
+ source, "Custom title\n\nBody text\n\nWarning\n\nNested body text");
assertStrippedCustomTitles(source, "Custom title: Body text Warning: Nested body text");
}
diff --git a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/examples/AlertsExample.java b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/examples/AlertsExample.java
index 34b78385c..26b348016 100644
--- a/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/examples/AlertsExample.java
+++ b/commonmark-ext-gfm-alerts/src/test/java/org/commonmark/ext/gfm/alerts/examples/AlertsExample.java
@@ -1,14 +1,11 @@
package org.commonmark.ext.gfm.alerts.examples;
+import java.util.List;
import org.commonmark.ext.gfm.alerts.AlertsExtension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
-import java.util.List;
-
-/**
- * Example demonstrating the use of the GFM Alerts extension.
- */
+/** Example demonstrating the use of the GFM Alerts extension. */
public class AlertsExample {
public static void main(String[] args) {
@@ -23,25 +20,22 @@ private static void standardTypesExample() {
var extension = AlertsExtension.create();
- var parser = Parser.builder()
- .extensions(List.of(extension))
- .build();
-
- var renderer = HtmlRenderer.builder()
- .extensions(List.of(extension))
- .build();
-
- var markdown = "# GFM Alerts Demo\n\n" +
- "> [!NOTE]\n" +
- "> Highlights information that users should take into account.\n\n" +
- "> [!TIP]\n" +
- "> Helpful advice for doing things better.\n\n" +
- "> [!IMPORTANT]\n" +
- "> Key information users need to know.\n\n" +
- "> [!WARNING]\n" +
- "> Urgent info that needs immediate attention.\n\n" +
- "> [!CAUTION]\n" +
- "> Advises about risks or negative outcomes.\n";
+ var parser = Parser.builder().extensions(List.of(extension)).build();
+
+ var renderer = HtmlRenderer.builder().extensions(List.of(extension)).build();
+
+ var markdown =
+ "# GFM Alerts Demo\n\n"
+ + "> [!NOTE]\n"
+ + "> Highlights information that users should take into account.\n\n"
+ + "> [!TIP]\n"
+ + "> Helpful advice for doing things better.\n\n"
+ + "> [!IMPORTANT]\n"
+ + "> Key information users need to know.\n\n"
+ + "> [!WARNING]\n"
+ + "> Urgent info that needs immediate attention.\n\n"
+ + "> [!CAUTION]\n"
+ + "> Advises about risks or negative outcomes.\n";
var html = renderer.render(parser.parse(markdown));
@@ -55,25 +49,20 @@ private static void customTypesExample() {
System.out.println("CUSTOM ALERT TYPES");
System.out.println("=".repeat(60));
- var extension = AlertsExtension.builder()
- .addCustomType("BUG", "Known Bug")
- .build();
-
- var parser = Parser.builder()
- .extensions(List.of(extension))
- .build();
-
- var renderer = HtmlRenderer.builder()
- .extensions(List.of(extension))
- .build();
-
- var markdown = "# Custom Alert Types\n\n" +
- "> [!NOTE]\n" +
- "> Useful information that users should know.\n\n" +
- "> [!TIP]\n" +
- "> Helpful advice for doing things better.\n\n" +
- "> [!BUG]\n" +
- "> This feature has a known issue with large files (see #42).\n";
+ var extension = AlertsExtension.builder().addCustomType("BUG", "Known Bug").build();
+
+ var parser = Parser.builder().extensions(List.of(extension)).build();
+
+ var renderer = HtmlRenderer.builder().extensions(List.of(extension)).build();
+
+ var markdown =
+ "# Custom Alert Types\n\n"
+ + "> [!NOTE]\n"
+ + "> Useful information that users should know.\n\n"
+ + "> [!TIP]\n"
+ + "> Helpful advice for doing things better.\n\n"
+ + "> [!BUG]\n"
+ + "> This feature has a known issue with large files (see #42).\n";
var html = renderer.render(parser.parse(markdown));
diff --git a/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/Strikethrough.java b/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/Strikethrough.java
index 0c24642bc..76ce213e8 100644
--- a/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/Strikethrough.java
+++ b/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/Strikethrough.java
@@ -3,9 +3,7 @@
import org.commonmark.node.CustomNode;
import org.commonmark.node.Delimited;
-/**
- * A strikethrough node containing text and other inline nodes as children.
- */
+/** A strikethrough node containing text and other inline nodes as children. */
public class Strikethrough extends CustomNode implements Delimited {
private String delimiter;
diff --git a/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/StrikethroughExtension.java b/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/StrikethroughExtension.java
index 0571aed84..4b18b7d66 100644
--- a/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/StrikethroughExtension.java
+++ b/commonmark-ext-gfm-strikethrough/src/main/java/org/commonmark/ext/gfm/strikethrough/StrikethroughExtension.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.gfm.strikethrough;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.strikethrough.internal.StrikethroughDelimiterProcessor;
import org.commonmark.ext.gfm.strikethrough.internal.StrikethroughHtmlNodeRenderer;
@@ -13,38 +14,40 @@
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.commonmark.renderer.text.TextContentRenderer;
-import java.util.Set;
-
/**
* Extension for GFM strikethrough using {@code ~} or {@code ~~} (GitHub Flavored Markdown).
- *
Example input:
+ *
+ *
Example input:
+ *
*
{@code ~foo~ or ~~bar~~}
- *
Example output (HTML):
+ *
+ *
Example output (HTML):
+ *
*
{@code foo or bar}
- *
- * Create the extension with {@link #create()} and then add it to the parser and renderer builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
- *
- * The parsed strikethrough text regions are turned into {@link Strikethrough} nodes.
- *
- *
- * If you have another extension that only uses a single tilde ({@code ~}) syntax, you will have to configure this
- * {@link StrikethroughExtension} to only accept the double tilde syntax, like this:
- *
- * If you don't do that, there's a conflict between the two extensions and you will get an
- * {@link IllegalArgumentException} when constructing the parser.
- *
+ *
+ *
Create the extension with {@link #create()} and then add it to the parser and renderer
+ * builders ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
+ *
+ *
The parsed strikethrough text regions are turned into {@link Strikethrough} nodes.
+ *
+ *
If you have another extension that only uses a single tilde ({@code ~}) syntax, you will have
+ * to configure this {@link StrikethroughExtension} to only accept the double tilde syntax, like
+ * this:
+ *
+ *
\n");
}
@@ -96,12 +98,15 @@ public void textContentRenderer() {
@Test
public void requireTwoTildesOption() {
- Parser parser = Parser.builder()
- .extensions(Set.of(StrikethroughExtension.builder()
- .requireTwoTildes(true)
- .build()))
- .customDelimiterProcessor(new SubscriptDelimiterProcessor())
- .build();
+ Parser parser =
+ Parser.builder()
+ .extensions(
+ Set.of(
+ StrikethroughExtension.builder()
+ .requireTwoTildes(true)
+ .build()))
+ .customDelimiterProcessor(new SubscriptDelimiterProcessor())
+ .build();
Node document = parser.parse("~foo~ ~~bar~~");
assertThat(CONTENT_RENDERER.render(document)).isEqualTo("(sub)foo(/sub) /bar/");
@@ -109,10 +114,11 @@ public void requireTwoTildesOption() {
@Test
public void sourceSpans() {
- Parser parser = Parser.builder()
- .extensions(EXTENSIONS)
- .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
- .build();
+ Parser parser =
+ Parser.builder()
+ .extensions(EXTENSIONS)
+ .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
+ .build();
Node document = parser.parse("hey ~~there~~\n");
Paragraph block = (Paragraph) document.getFirstChild();
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBlock.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBlock.java
index c46fc27ef..3ad550907 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBlock.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBlock.java
@@ -2,8 +2,5 @@
import org.commonmark.node.CustomBlock;
-/**
- * Table block containing a {@link TableHead} and optionally a {@link TableBody}.
- */
-public class TableBlock extends CustomBlock {
-}
+/** Table block containing a {@link TableHead} and optionally a {@link TableBody}. */
+public class TableBlock extends CustomBlock {}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBody.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBody.java
index ddc80deb3..09f5b45b1 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBody.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableBody.java
@@ -2,8 +2,5 @@
import org.commonmark.node.CustomNode;
-/**
- * Body part of a {@link TableBlock} containing {@link TableRow TableRows}.
- */
-public class TableBody extends CustomNode {
-}
+/** Body part of a {@link TableBlock} containing {@link TableRow TableRows}. */
+public class TableBody extends CustomNode {}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableCell.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableCell.java
index 033c2dd04..d4ad1f171 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableCell.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableCell.java
@@ -2,9 +2,7 @@
import org.commonmark.node.CustomNode;
-/**
- * Table cell of a {@link TableRow} containing inline nodes.
- */
+/** Table cell of a {@link TableRow} containing inline nodes. */
public class TableCell extends CustomNode {
private boolean header;
@@ -34,7 +32,8 @@ public void setAlignment(Alignment alignment) {
}
/**
- * @return the cell width (the number of dash and colon characters in the delimiter row of the table for this column)
+ * @return the cell width (the number of dash and colon characters in the delimiter row of the
+ * table for this column)
*/
public int getWidth() {
return width;
@@ -44,11 +43,10 @@ public void setWidth(int width) {
this.width = width;
}
- /**
- * How the cell is aligned horizontally.
- */
+ /** How the cell is aligned horizontally. */
public enum Alignment {
- LEFT, CENTER, RIGHT
+ LEFT,
+ CENTER,
+ RIGHT
}
-
}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableHead.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableHead.java
index 96a95e620..fa771f8f7 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableHead.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableHead.java
@@ -2,8 +2,5 @@
import org.commonmark.node.CustomNode;
-/**
- * Head part of a {@link TableBlock} containing {@link TableRow TableRows}.
- */
-public class TableHead extends CustomNode {
-}
+/** Head part of a {@link TableBlock} containing {@link TableRow TableRows}. */
+public class TableHead extends CustomNode {}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableRow.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableRow.java
index 1325875d0..19b31b9bc 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableRow.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TableRow.java
@@ -5,5 +5,4 @@
/**
* Table row of a {@link TableHead} or {@link TableBody} containing {@link TableCell TableCells}.
*/
-public class TableRow extends CustomNode {
-}
+public class TableRow extends CustomNode {}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TablesExtension.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TablesExtension.java
index 4740e9aad..582c30aae 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TablesExtension.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/TablesExtension.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.gfm.tables;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.internal.TableBlockParser;
import org.commonmark.ext.gfm.tables.internal.TableHtmlNodeRenderer;
@@ -13,26 +14,25 @@
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.commonmark.renderer.text.TextContentRenderer;
-import java.util.Set;
-
/**
* Extension for GFM tables using "|" pipes (GitHub Flavored Markdown).
- *
- * Create it with {@link #create()} and then configure it on the builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
- *
- * The parsed tables are turned into {@link TableBlock} blocks.
- *
Create it with {@link #create()} and then configure it on the builders ({@link
+ * org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
+ *
+ *
The parsed tables are turned into {@link TableBlock} blocks.
+ *
+ * @see Tables (extension) in GitHub
+ * Flavored Markdown Spec
*/
-public class TablesExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension,
- TextContentRenderer.TextContentRendererExtension, MarkdownRenderer.MarkdownRendererExtension {
+public class TablesExtension
+ implements Parser.ParserExtension,
+ HtmlRenderer.HtmlRendererExtension,
+ TextContentRenderer.TextContentRendererExtension,
+ MarkdownRenderer.MarkdownRendererExtension {
- private TablesExtension() {
- }
+ private TablesExtension() {}
public static Extension create() {
return new TablesExtension();
@@ -55,16 +55,17 @@ public void extend(TextContentRenderer.Builder rendererBuilder) {
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
- @Override
- public NodeRenderer create(MarkdownNodeRendererContext context) {
- return new TableMarkdownNodeRenderer(context);
- }
+ rendererBuilder.nodeRendererFactory(
+ new MarkdownNodeRendererFactory() {
+ @Override
+ public NodeRenderer create(MarkdownNodeRendererContext context) {
+ return new TableMarkdownNodeRenderer(context);
+ }
- @Override
- public Set getSpecialCharacters() {
- return Set.of('|');
- }
- });
+ @Override
+ public Set getSpecialCharacters() {
+ return Set.of('|');
+ }
+ });
}
}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableBlockParser.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableBlockParser.java
index 49f17194d..5e74e78eb 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableBlockParser.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableBlockParser.java
@@ -1,5 +1,7 @@
package org.commonmark.ext.gfm.tables.internal;
+import java.util.ArrayList;
+import java.util.List;
import org.commonmark.ext.gfm.tables.*;
import org.commonmark.node.Block;
import org.commonmark.node.Node;
@@ -10,9 +12,6 @@
import org.commonmark.parser.block.*;
import org.commonmark.text.Characters;
-import java.util.ArrayList;
-import java.util.List;
-
public class TableBlockParser extends AbstractBlockParser {
private final TableBlock block = new TableBlock();
@@ -42,8 +41,10 @@ public BlockContinue tryContinue(ParserState state) {
int pipe = Characters.find('|', content, state.getNextNonSpaceIndex());
if (pipe != -1) {
if (pipe == state.getNextNonSpaceIndex()) {
- // If we *only* have a pipe character (and whitespace), that is not a valid table row and ends the table.
- if (Characters.skipSpaceTab(content, pipe + 1, content.length()) == content.length()) {
+ // If we *only* have a pipe character (and whitespace), that is not a valid table
+ // row and ends the table.
+ if (Characters.skipSpaceTab(content, pipe + 1, content.length())
+ == content.length()) {
// We also don't want the pipe to be added via lazy continuation.
canHaveLazyContinuationLines = false;
return BlockContinue.none();
@@ -88,7 +89,8 @@ public void parseInlines(InlineParser inlineParser) {
// Body starts at index 2. 0 is header, 1 is separator.
for (int rowIndex = 2; rowIndex < rowLines.size(); rowIndex++) {
SourceLine rowLine = rowLines.get(rowIndex);
- SourceSpan sourceSpan = rowIndex < sourceSpans.size() ? sourceSpans.get(rowIndex) : null;
+ SourceSpan sourceSpan =
+ rowIndex < sourceSpans.size() ? sourceSpans.get(rowIndex) : null;
List cells = split(rowLine);
TableRow row = new TableRow();
if (sourceSpan != null) {
@@ -103,7 +105,8 @@ public void parseInlines(InlineParser inlineParser) {
}
if (body == null) {
- // It's valid to have a table without body. In that case, don't add an empty TableBody node.
+ // It's valid to have a table without body. In that case, don't add an empty
+ // TableBody node.
body = new TableBody();
block.appendChild(body);
}
@@ -152,9 +155,10 @@ private static List split(SourceLine line) {
switch (c) {
case '\\':
if (i + 1 < cellEnd && row.charAt(i + 1) == '|') {
- // Pipe is special for table parsing. An escaped pipe doesn't result in a new cell, but is
- // passed down to inline parsing as an unescaped pipe. Note that that applies even for the `\|`
- // in an input like `\\|` - in other words, table parsing doesn't support escaping backslashes.
+ // Pipe is special for table parsing. An escaped pipe doesn't result in a
+ // new cell, but is passed down to inline parsing as an unescaped pipe. Note
+ // that that applies even for the `\|` in an input like `\\|` - in other
+ // words, table parsing doesn't support escaping backslashes.
sb.append('|');
i++;
} else {
@@ -176,7 +180,10 @@ private static List split(SourceLine line) {
}
if (sb.length() > 0) {
String content = sb.toString();
- cells.add(SourceLine.of(content, line.substring(cellStart, line.getContent().length()).getSourceSpan()));
+ cells.add(
+ SourceLine.of(
+ content,
+ line.substring(cellStart, line.getContent().length()).getSourceSpan()));
}
return cells;
}
@@ -211,7 +218,8 @@ private static List parseSeparator(CharSequence s) {
case '-':
case ':':
if (pipes == 0 && !columns.isEmpty()) {
- // Need a pipe after the first column (first column doesn't need to start with one)
+ // Need a pipe after the first column (first column doesn't need to start
+ // with one)
return null;
}
boolean left = false;
@@ -274,9 +282,14 @@ public static class Factory extends AbstractBlockParserFactory {
@Override
public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockParser) {
List paragraphLines = matchedBlockParser.getParagraphLines().getLines();
- if (!paragraphLines.isEmpty() && Characters.find('|', paragraphLines.get(paragraphLines.size() - 1).getContent(), 0) != -1) {
+ if (paragraphLines.isEmpty()) {
+ return BlockStart.none();
+ }
+ var previousLine = paragraphLines.get(paragraphLines.size() - 1).getContent();
+ if (Characters.find('|', previousLine, 0) != -1) {
SourceLine line = state.getLine();
- SourceLine separatorLine = line.substring(state.getIndex(), line.getContent().length());
+ SourceLine separatorLine =
+ line.substring(state.getIndex(), line.getContent().length());
List columns = parseSeparator(separatorLine.getContent());
if (columns != null && !columns.isEmpty()) {
SourceLine paragraph = paragraphLines.get(paragraphLines.size() - 1);
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableHtmlNodeRenderer.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableHtmlNodeRenderer.java
index 966c4c151..81e584c9d 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableHtmlNodeRenderer.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableHtmlNodeRenderer.java
@@ -1,12 +1,11 @@
package org.commonmark.ext.gfm.tables.internal;
+import java.util.Map;
import org.commonmark.ext.gfm.tables.*;
import org.commonmark.node.Node;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;
-import java.util.Map;
-
public class TableHtmlNodeRenderer extends TableNodeRenderer {
private final HtmlWriter htmlWriter;
@@ -69,7 +68,8 @@ private Map getAttributes(Node node, String tagName) {
private Map getCellAttributes(TableCell tableCell, String tagName) {
if (tableCell.getAlignment() != null) {
- return context.extendAttributes(tableCell, tagName, Map.of("align", getAlignValue(tableCell.getAlignment())));
+ return context.extendAttributes(
+ tableCell, tagName, Map.of("align", getAlignValue(tableCell.getAlignment())));
} else {
return context.extendAttributes(tableCell, tagName, Map.of());
}
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableMarkdownNodeRenderer.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableMarkdownNodeRenderer.java
index b0705f579..a9c4f9049 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableMarkdownNodeRenderer.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableMarkdownNodeRenderer.java
@@ -1,16 +1,16 @@
package org.commonmark.ext.gfm.tables.internal;
+import java.util.ArrayList;
+import java.util.List;
import org.commonmark.ext.gfm.tables.*;
import org.commonmark.node.Node;
import org.commonmark.renderer.markdown.MarkdownNodeRendererContext;
import org.commonmark.renderer.markdown.MarkdownWriter;
import org.commonmark.text.AsciiMatcher;
-import java.util.ArrayList;
-import java.util.List;
-
/**
- * The Table node renderer that is needed for rendering GFM tables (GitHub Flavored Markdown) to text content.
+ * The Table node renderer that is needed for rendering GFM tables (GitHub Flavored Markdown) to
+ * text content.
*/
public class TableMarkdownNodeRenderer extends TableNodeRenderer {
private final MarkdownWriter writer;
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableNodeRenderer.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableNodeRenderer.java
index 2982e1518..4e3a00815 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableNodeRenderer.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableNodeRenderer.java
@@ -1,11 +1,10 @@
package org.commonmark.ext.gfm.tables.internal;
+import java.util.Set;
import org.commonmark.ext.gfm.tables.*;
import org.commonmark.node.Node;
import org.commonmark.renderer.NodeRenderer;
-import java.util.Set;
-
abstract class TableNodeRenderer implements NodeRenderer {
@Override
@@ -15,8 +14,7 @@ public Set> getNodeTypes() {
TableHead.class,
TableBody.class,
TableRow.class,
- TableCell.class
- );
+ TableCell.class);
}
@Override
diff --git a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableTextContentNodeRenderer.java b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableTextContentNodeRenderer.java
index 0ba6894b5..b9e17c1d3 100644
--- a/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableTextContentNodeRenderer.java
+++ b/commonmark-ext-gfm-tables/src/main/java/org/commonmark/ext/gfm/tables/internal/TableTextContentNodeRenderer.java
@@ -10,7 +10,8 @@
import org.commonmark.renderer.text.TextContentWriter;
/**
- * The Table node renderer that is needed for rendering GFM tables (GitHub Flavored Markdown) to text content.
+ * The Table node renderer that is needed for rendering GFM tables (GitHub Flavored Markdown) to
+ * text content.
*/
public class TableTextContentNodeRenderer extends TableNodeRenderer {
diff --git a/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TableMarkdownRendererTest.java b/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TableMarkdownRendererTest.java
index 85c11206c..32a8218b2 100644
--- a/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TableMarkdownRendererTest.java
+++ b/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TableMarkdownRendererTest.java
@@ -1,19 +1,19 @@
package org.commonmark.ext.gfm.tables;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class TableMarkdownRendererTest {
private static final Set EXTENSIONS = Set.of(TablesExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final MarkdownRenderer RENDERER = MarkdownRenderer.builder().extensions(EXTENSIONS).build();
+ private static final MarkdownRenderer RENDERER =
+ MarkdownRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void testHeadNoBody() {
@@ -60,7 +60,8 @@ public void testEscaping() {
@Test
public void testEscaped() {
- // `|` in Text nodes needs to be escaped, otherwise the generated Markdown does not get parsed back as a table
+ // `|` in Text nodes needs to be escaped, otherwise the generated Markdown does not get
+ // parsed back as a table
assertRoundTrip("\\|Abc\\|\n\\|---\\|\n");
}
diff --git a/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesSpecTest.java b/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesSpecTest.java
index e7f3db4d1..81def7c2e 100644
--- a/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesSpecTest.java
+++ b/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesSpecTest.java
@@ -1,5 +1,7 @@
package org.commonmark.ext.gfm.tables;
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
@@ -12,19 +14,16 @@
import org.junit.jupiter.params.ParameterizedClass;
import org.junit.jupiter.params.provider.MethodSource;
-import java.util.List;
-import java.util.Set;
-
@ParameterizedClass
@MethodSource("data")
public class TablesSpecTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(TablesExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
- @Parameter
- Example example;
+ @Parameter Example example;
static List data() {
return ExampleReader.readExamples(TestResources.getGfmSpec(), "table");
diff --git a/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesTest.java b/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesTest.java
index 98c3ad4d7..f872c0cde 100644
--- a/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesTest.java
+++ b/commonmark-ext-gfm-tables/src/test/java/org/commonmark/ext/gfm/tables/TablesTest.java
@@ -1,5 +1,9 @@
package org.commonmark.ext.gfm.tables;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.*;
import org.commonmark.parser.IncludeSourceSpans;
@@ -9,16 +13,12 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class TablesTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(TablesExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void mustHaveHeaderAndSeparator() {
@@ -28,22 +28,26 @@ public void mustHaveHeaderAndSeparator() {
@Test
public void separatorMustBeOneOrMore() {
- assertRendering("Abc|Def\n-|-", "
\n" +
- "\n" +
- "
\n" +
- "
Abc
\n" +
- "
Def
\n" +
- "
\n" +
- "\n" +
- "
\n");
- assertRendering("Abc|Def\n--|--", "
\n" +
- "\n" +
- "
\n" +
- "
Abc
\n" +
- "
Def
\n" +
- "
\n" +
- "\n" +
- "
\n");
+ assertRendering(
+ "Abc|Def\n-|-",
+ "
\n"
+ + "\n"
+ + "
\n"
+ + "
Abc
\n"
+ + "
Def
\n"
+ + "
\n"
+ + "\n"
+ + "
\n");
+ assertRendering(
+ "Abc|Def\n--|--",
+ "
\n"
+ + "\n"
+ + "
\n"
+ + "
Abc
\n"
+ + "
Def
\n"
+ + "
\n"
+ + "\n"
+ + "
\n");
}
@Test
@@ -55,14 +59,16 @@ public void separatorMustNotContainInvalidChars() {
@Test
public void separatorCanHaveLeadingSpaceThenPipe() {
- assertRendering("Abc|Def\n |---|---", "
\n");
}
@Test
public void pipesOnOutsideZeroLengthHeaders() {
// This is literally what someone has done IRL - it helped to expose
// an issue with parsing the last header cell correctly
- assertRendering("||center header||\n" +
- "-|-------------|-\n" +
- "1| 2 |3",
- "
\n");
}
@Test
public void escapedBackslash() {
- // This is a bit weird in the GFM spec IMO. `1\\|2` looks like an escaped backslash, followed by a pipe
- // (so two cells). Instead, the `\|` is parsed as an escaped pipe first, so just a single cell. The inline
- // parser then gets `1\|2` which renders as `1|2`.
- assertRendering("Abc|Def\n---|---\n1\\\\|2", "
\n" +
- "\n" +
- "
\n" +
- "
Abc
\n" +
- "
Def
\n" +
- "
\n" +
- "\n" +
- "\n" +
- "
\n" +
- "
1|2
\n" +
- "
\n" +
- "
\n" +
- "\n" +
- "
\n");
+ // This is a bit weird in the GFM spec IMO. `1\\|2` looks like an escaped backslash,
+ // followed by a pipe (so two cells). Instead, the `\|` is parsed as an escaped pipe first,
+ // so just a single cell. The inline parser then gets `1\|2` which renders as `1|2`.
+ assertRendering(
+ "Abc|Def\n---|---\n1\\\\|2",
+ "
\n"
+ + "\n"
+ + "
\n"
+ + "
Abc
\n"
+ + "
Def
\n"
+ + "
\n"
+ + "\n"
+ + "\n"
+ + "
\n"
+ + "
1|2
\n"
+ + "
\n"
+ + "
\n"
+ + "\n"
+ + "
\n");
}
@Test
public void escapedOther() {
- // This is a tricky one. For \`, we don't want to remove the backslash when we parse the table, otherwise
- // inline parsing is wrong. So we have to be careful where we do/don't consume the backslash.
- assertRendering("Abc|Def\n---|---\n1|\\`not code`", "
\n" +
- "\n" +
- "
\n" +
- "
Abc
\n" +
- "
Def
\n" +
- "
\n" +
- "\n" +
- "\n" +
- "
\n" +
- "
1
\n" +
- "
`not code`
\n" +
- "
\n" +
- "\n" +
- "
\n");
+ // This is a tricky one. For \`, we don't want to remove the backslash when we parse the
+ // table, otherwise inline parsing is wrong. So we have to be careful where we do/don't
+ // consume the backslash.
+ assertRendering(
+ "Abc|Def\n---|---\n1|\\`not code`",
+ "
\n"
+ + "\n"
+ + "
\n"
+ + "
Abc
\n"
+ + "
Def
\n"
+ + "
\n"
+ + "\n"
+ + "\n"
+ + "
\n"
+ + "
1
\n"
+ + "
`not code`
\n"
+ + "
\n"
+ + "\n"
+ + "
\n");
}
@Test
public void backslashAtEnd() {
- assertRendering("Abc|Def\n---|---\n1|2\\", "
- * Create it with {@link #create()} or {@link #builder()} and then configure it on the
- * renderer builder ({@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
- * The heading text will be used to create the id. Multiple headings with the
- * same text will result in appending a hyphen and number. For example:
+ *
+ *
Create it with {@link #create()} or {@link #builder()} and then configure it on the renderer
+ * builder ({@link HtmlRenderer.Builder#extensions(Iterable)}).
+ *
+ *
The heading text will be used to create the id. Multiple headings with the same text will
+ * result in appending a hyphen and number. For example:
+ *
*
* # Heading
* # Heading
*
+ *
* will result in
+ *
*
* <h1 id="heading">Heading</h1>
* <h1 id="heading-1">Heading</h1>
@@ -52,7 +55,8 @@ public static Builder builder() {
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
- rendererBuilder.attributeProviderFactory(context -> HeadingIdAttributeProvider.create(defaultId, idPrefix, idSuffix));
+ rendererBuilder.attributeProviderFactory(
+ context -> HeadingIdAttributeProvider.create(defaultId, idPrefix, idSuffix));
}
public static class Builder {
@@ -61,7 +65,8 @@ public static class Builder {
private String idSuffix = "";
/**
- * @param value Default value for the id to take if no generated id can be extracted. Default "id"
+ * @param value Default value for the id to take if no generated id can be extracted.
+ * Default "id"
* @return {@code this}
*/
public Builder defaultId(String value) {
diff --git a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/IdGenerator.java b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/IdGenerator.java
index 2c37433e2..8ab5b3b32 100644
--- a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/IdGenerator.java
+++ b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/IdGenerator.java
@@ -7,8 +7,8 @@
/**
* Generates strings to be used as identifiers.
- *
- * Use {@link #builder()} to create an instance.
+ *
+ *
Use {@link #builder()} to create an instance.
*/
public class IdGenerator {
private final Pattern allowedCharacters;
@@ -33,35 +33,35 @@ public static Builder builder() {
}
/**
- *
* Generate an ID based on the provided text and previously generated IDs.
- *
- * This method is not thread safe, concurrent calls can end up
- * with non-unique identifiers.
- *
- * Note that collision can occur in the case that
+ *
+ *
This method is not thread safe, concurrent calls can end up with non-unique identifiers.
+ *
+ *
Note that collision can occur in the case that
+ *
*
- *
Method called with 'X'
- *
Method called with 'X' again
- *
Method called with 'X-1'
+ *
Method called with 'X'
+ *
Method called with 'X' again
+ *
Method called with 'X-1'
*
- *
- * In that case, the three generated IDs will be:
+ *
+ *
In that case, the three generated IDs will be:
+ *
*
- *
X
- *
X-1
- *
X-1
+ *
X
+ *
X-1
+ *
X-1
*
- *
- * Therefore if collisions are unacceptable you should ensure that
- * numbers are stripped from end of {@code text}.
*
- * @param text Text that the identifier should be based on. Will be normalised, then used to generate the
- * identifier.
- * @return {@code text} if this is the first instance that the {@code text} has been passed
- * to the method. Otherwise, {@code text + "-" + X} will be returned, where X is the number of times
- * that {@code text} has previously been passed in. If {@code text} is empty, the default
- * identifier given in the constructor will be used.
+ *
Therefore if collisions are unacceptable you should ensure that numbers are stripped from
+ * end of {@code text}.
+ *
+ * @param text Text that the identifier should be based on. Will be normalised, then used to
+ * generate the identifier.
+ * @return {@code text} if this is the first instance that the {@code text} has been passed to
+ * the method. Otherwise, {@code text + "-" + X} will be returned, where X is the number of
+ * times that {@code text} has previously been passed in. If {@code text} is empty, the
+ * default identifier given in the constructor will be used.
*/
public String generateId(String text) {
String normalizedIdentity = text != null ? normalizeText(text) : defaultIdentifier;
@@ -85,7 +85,8 @@ private static Pattern compileAllowedCharactersPattern() {
try {
return Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
} catch (IllegalArgumentException e) {
- // Android only supports the flag in API level 24. But it actually uses Unicode character classes by
+ // Android only supports the flag in API level 24. But it actually uses Unicode
+ // character classes by
// default, so not specifying the flag is ok. See issue #71.
return Pattern.compile(regex);
}
@@ -119,7 +120,8 @@ public IdGenerator build() {
}
/**
- * @param defaultId the default identifier to use in case the provided text is empty or only contains unusable characters
+ * @param defaultId the default identifier to use in case the provided text is empty or only
+ * contains unusable characters
* @return {@code this}
*/
public Builder defaultId(String defaultId) {
diff --git a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java
index 6b8792bd5..f7d1b75a1 100644
--- a/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java
+++ b/commonmark-ext-heading-anchor/src/main/java/org/commonmark/ext/heading/anchor/internal/HeadingIdAttributeProvider.java
@@ -1,26 +1,23 @@
package org.commonmark.ext.heading.anchor.internal;
-import org.commonmark.ext.heading.anchor.IdGenerator;
-import org.commonmark.renderer.html.AttributeProvider;
-import org.commonmark.node.*;
-
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import org.commonmark.ext.heading.anchor.IdGenerator;
+import org.commonmark.node.*;
+import org.commonmark.renderer.html.AttributeProvider;
public class HeadingIdAttributeProvider implements AttributeProvider {
private final IdGenerator idGenerator;
private HeadingIdAttributeProvider(String defaultId, String prefix, String suffix) {
- idGenerator = IdGenerator.builder()
- .defaultId(defaultId)
- .prefix(prefix)
- .suffix(suffix)
- .build();
+ idGenerator =
+ IdGenerator.builder().defaultId(defaultId).prefix(prefix).suffix(suffix).build();
}
- public static HeadingIdAttributeProvider create(String defaultId, String prefix, String suffix) {
+ public static HeadingIdAttributeProvider create(
+ String defaultId, String prefix, String suffix) {
return new HeadingIdAttributeProvider(defaultId, prefix, suffix);
}
@@ -31,17 +28,18 @@ public void setAttributes(Node node, String tagName, final Map a
final List wordList = new ArrayList<>();
- node.accept(new AbstractVisitor() {
- @Override
- public void visit(Text text) {
- wordList.add(text.getLiteral());
- }
-
- @Override
- public void visit(Code code) {
- wordList.add(code.getLiteral());
- }
- });
+ node.accept(
+ new AbstractVisitor() {
+ @Override
+ public void visit(Text text) {
+ wordList.add(text.getLiteral());
+ }
+
+ @Override
+ public void visit(Code code) {
+ wordList.add(code.getLiteral());
+ }
+ });
String finalString = "";
for (String word : wordList) {
diff --git a/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorConfigurationTest.java b/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorConfigurationTest.java
index 438a3a9bd..c78b7c61a 100644
--- a/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorConfigurationTest.java
+++ b/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorConfigurationTest.java
@@ -1,34 +1,31 @@
package org.commonmark.ext.heading.anchor;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.junit.jupiter.api.Test;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class HeadingAnchorConfigurationTest {
private static final Parser PARSER = Parser.builder().build();
private HtmlRenderer buildRenderer(String defaultId, String prefix, String suffix) {
- Extension ext = HeadingAnchorExtension.builder()
- .defaultId(defaultId)
- .idPrefix(prefix)
- .idSuffix(suffix)
- .build();
- return HtmlRenderer.builder()
- .extensions(List.of(ext))
- .build();
+ Extension ext =
+ HeadingAnchorExtension.builder()
+ .defaultId(defaultId)
+ .idPrefix(prefix)
+ .idSuffix(suffix)
+ .build();
+ return HtmlRenderer.builder().extensions(List.of(ext)).build();
}
@Test
public void testDefaultConfigurationHasNoAdditions() {
- HtmlRenderer renderer = HtmlRenderer.builder()
- .extensions(List.of(HeadingAnchorExtension.create()))
- .build();
+ HtmlRenderer renderer =
+ HtmlRenderer.builder().extensions(List.of(HeadingAnchorExtension.create())).build();
assertThat(doRender(renderer, "# ")).isEqualTo("\n");
}
@@ -53,5 +50,4 @@ public void testSuffixAddedToHeader() {
private String doRender(HtmlRenderer renderer, String text) {
return renderer.render(PARSER.parse(text));
}
-
}
diff --git a/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorTest.java b/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorTest.java
index 3149542e3..95ee2d7eb 100644
--- a/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorTest.java
+++ b/commonmark-ext-heading-anchor/src/test/java/org/commonmark/ext/heading/anchor/HeadingAnchorTest.java
@@ -1,34 +1,35 @@
package org.commonmark.ext.heading.anchor;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
public class HeadingAnchorTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(HeadingAnchorExtension.create());
private static final Parser PARSER = Parser.builder().build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void baseCaseSingleHeader() {
- assertRendering("# Heading here\n",
- "
\n");
}
@Override
diff --git a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributes.java b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributes.java
index 1ee43958b..1739aae77 100644
--- a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributes.java
+++ b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributes.java
@@ -1,13 +1,10 @@
package org.commonmark.ext.image.attributes;
+import java.util.Map;
import org.commonmark.node.CustomNode;
import org.commonmark.node.Delimited;
-import java.util.Map;
-
-/**
- * A node containing text and other inline nodes as children.
- */
+/** A node containing text and other inline nodes as children. */
public class ImageAttributes extends CustomNode implements Delimited {
private final Map attributes;
diff --git a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributesExtension.java b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributesExtension.java
index 9a4de2628..f6becc651 100644
--- a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributesExtension.java
+++ b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/ImageAttributesExtension.java
@@ -8,18 +8,17 @@
/**
* Extension for adding attributes to image nodes.
- *
- * Create it with {@link #create()} and then configure it on the builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
+ *
+ *
Create it with {@link #create()} and then configure it on the builders ({@link
+ * org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
*
* @since 0.15.0
*/
-public class ImageAttributesExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension {
+public class ImageAttributesExtension
+ implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension {
- private ImageAttributesExtension() {
- }
+ private ImageAttributesExtension() {}
public static Extension create() {
return new ImageAttributesExtension();
@@ -32,6 +31,7 @@ public void extend(Parser.Builder parserBuilder) {
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
- rendererBuilder.attributeProviderFactory(context -> ImageAttributesAttributeProvider.create());
+ rendererBuilder.attributeProviderFactory(
+ context -> ImageAttributesAttributeProvider.create());
}
}
diff --git a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesAttributeProvider.java b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesAttributeProvider.java
index bd89738de..c132c9dcd 100644
--- a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesAttributeProvider.java
+++ b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesAttributeProvider.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.image.attributes.internal;
+import java.util.*;
import org.commonmark.ext.image.attributes.ImageAttributes;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.CustomNode;
@@ -7,12 +8,9 @@
import org.commonmark.node.Node;
import org.commonmark.renderer.html.AttributeProvider;
-import java.util.*;
-
public class ImageAttributesAttributeProvider implements AttributeProvider {
- private ImageAttributesAttributeProvider() {
- }
+ private ImageAttributesAttributeProvider() {}
public static ImageAttributesAttributeProvider create() {
return new ImageAttributesAttributeProvider();
@@ -21,17 +19,18 @@ public static ImageAttributesAttributeProvider create() {
@Override
public void setAttributes(Node node, String tagName, final Map attributes) {
if (node instanceof Image) {
- node.accept(new AbstractVisitor() {
- @Override
- public void visit(CustomNode node) {
- if (node instanceof ImageAttributes) {
- ImageAttributes imageAttributes = (ImageAttributes) node;
- attributes.putAll(imageAttributes.getAttributes());
- // Now that we have used the image attributes we remove the node.
- imageAttributes.unlink();
- }
- }
- });
+ node.accept(
+ new AbstractVisitor() {
+ @Override
+ public void visit(CustomNode node) {
+ if (node instanceof ImageAttributes) {
+ ImageAttributes imageAttributes = (ImageAttributes) node;
+ attributes.putAll(imageAttributes.getAttributes());
+ // Now that we have used the image attributes we remove the node.
+ imageAttributes.unlink();
+ }
+ }
+ });
}
}
}
diff --git a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesDelimiterProcessor.java b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesDelimiterProcessor.java
index 06a39ba23..53ba882c9 100644
--- a/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesDelimiterProcessor.java
+++ b/commonmark-ext-image-attributes/src/main/java/org/commonmark/ext/image/attributes/internal/ImageAttributesDelimiterProcessor.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.image.attributes.internal;
+import java.util.*;
import org.commonmark.ext.image.attributes.ImageAttributes;
import org.commonmark.node.Image;
import org.commonmark.node.Node;
@@ -8,8 +9,6 @@
import org.commonmark.parser.delimiter.DelimiterProcessor;
import org.commonmark.parser.delimiter.DelimiterRun;
-import java.util.*;
-
public class ImageAttributesDelimiterProcessor implements DelimiterProcessor {
// Only allow a defined set of attributes to be used.
@@ -36,8 +35,8 @@ public int process(DelimiterRun openingRun, DelimiterRun closingRun) {
return 0;
}
- // Check if the attributes can be applied - if the previous node is an Image, and if all the attributes are in
- // the set of SUPPORTED_ATTRIBUTES
+ // Check if the attributes can be applied - if the previous node is an Image, and if all the
+ // attributes are in the set of SUPPORTED_ATTRIBUTES
Text opener = openingRun.getOpener();
Node nodeToStyle = opener.getPrevious();
if (!(nodeToStyle instanceof Image)) {
@@ -53,7 +52,8 @@ public int process(DelimiterRun openingRun, DelimiterRun closingRun) {
content.append(((Text) node).getLiteral());
toUnlink.add(node);
} else {
- // This node type is not supported, so stop here (no need to check any further ones).
+ // This node type is not supported, so stop here (no need to check any further
+ // ones).
return 0;
}
}
@@ -65,7 +65,8 @@ public int process(DelimiterRun openingRun, DelimiterRun closingRun) {
if (attribute.length > 1 && SUPPORTED_ATTRIBUTES.contains(attribute[0].toLowerCase())) {
attributesMap.put(attribute[0], attribute[1]);
} else {
- // This attribute is not supported, so stop here (no need to check any further ones).
+ // This attribute is not supported, so stop here (no need to check any further
+ // ones).
return 0;
}
}
diff --git a/commonmark-ext-image-attributes/src/test/java/org/commonmark/ext/image/attributes/ImageAttributesTest.java b/commonmark-ext-image-attributes/src/test/java/org/commonmark/ext/image/attributes/ImageAttributesTest.java
index 3edf8497e..4232646a2 100644
--- a/commonmark-ext-image-attributes/src/test/java/org/commonmark/ext/image/attributes/ImageAttributesTest.java
+++ b/commonmark-ext-image-attributes/src/test/java/org/commonmark/ext/image/attributes/ImageAttributesTest.java
@@ -1,5 +1,9 @@
package org.commonmark.ext.image.attributes;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.Node;
import org.commonmark.node.Paragraph;
@@ -10,44 +14,48 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class ImageAttributesTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(ImageAttributesExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void baseCase() {
- assertRendering("{height=5}",
+ assertRendering(
+ "{height=5}",
"
\n");
}
@Test
public void sourceSpans() {
- Parser parser = Parser.builder()
- .extensions(EXTENSIONS)
- .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
- .build();
-
- // This doesn't result in image attributes, so source spans should be for the single (merged) text node.
+ Parser parser =
+ Parser.builder()
+ .extensions(EXTENSIONS)
+ .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
+ .build();
+
+ // This doesn't result in image attributes, so source spans should be for the single
+ // (merged) text node.
Node document = parser.parse("x{height=3 width=4}\n");
Paragraph block = (Paragraph) document.getFirstChild();
Node text = block.getFirstChild();
diff --git a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/Ins.java b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/Ins.java
index 2ebd4f5ca..b6d7a2f2a 100644
--- a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/Ins.java
+++ b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/Ins.java
@@ -3,9 +3,7 @@
import org.commonmark.node.CustomNode;
import org.commonmark.node.Delimited;
-/**
- * An ins node containing text and other inline nodes as children.
- */
+/** An ins node containing text and other inline nodes as children. */
public class Ins extends CustomNode implements Delimited {
private static final String DELIMITER = "++";
diff --git a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/InsExtension.java b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/InsExtension.java
index 3d2974916..a39b77af8 100644
--- a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/InsExtension.java
+++ b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/InsExtension.java
@@ -1,5 +1,6 @@
package org.commonmark.ext.ins;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.ext.ins.internal.InsDelimiterProcessor;
import org.commonmark.ext.ins.internal.InsHtmlNodeRenderer;
@@ -13,23 +14,22 @@
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.commonmark.renderer.text.TextContentRenderer;
-import java.util.Set;
-
/**
* Extension for ins using ++
- *
- * Create it with {@link #create()} and then configure it on the builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
- *
- * The parsed ins text regions are turned into {@link Ins} nodes.
- *
+ *
+ *
Create it with {@link #create()} and then configure it on the builders ({@link
+ * org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
+ *
+ *
The parsed ins text regions are turned into {@link Ins} nodes.
*/
-public class InsExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension, TextContentRenderer.TextContentRendererExtension, MarkdownRenderer.MarkdownRendererExtension {
+public class InsExtension
+ implements Parser.ParserExtension,
+ HtmlRenderer.HtmlRendererExtension,
+ TextContentRenderer.TextContentRendererExtension,
+ MarkdownRenderer.MarkdownRendererExtension {
- private InsExtension() {
- }
+ private InsExtension() {}
public static Extension create() {
return new InsExtension();
@@ -52,18 +52,20 @@ public void extend(TextContentRenderer.Builder rendererBuilder) {
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
- @Override
- public NodeRenderer create(MarkdownNodeRendererContext context) {
- return new InsMarkdownNodeRenderer(context);
- }
+ rendererBuilder.nodeRendererFactory(
+ new MarkdownNodeRendererFactory() {
+ @Override
+ public NodeRenderer create(MarkdownNodeRendererContext context) {
+ return new InsMarkdownNodeRenderer(context);
+ }
- @Override
- public Set getSpecialCharacters() {
- // We technically don't need to escape single occurrences of +, but that's all the extension API
- // exposes currently.
- return Set.of('+');
- }
- });
+ @Override
+ public Set getSpecialCharacters() {
+ // We technically don't need to escape single occurrences of +, but that's
+ // all the extension API
+ // exposes currently.
+ return Set.of('+');
+ }
+ });
}
}
diff --git a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsDelimiterProcessor.java b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsDelimiterProcessor.java
index b0bfb4c6e..a742c70cf 100644
--- a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsDelimiterProcessor.java
+++ b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsDelimiterProcessor.java
@@ -28,7 +28,8 @@ public int getMinLength() {
@Override
public int process(DelimiterRun openingRun, DelimiterRun closingRun) {
if (openingRun.length() >= 2 && closingRun.length() >= 2) {
- // Use exactly two delimiters even if we have more, and don't care about internal openers/closers.
+ // Use exactly two delimiters even if we have more, and don't care about internal
+ // openers/closers.
Text opener = openingRun.getOpener();
diff --git a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsHtmlNodeRenderer.java b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsHtmlNodeRenderer.java
index dcd05fd59..d4defcbdc 100644
--- a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsHtmlNodeRenderer.java
+++ b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsHtmlNodeRenderer.java
@@ -1,11 +1,10 @@
package org.commonmark.ext.ins.internal;
+import java.util.Map;
import org.commonmark.node.Node;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;
-import java.util.Map;
-
public class InsHtmlNodeRenderer extends InsNodeRenderer {
private final HtmlNodeRendererContext context;
diff --git a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsNodeRenderer.java b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsNodeRenderer.java
index 31f0a64ec..4e8e0283e 100644
--- a/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsNodeRenderer.java
+++ b/commonmark-ext-ins/src/main/java/org/commonmark/ext/ins/internal/InsNodeRenderer.java
@@ -1,11 +1,10 @@
package org.commonmark.ext.ins.internal;
+import java.util.Set;
import org.commonmark.ext.ins.Ins;
import org.commonmark.node.Node;
import org.commonmark.renderer.NodeRenderer;
-import java.util.Set;
-
abstract class InsNodeRenderer implements NodeRenderer {
@Override
diff --git a/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsMarkdownRendererTest.java b/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsMarkdownRendererTest.java
index 6fc9ead67..023413121 100644
--- a/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsMarkdownRendererTest.java
+++ b/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsMarkdownRendererTest.java
@@ -1,19 +1,19 @@
package org.commonmark.ext.ins;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class InsMarkdownRendererTest {
private static final Set EXTENSIONS = Set.of(InsExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final MarkdownRenderer RENDERER = MarkdownRenderer.builder().extensions(EXTENSIONS).build();
+ private static final MarkdownRenderer RENDERER =
+ MarkdownRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void testStrikethrough() {
diff --git a/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsTest.java b/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsTest.java
index a5c91a395..8687d9a06 100644
--- a/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsTest.java
+++ b/commonmark-ext-ins/src/test/java/org/commonmark/ext/ins/InsTest.java
@@ -1,5 +1,9 @@
package org.commonmark.ext.ins;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.Node;
import org.commonmark.node.Paragraph;
@@ -11,18 +15,14 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class InsTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(InsExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
- private static final TextContentRenderer CONTENT_RENDERER = TextContentRenderer.builder()
- .extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final TextContentRenderer CONTENT_RENDERER =
+ TextContentRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void onePlusIsNotEnough() {
@@ -68,13 +68,15 @@ public void plusesInside() {
@Test
public void insWholeParagraphWithOtherDelimiters() {
- assertRendering("++Paragraph with *emphasis* and __strong emphasis__++",
+ assertRendering(
+ "++Paragraph with *emphasis* and __strong emphasis__++",
"
\n");
}
@@ -94,10 +96,11 @@ public void textContentRenderer() {
@Test
public void sourceSpans() {
- Parser parser = Parser.builder()
- .extensions(EXTENSIONS)
- .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
- .build();
+ Parser parser =
+ Parser.builder()
+ .extensions(EXTENSIONS)
+ .includeSourceSpans(IncludeSourceSpans.BLOCKS_AND_INLINES)
+ .build();
Node document = parser.parse("hey ++there++\n");
Paragraph block = (Paragraph) document.getFirstChild();
diff --git a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemMarker.java b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemMarker.java
index 9eca59bc9..4cfcb73eb 100644
--- a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemMarker.java
+++ b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemMarker.java
@@ -2,9 +2,7 @@
import org.commonmark.node.CustomNode;
-/**
- * A marker node indicating that a list item contains a task.
- */
+/** A marker node indicating that a list item contains a task. */
public class TaskListItemMarker extends CustomNode {
private final boolean checked;
diff --git a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemsExtension.java b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemsExtension.java
index 1c89256d3..abddc519a 100644
--- a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemsExtension.java
+++ b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/TaskListItemsExtension.java
@@ -14,19 +14,19 @@
/**
* Extension for adding task list items.
- *
- * Create it with {@link #create()} and then configure it on the builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
+ *
+ *
Create it with {@link #create()} and then configure it on the builders ({@link
+ * org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
*
* @since 0.15.0
*/
-public class TaskListItemsExtension implements Parser.ParserExtension, HtmlRenderer.HtmlRendererExtension,
- MarkdownRenderer.MarkdownRendererExtension {
+public class TaskListItemsExtension
+ implements Parser.ParserExtension,
+ HtmlRenderer.HtmlRendererExtension,
+ MarkdownRenderer.MarkdownRendererExtension {
- private TaskListItemsExtension() {
- }
+ private TaskListItemsExtension() {}
public static Extension create() {
return new TaskListItemsExtension();
@@ -44,16 +44,17 @@ public void extend(HtmlRenderer.Builder rendererBuilder) {
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
- @Override
- public NodeRenderer create(MarkdownNodeRendererContext context) {
- return new TaskListItemMarkdownNodeRenderer(context);
- }
-
- @Override
- public Set getSpecialCharacters() {
- return Set.of();
- }
- });
+ rendererBuilder.nodeRendererFactory(
+ new MarkdownNodeRendererFactory() {
+ @Override
+ public NodeRenderer create(MarkdownNodeRendererContext context) {
+ return new TaskListItemMarkdownNodeRenderer(context);
+ }
+
+ @Override
+ public Set getSpecialCharacters() {
+ return Set.of();
+ }
+ });
}
}
diff --git a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemHtmlNodeRenderer.java b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemHtmlNodeRenderer.java
index a27b125c8..cb1c275b4 100644
--- a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemHtmlNodeRenderer.java
+++ b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemHtmlNodeRenderer.java
@@ -1,13 +1,12 @@
package org.commonmark.ext.task.list.items.internal;
+import java.util.LinkedHashMap;
+import java.util.Map;
import org.commonmark.ext.task.list.items.TaskListItemMarker;
import org.commonmark.node.Node;
import org.commonmark.renderer.html.HtmlNodeRendererContext;
import org.commonmark.renderer.html.HtmlWriter;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
public class TaskListItemHtmlNodeRenderer extends TaskListItemNodeRenderer {
private final HtmlNodeRendererContext context;
diff --git a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemPostProcessor.java b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemPostProcessor.java
index b95c2e30d..2898a8229 100644
--- a/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemPostProcessor.java
+++ b/commonmark-ext-task-list-items/src/main/java/org/commonmark/ext/task/list/items/internal/TaskListItemPostProcessor.java
@@ -1,12 +1,11 @@
package org.commonmark.ext.task.list.items.internal;
-import org.commonmark.ext.task.list.items.TaskListItemMarker;
-import org.commonmark.node.*;
-import org.commonmark.parser.PostProcessor;
-
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.commonmark.ext.task.list.items.TaskListItemMarker;
+import org.commonmark.node.*;
+import org.commonmark.parser.PostProcessor;
public class TaskListItemPostProcessor implements PostProcessor {
@@ -31,14 +30,16 @@ public void visit(ListItem listItem) {
Matcher matcher = REGEX_TASK_LIST_ITEM.matcher(textNode.getLiteral());
if (matcher.matches()) {
String checked = matcher.group(1);
- boolean isChecked = Objects.equals(checked, "X") || Objects.equals(checked, "x");
+ boolean isChecked =
+ Objects.equals(checked, "X") || Objects.equals(checked, "x");
// Add the task list item marker node as the first child of the list item.
listItem.prependChild(new TaskListItemMarker(isChecked));
- // Parse the node using the input after the task marker (in other words, group 2 from the matcher).
- // (Note that the String has been trimmed, so we should add a space between the
- // TaskListItemMarker and the text that follows it when we come to render it).
+ // Parse the node using the input after the task marker (in other words,
+ // group 2 from the matcher). (Note that the String has been trimmed, so we
+ // should add a space between the TaskListItemMarker and the text that
+ // follows it when we come to render it).
textNode.setLiteral(matcher.group(2));
}
}
diff --git a/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemMarkdownRendererTest.java b/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemMarkdownRendererTest.java
index cf73f434c..e67768f16 100644
--- a/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemMarkdownRendererTest.java
+++ b/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemMarkdownRendererTest.java
@@ -1,5 +1,7 @@
package org.commonmark.ext.task.list.items;
+import static org.assertj.core.api.Assertions.assertThat;
+
import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.BulletList;
@@ -12,13 +14,12 @@
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.junit.jupiter.api.Test;
-import static org.assertj.core.api.Assertions.assertThat;
-
public class TaskListItemMarkdownRendererTest {
private static final Set EXTENSIONS = Set.of(TaskListItemsExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final MarkdownRenderer RENDERER = MarkdownRenderer.builder().extensions(EXTENSIONS).build();
+ private static final MarkdownRenderer RENDERER =
+ MarkdownRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void testCheckedRoundTrip() {
diff --git a/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemsTest.java b/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemsTest.java
index 0adc615a7..dd9290b6e 100644
--- a/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemsTest.java
+++ b/commonmark-ext-task-list-items/src/test/java/org/commonmark/ext/task/list/items/TaskListItemsTest.java
@@ -1,87 +1,116 @@
package org.commonmark.ext.task.list.items;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.Set;
-
public class TaskListItemsTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(TaskListItemsExtension.create());
- private static final String HTML_CHECKED = "";
+ private static final String HTML_CHECKED =
+ "";
private static final String HTML_UNCHECKED = "";
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void baseCase() {
- assertRendering("- [x] this is *done*\n", "
\n
" + HTML_CHECKED + " this is done
\n
\n");
+ assertRendering(
+ "- [x] this is *done*\n",
+ "
- * Create it with {@link #create()} and then configure it on the builders
- * ({@link org.commonmark.parser.Parser.Builder#extensions(Iterable)},
- * {@link HtmlRenderer.Builder#extensions(Iterable)}).
- *
- *
- * The parsed metadata is turned into {@link YamlFrontMatterNode}. You can access the metadata using {@link YamlFrontMatterVisitor}.
- *
+ *
+ *
Create it with {@link #create()} and then configure it on the builders ({@link
+ * org.commonmark.parser.Parser.Builder#extensions(Iterable)}, {@link
+ * HtmlRenderer.Builder#extensions(Iterable)}).
+ *
+ *
The parsed metadata is turned into {@link YamlFrontMatterNode}. You can access the metadata
+ * using {@link YamlFrontMatterVisitor}.
*/
-public class YamlFrontMatterExtension implements Parser.ParserExtension, MarkdownRenderer.MarkdownRendererExtension {
+public class YamlFrontMatterExtension
+ implements Parser.ParserExtension, MarkdownRenderer.MarkdownRendererExtension {
- private YamlFrontMatterExtension() {
- }
+ private YamlFrontMatterExtension() {}
@Override
public void extend(Parser.Builder parserBuilder) {
@@ -38,16 +37,17 @@ public static Extension create() {
@Override
public void extend(MarkdownRenderer.Builder rendererBuilder) {
- rendererBuilder.nodeRendererFactory(new MarkdownNodeRendererFactory() {
- @Override
- public NodeRenderer create(MarkdownNodeRendererContext context) {
- return new YamlFrontMatterMarkdownNodeRenderer(context);
- }
+ rendererBuilder.nodeRendererFactory(
+ new MarkdownNodeRendererFactory() {
+ @Override
+ public NodeRenderer create(MarkdownNodeRendererContext context) {
+ return new YamlFrontMatterMarkdownNodeRenderer(context);
+ }
- @Override
- public Set getSpecialCharacters() {
- return Set.of();
- }
- });
+ @Override
+ public Set getSpecialCharacters() {
+ return Set.of();
+ }
+ });
}
}
diff --git a/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterNode.java b/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterNode.java
index 20eb3baf7..e5fe473ad 100644
--- a/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterNode.java
+++ b/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterNode.java
@@ -1,8 +1,7 @@
package org.commonmark.ext.front.matter;
-import org.commonmark.node.CustomNode;
-
import java.util.List;
+import org.commonmark.node.CustomNode;
public class YamlFrontMatterNode extends CustomNode {
private String key;
diff --git a/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterVisitor.java b/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterVisitor.java
index 1c23966f5..e49e22c0d 100644
--- a/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterVisitor.java
+++ b/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/YamlFrontMatterVisitor.java
@@ -1,11 +1,10 @@
package org.commonmark.ext.front.matter;
-import org.commonmark.node.AbstractVisitor;
-import org.commonmark.node.CustomNode;
-
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import org.commonmark.node.AbstractVisitor;
+import org.commonmark.node.CustomNode;
public class YamlFrontMatterVisitor extends AbstractVisitor {
private Map> data;
@@ -17,7 +16,9 @@ public YamlFrontMatterVisitor() {
@Override
public void visit(CustomNode customNode) {
if (customNode instanceof YamlFrontMatterNode) {
- data.put(((YamlFrontMatterNode) customNode).getKey(), ((YamlFrontMatterNode) customNode).getValues());
+ data.put(
+ ((YamlFrontMatterNode) customNode).getKey(),
+ ((YamlFrontMatterNode) customNode).getValues());
} else {
super.visit(customNode);
}
diff --git a/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/internal/YamlFrontMatterBlockParser.java b/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/internal/YamlFrontMatterBlockParser.java
index f7f03c001..7d14b403b 100644
--- a/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/internal/YamlFrontMatterBlockParser.java
+++ b/commonmark-ext-yaml-front-matter/src/main/java/org/commonmark/ext/front/matter/internal/YamlFrontMatterBlockParser.java
@@ -1,18 +1,18 @@
package org.commonmark.ext.front.matter.internal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.commonmark.ext.front.matter.YamlFrontMatterBlock;
import org.commonmark.ext.front.matter.YamlFrontMatterNode;
import org.commonmark.node.Block;
import org.commonmark.node.Document;
import org.commonmark.parser.block.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
public class YamlFrontMatterBlockParser extends AbstractBlockParser {
- private static final Pattern REGEX_METADATA = Pattern.compile("^[ ]{0,3}([A-Za-z0-9._-]+):\\s*(.*)");
+ private static final Pattern REGEX_METADATA =
+ Pattern.compile("^[ ]{0,3}([A-Za-z0-9._-]+):\\s*(.*)");
private static final Pattern REGEX_METADATA_LIST = Pattern.compile("^[ ]+-\\s*(.*)");
private static final Pattern REGEX_METADATA_LITERAL = Pattern.compile("^\\s*(.*)");
private static final Pattern REGEX_BEGIN = Pattern.compile("^-{3}(\\s.*)?");
@@ -95,9 +95,7 @@ private static String parseString(String s) {
} else if (s.startsWith("\"") && s.endsWith("\"")) {
String inner = s.substring(1, s.length() - 1);
// Only support escaped `\` and `"`, nothing else.
- return inner
- .replace("\\\"", "\"")
- .replace("\\\\", "\\");
+ return inner.replace("\\\"", "\"").replace("\\\\", "\\");
} else {
return s;
}
@@ -109,9 +107,11 @@ public BlockStart tryStart(ParserState state, MatchedBlockParser matchedBlockPar
CharSequence line = state.getLine().getContent();
BlockParser parentParser = matchedBlockParser.getMatchedBlockParser();
// check whether this line is the first line of whole document or not
- if (parentParser.getBlock() instanceof Document && parentParser.getBlock().getFirstChild() == null &&
- REGEX_BEGIN.matcher(line).matches()) {
- return BlockStart.of(new YamlFrontMatterBlockParser()).atIndex(state.getNextNonSpaceIndex());
+ if (parentParser.getBlock() instanceof Document
+ && parentParser.getBlock().getFirstChild() == null
+ && REGEX_BEGIN.matcher(line).matches()) {
+ return BlockStart.of(new YamlFrontMatterBlockParser())
+ .atIndex(state.getNextNonSpaceIndex());
}
return BlockStart.none();
diff --git a/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterMarkdownRendererTest.java b/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterMarkdownRendererTest.java
index 987513ea4..b5bd06058 100644
--- a/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterMarkdownRendererTest.java
+++ b/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterMarkdownRendererTest.java
@@ -1,5 +1,8 @@
package org.commonmark.ext.front.matter;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
import org.commonmark.Extension;
import org.commonmark.node.Document;
import org.commonmark.node.Node;
@@ -9,15 +12,12 @@
import org.commonmark.renderer.markdown.MarkdownRenderer;
import org.junit.jupiter.api.Test;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class YamlFrontMatterMarkdownRendererTest {
private static final List EXTENSIONS = List.of(YamlFrontMatterExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final MarkdownRenderer RENDERER = MarkdownRenderer.builder().extensions(EXTENSIONS).build();
+ private static final MarkdownRenderer RENDERER =
+ MarkdownRenderer.builder().extensions(EXTENSIONS).build();
// ===== Round-trip tests (parse string -> render -> compare to input) =====
@@ -43,7 +43,8 @@ public void testRoundTripListValues() {
@Test
public void testRoundTripLiteralBlock() {
- assertRoundTrip("---\ndescription: |\n first line\n second line\n---\n\nMarkdown content\n");
+ assertRoundTrip(
+ "---\ndescription: |\n first line\n second line\n---\n\nMarkdown content\n");
}
@Test
@@ -84,7 +85,9 @@ public void testRoundTripEmptyFrontmatter() {
@Test
public void testProgrammaticallyBuilt() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("title", List.of("My Document"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("title", List.of("My Document"))));
assertRenderedEquals(doc, "---\ntitle: My Document\n---\n\nMarkdown content\n");
}
@@ -93,29 +96,40 @@ public void testProgrammaticallyBuilt() {
@Test
public void testValueWithColonSpace() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("value with a: colon inside"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(
+ new YamlFrontMatterNode(
+ "key", List.of("value with a: colon inside"))));
- assertRenderedEquals(doc, "---\nkey: 'value with a: colon inside'\n---\n\nMarkdown content\n");
+ assertRenderedEquals(
+ doc, "---\nkey: 'value with a: colon inside'\n---\n\nMarkdown content\n");
}
@Test
public void testValueWithColonNoSpace() {
// Colon without trailing space is fine unquoted (e.g. timestamps, URLs)
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("time", List.of("12:30:00"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("time", List.of("12:30:00"))));
assertRenderedEquals(doc, "---\ntime: 12:30:00\n---\n\nMarkdown content\n");
}
@Test
public void testValueStartingWithDash() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("- not a list"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("key", List.of("- not a list"))));
assertRenderedEquals(doc, "---\nkey: '- not a list'\n---\n\nMarkdown content\n");
}
@Test
public void testValueStartingWithUnmatchedBracket() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("[broken"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("key", List.of("[broken"))));
assertRenderedEquals(doc, "---\nkey: '[broken'\n---\n\nMarkdown content\n");
}
@@ -123,14 +137,18 @@ public void testValueStartingWithUnmatchedBracket() {
@Test
public void testValueStartingWithMatchedBrackets() {
// Valid flow list - should NOT be quoted
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("flowList", List.of("[1, 2, 3]"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("flowList", List.of("[1, 2, 3]"))));
assertRenderedEquals(doc, "---\nflowList: [1, 2, 3]\n---\n\nMarkdown content\n");
}
@Test
public void testValueStartingWithUnmatchedBrace() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("{broken"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("key", List.of("{broken"))));
assertRenderedEquals(doc, "---\nkey: '{broken'\n---\n\nMarkdown content\n");
}
@@ -138,35 +156,47 @@ public void testValueStartingWithUnmatchedBrace() {
@Test
public void testValueStartingWithMatchedBraces() {
// Valid flow mapping - should NOT be quoted
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("flowMapping", List.of("{key: val}"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("flowMapping", List.of("{key: val}"))));
assertRenderedEquals(doc, "---\nflowMapping: {key: val}\n---\n\nMarkdown content\n");
}
@Test
public void testValueContainingHashComment() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("value # not a comment"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("key", List.of("value # not a comment"))));
assertRenderedEquals(doc, "---\nkey: 'value # not a comment'\n---\n\nMarkdown content\n");
}
@Test
public void testValueContainingApostrophe() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("it's a test"))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("key", List.of("it's a test"))));
assertRenderedEquals(doc, "---\nkey: 'it''s a test'\n---\n\nMarkdown content\n");
}
@Test
public void testEmptyStringValue() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("empty", List.of(""))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(new YamlFrontMatterNode("empty", List.of(""))));
assertRenderedEquals(doc, "---\nempty: ''\n---\n\nMarkdown content\n");
}
@Test
public void testValueStartingWithDoubleQuote() {
- var doc = buildDocumentWithFrontMatter(List.of(new YamlFrontMatterNode("key", List.of("\"quotes within value\""))));
+ var doc =
+ buildDocumentWithFrontMatter(
+ List.of(
+ new YamlFrontMatterNode(
+ "key", List.of("\"quotes within value\""))));
assertRenderedEquals(doc, "---\nkey: '\"quotes within value\"'\n---\n\nMarkdown content\n");
}
diff --git a/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterTest.java b/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterTest.java
index e0555dc0a..71da8a936 100644
--- a/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterTest.java
+++ b/commonmark-ext-yaml-front-matter/src/test/java/org/commonmark/ext/front/matter/YamlFrontMatterTest.java
@@ -1,5 +1,10 @@
package org.commonmark.ext.front.matter;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.commonmark.Extension;
import org.commonmark.node.CustomNode;
import org.commonmark.node.Node;
@@ -8,24 +13,15 @@
import org.commonmark.testutil.RenderingTestCase;
import org.junit.jupiter.api.Test;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
public class YamlFrontMatterTest extends RenderingTestCase {
private static final Set EXTENSIONS = Set.of(YamlFrontMatterExtension.create());
private static final Parser PARSER = Parser.builder().extensions(EXTENSIONS).build();
- private static final HtmlRenderer RENDERER = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ private static final HtmlRenderer RENDERER =
+ HtmlRenderer.builder().extensions(EXTENSIONS).build();
@Test
public void simpleValue() {
- final String input = "---" +
- "\nhello: world" +
- "\n..." +
- "\n" +
- "\ngreat";
+ final String input = "---" + "\nhello: world" + "\n..." + "\n" + "\ngreat";
final String rendered = "
great
\n";
Map> data = getFrontMatter(input);
@@ -40,11 +36,7 @@ public void simpleValue() {
@Test
public void emptyValue() {
- final String input = "---" +
- "\nkey:" +
- "\n---" +
- "\n" +
- "\ngreat";
+ final String input = "---" + "\nkey:" + "\n---" + "\n" + "\ngreat";
final String rendered = "