在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):commonmark/commonmark-java开源软件地址(OpenSource Url):https://github.com/commonmark/commonmark-java开源编程语言(OpenSource Language):Java 99.8%开源软件介绍(OpenSource Introduction):commonmark-javaJava library for parsing and rendering Markdown text according to the CommonMark specification (and some extensions). IntroductionProvides classes for parsing input to an abstract syntax tree of nodes (AST), visiting and manipulating nodes, and rendering to HTML. It started out as a port of commonmark.js, but has since evolved into a full library with a nice API and the following features:
The library is supported on Java 8 or later. It should work on Java 7 and Android too, but that is on a best-effort basis, please report problems. For Android the minimum API level is 19, see the commonmark-android-test directory. Coordinates for core library (see all on Maven Central): <dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark</artifactId>
<version>0.18.1</version>
</dependency> The module names to use in Java 9 are Note that for 0.x releases of this library, the API is not considered stable yet and may break between minor releases. After 1.0, Semantic Versioning will be followed. See the spec.txt file if you're wondering which version of the spec is currently implemented. Also check out the CommonMark dingus for getting familiar with the syntax or trying out edge cases. UsageParse and render to HTMLimport org.commonmark.node.*;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
Parser parser = Parser.builder().build();
Node document = parser.parse("This is *Sparta*");
HtmlRenderer renderer = HtmlRenderer.builder().build();
renderer.render(document); // "<p>This is <em>Sparta</em></p>\n" This uses the parser and renderer with default options. Both builders have methods for configuring their behavior:
Note that this library doesn't try to sanitize the resulting HTML with regards to which tags are allowed, etc. That is the responsibility of the caller, and if you expose the resulting HTML, you probably want to run a sanitizer on it after this. For rendering to plain text, there's also a Use a visitor to process parsed nodesAfter the source text has been parsed, the result is a tree of nodes. That tree can be modified before rendering, or just inspected without rendering: Node node = parser.parse("Example\n=======\n\nSome more text");
WordCountVisitor visitor = new WordCountVisitor();
node.accept(visitor);
visitor.wordCount; // 4
class WordCountVisitor extends AbstractVisitor {
int wordCount = 0;
@Override
public void visit(Text text) {
// This is called for all Text nodes. Override other visit methods for other node types.
// Count words (this is just an example, don't actually do it this way for various reasons).
wordCount += text.getLiteral().split("\\W+").length;
// Descend into children (could be omitted in this case because Text nodes don't have children).
visitChildren(text);
}
} Add or change attributes of HTML elementsSometimes you might want to customize how HTML is rendered. If all you want to do is add or change attributes on some elements, there's a simple way to do that. In this example, we register a factory for an Parser parser = Parser.builder().build();
HtmlRenderer renderer = HtmlRenderer.builder()
.attributeProviderFactory(new AttributeProviderFactory() {
public AttributeProvider create(AttributeProviderContext context) {
return new ImageAttributeProvider();
}
})
.build();
Node document = parser.parse("![text](/url.png)");
renderer.render(document);
// "<p><img src=\"/url.png\" alt=\"text\" class=\"border\" /></p>\n"
class ImageAttributeProvider implements AttributeProvider {
@Override
public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
if (node instanceof Image) {
attributes.put("class", "border");
}
}
} Customize HTML renderingIf you want to do more than just change attributes, there's also a way to take complete control over how HTML is rendered. In this example, we're changing the rendering of indented code blocks to
only wrap them in Parser parser = Parser.builder().build();
HtmlRenderer renderer = HtmlRenderer.builder()
.nodeRendererFactory(new HtmlNodeRendererFactory() {
public NodeRenderer create(HtmlNodeRendererContext context) {
return new IndentedCodeBlockNodeRenderer(context);
}
})
.build();
Node document = parser.parse("Example:\n\n code");
renderer.render(document);
// "<p>Example:</p>\n<pre>code\n</pre>\n"
class IndentedCodeBlockNodeRenderer implements NodeRenderer {
private final HtmlWriter html;
IndentedCodeBlockNodeRenderer(HtmlNodeRendererContext context) {
this.html = context.getWriter();
}
@Override
public Set<Class<? extends Node>> getNodeTypes() {
// Return the node types we want to use this renderer for.
return Collections.<Class<? extends Node>>singleton(IndentedCodeBlock.class);
}
@Override
public void render(Node node) {
// We only handle one type as per getNodeTypes, so we can just cast it here.
IndentedCodeBlock codeBlock = (IndentedCodeBlock) node;
html.line();
html.tag("pre");
html.text(codeBlock.getLiteral());
html.tag("/pre");
html.line();
}
} Add your own node typesIn case you want to store additional data in the document or have custom
elements in the resulting HTML, you can create your own subclass of
To define the HTML rendering for them, you can use a Thread-safetyBoth the Having said that, there might be bugs of course. If you find one, please report an issue. API documentationJavadocs are available online on javadoc.io. ExtensionsExtensions need to extend the parser, or the HTML renderer, or both. To use an extension, the builder objects can be configured with a list of extensions. Because extensions are optional, they live in separate artifacts, so additional dependencies need to be added as well. Let's look at how to enable tables from GitHub Flavored Markdown. First, add an additional dependency (see Maven Central for others): <dependency>
<groupId>org.commonmark</groupId>
<artifactId>commonmark-ext-gfm-tables</artifactId>
<version>0.18.1</version>
</dependency> Then, configure the extension on the builders: import org.commonmark.ext.gfm.tables.TablesExtension;
List<Extension> extensions = Arrays.asList(TablesExtension.create());
Parser parser = Parser.builder()
.extensions(extensions)
.build();
HtmlRenderer renderer = HtmlRenderer.builder()
.extensions(extensions)
.build(); To configure another extension in the above example, just add it to the list. The following extensions are developed with this library, each in their own artifact. AutolinkTurns plain links such as URLs and email addresses into links (based on autolink-java). Use class StrikethroughEnables strikethrough of text by enclosing it in Use class TablesEnables tables using pipes as in GitHub Flavored Markdown. Use class Heading anchorEnables adding auto generated "id" attributes to heading tags. The "id" is based on the text of the heading.
Use class In case you want custom rendering of the heading instead, you can use
the InsEnables underlining of text by enclosing it in Use class YAML front matterAdds support for metadata through a YAML front matter block. This extension only supports a subset of YAML syntax. Here's an example of what's supported:
Use class Image AttributesAdds support for specifying attributes (specifically height and width) for images. The attribute elements are given as
will be rendered as:
Use class Note: since this extension uses curly braces Task List ItemsAdds support for tasks as list items. A task can be represented as a list item where the first non-whitespace character is a left bracket For example:
will be rendered as:
Use class Third-party extensionsYou can also find other extensions in the wild:
See also
ContributingSee CONTRIBUTING.md file. LicenseCopyright (c) 2015-2019 Atlassian and others. BSD (2-clause) licensed, see LICENSE.txt file. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论