org.commonmark.node.Node Java Examples

The following examples show how to use org.commonmark.node.Node. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MarkdownUtil.java    From Roothub with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * 渲染 Markdown
 * @param content
 * @return
 */
public static String render(String content) {
    List<Extension> extensions = Arrays.asList(
            AutolinkExtension.create(),
            TablesExtension.create());

    Parser parser = Parser.builder()
            .extensions(extensions)
            .build();
    // 回车一次就可以实现换行
    HtmlRenderer renderer = HtmlRenderer.builder()
            .softbreak("<br/>")
            .attributeProviderFactory(context -> new MyAttributeProvider())
            .extensions(extensions)
            .build();
    Node document = parser.parse(content == null ? "" : content);
    return renderer.render(document);
}
 
Example #2
Source File: YamlFrontMatterTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void literalValue1() {
    final String input = "---" +
            "\nliteral: |" +
            "\n  hello markdown!" +
            "\n  literal thing..." +
            "\n---" +
            "\n" +
            "\ngreat";
    final String rendered = "<p>great</p>\n";

    YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor();
    Node document = PARSER.parse(input);
    document.accept(visitor);

    Map<String, List<String>> data = visitor.getData();

    assertEquals(1, data.size());
    assertTrue(data.containsKey("literal"));
    assertEquals(1, data.get("literal").size());
    assertEquals("hello markdown!\nliteral thing...", data.get("literal").get(0));

    assertRendering(input, rendered);
}
 
Example #3
Source File: NewLineInlineProcessor.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Override
protected Node parse() {
    index++; // assume we're at a \n

    final Node previous = block.getLastChild();

    // Check previous text for trailing spaces.
    // The "endsWith" is an optimization to avoid an RE match in the common case.
    if (previous instanceof Text && ((Text) previous).getLiteral().endsWith(" ")) {
        Text text = (Text) previous;
        String literal = text.getLiteral();
        Matcher matcher = FINAL_SPACE.matcher(literal);
        int spaces = matcher.find() ? matcher.end() - matcher.start() : 0;
        if (spaces > 0) {
            text.setLiteral(literal.substring(0, literal.length() - spaces));
        }
        if (spaces >= 2) {
            return new HardLineBreak();
        } else {
            return new SoftLineBreak();
        }
    } else {
        return new SoftLineBreak();
    }
}
 
Example #4
Source File: MarkwonBuilderImplTest.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Test
public void plugin_configured() {
    // verify that all configuration methods (applicable) are called

    final MarkwonPlugin plugin = mock(MarkwonPlugin.class);

    final MarkwonBuilderImpl impl = new MarkwonBuilderImpl(RuntimeEnvironment.application);
    impl.usePlugin(plugin).build();

    verify(plugin, times(1)).configure(any(MarkwonPlugin.Registry.class));

    verify(plugin, times(1)).configureParser(any(Parser.Builder.class));
    verify(plugin, times(1)).configureTheme(any(MarkwonTheme.Builder.class));
    verify(plugin, times(1)).configureConfiguration(any(MarkwonConfiguration.Builder.class));
    verify(plugin, times(1)).configureVisitor(any(MarkwonVisitor.Builder.class));
    verify(plugin, times(1)).configureSpansFactory(any(MarkwonSpansFactory.Builder.class));

    // note, no render props -> they must be configured on render stage
    verify(plugin, times(0)).processMarkdown(anyString());
    verify(plugin, times(0)).beforeRender(any(Node.class));
    verify(plugin, times(0)).afterRender(any(Node.class), any(MarkwonVisitor.class));
    verify(plugin, times(0)).beforeSetText(any(TextView.class), any(Spanned.class));
    verify(plugin, times(0)).afterSetText(any(TextView.class));
}
 
Example #5
Source File: MarkwonVisitorImplTest.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Test
public void clear() {
    // clear method will clear renderProps and spannableBuilder

    final RenderProps renderProps = mock(RenderProps.class);
    final SpannableBuilder spannableBuilder = mock(SpannableBuilder.class);

    final MarkwonVisitorImpl impl = new MarkwonVisitorImpl(
            mock(MarkwonConfiguration.class),
            renderProps,
            spannableBuilder,
            Collections.<Class<? extends Node>, MarkwonVisitor.NodeVisitor<? extends Node>>emptyMap(),
            mock(MarkwonVisitor.BlockHandler.class));

    impl.clear();

    verify(renderProps, times(1)).clearAll();
    verify(spannableBuilder, times(1)).clear();
}
 
Example #6
Source File: CommonmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void printAttribute(StringBuilder buf, String name, String value) {
	if (value == null)
		return;

	int fromIndex = buf.length();
	if (value.length() > 30) {
		// limit to 30 characters
		com.vladsch.flexmark.ast.Node.segmentSpanChars(buf, 0, 1, name,
			value.substring(0, 30), "...", "");
	} else
		com.vladsch.flexmark.ast.Node.segmentSpanChars(buf, 0, 1, name, value);

	// change 'name:[0, 1, value]' to 'name=value'
	String posStr = "[0, 1, ";
	int posIndex = buf.indexOf(posStr, fromIndex);
	if (posIndex >= 0) {
		buf.delete(posIndex, posIndex + posStr.length());
		buf.setCharAt(posIndex - 1, '=');
		buf.setLength(buf.length() - 1);
	}
}
 
Example #7
Source File: MockBodyPost.java    From Natty with GNU General Public License v3.0 6 votes vote down vote up
public MockBodyPost(String bodyMarkdown) {

        super("","",null,null,
                1, 1, "", bodyMarkdown, null, null, null, "", "");
        SOUser asker = new SOUser("testUser",-1,1,"registered");
        SOUser answerer = new SOUser("testUser",-1,1,"unregistered");

        setAnswerCreationDate(Instant.now());
        setQuestionCreationDate(Instant.EPOCH);
        setAsker(asker);
        setAnswerer(answerer);

        Parser parser = Parser.builder().build();
        Node document = parser.parse(bodyMarkdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        setBody(renderer.render(document));

    }
 
Example #8
Source File: DocMaker.java    From jeka with Apache License 2.0 6 votes vote down vote up
private void addMenu(Node document, List<MenuItem> menuItems) {
    final List<MenuItem> reversedItems = new LinkedList<>(menuItems);
    Collections.reverse(reversedItems);
    for (final MenuItem menuItem : reversedItems) {
        if (menuItem.level > 5) {
            continue;
        }
        final Link link = new Link();
        link.setTitle(menuItem.title);
        final Text text = new Text();
        text.setLiteral( menuItem.title);
        link.appendChild(text);
        link.setDestination("#" + menuItem.anchorId);
        final HtmlInline indent = new HtmlInline();
        final String cssClass = "menuItem" + menuItem.level;
        indent.setLiteral("<a href=\"#" + menuItem.anchorId + "\" class=\"" + cssClass + "\">" + menuItem.title + "</a>");
        document.prependChild(indent);
        document.prependChild(new HardLineBreak());
    }
}
 
Example #9
Source File: MarkdownUtil.java    From ml-blog with MIT License 6 votes vote down vote up
@Override
public void render(Node node) {

    HtmlWriter html = context.getWriter();
    FencedCodeBlock codeBlock = (FencedCodeBlock) node;
    Map<String,String> attrs = new HashMap<>();
    if (!StringUtils.isEmpty(codeBlock.getInfo())) {
        attrs.put("class","language-" + codeBlock.getInfo());
    }
    html.line();
    html.tag("pre");
    html.tag("code",attrs);
    html.tag("ol");
    String data = codeBlock.getLiteral();
    String[] split = data.split("\n");
    for (String s : split) {
        html.tag("li");
        html.text(s + "\n");
        html.tag("/li");
    }
    html.tag("/ol");
    html.tag("/code");
    html.tag("/pre");
    html.line();

}
 
Example #10
Source File: MarkwonSpansFactoryImpl.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public <N extends Node> Builder appendFactory(@NonNull Class<N> node, @NonNull SpanFactory factory) {
    final SpanFactory existing = factories.get(node);
    if (existing == null) {
        factories.put(node, factory);
    } else {
        if (existing instanceof CompositeSpanFactory) {
            ((CompositeSpanFactory) existing).factories.add(0, factory);
        } else {
            final CompositeSpanFactory compositeSpanFactory =
                    new CompositeSpanFactory(factory, existing);
            factories.put(node, compositeSpanFactory);
        }
    }
    return this;
}
 
Example #11
Source File: TableOfContentsPlugin.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeRender(@NonNull Node node) {

    // custom block to hold TOC
    final TableOfContentsBlock block = new TableOfContentsBlock();

    // create TOC title
    {
        final Text text = new Text("Table of contents");
        final Heading heading = new Heading();
        // important one - set TOC heading level
        heading.setLevel(1);
        heading.appendChild(text);
        block.appendChild(heading);
    }

    final HeadingVisitor visitor = new HeadingVisitor(block);
    node.accept(visitor);

    // make it the very first node in rendered markdown
    node.prependChild(block);
}
 
Example #12
Source File: MarkDownProvider.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
protected static void render(@NonNull TextView textView, String markdown, int width) {
    List<Extension> extensions = Arrays.asList(
            StrikethroughExtension.create(),
            AutolinkExtension.create(),
            TablesExtension.create(),
            InsExtension.create(),
            EmojiExtension.create(),
            MentionExtension.create(),
            YamlFrontMatterExtension.create());
    Parser parser = Parser.builder()
            .extensions(extensions)
            .build();
    try {
        Node node = parser.parse(markdown);
        String rendered = HtmlRenderer
                .builder()
                .extensions(extensions)
                .build()
                .render(node);
        HtmlHelper.htmlIntoTextView(textView, rendered, (width - (textView.getPaddingStart() + textView.getPaddingEnd())));
    } catch (Exception ignored) {
        HtmlHelper.htmlIntoTextView(textView, markdown, (width - (textView.getPaddingStart() + textView.getPaddingEnd())));
    }
}
 
Example #13
Source File: MarkwonSpansFactoryImpl.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public <N extends Node> Builder prependFactory(@NonNull Class<N> node, @NonNull SpanFactory factory) {
    // if there is no factory registered for this node -> just add it
    final SpanFactory existing = factories.get(node);
    if (existing == null) {
        factories.put(node, factory);
    } else {
        // existing span factory can be of CompositeSpanFactory at this point -> append to it
        if (existing instanceof CompositeSpanFactory) {
            ((CompositeSpanFactory) existing).factories.add(factory);
        } else {
            // if it's not composite at this point -> make it
            final CompositeSpanFactory compositeSpanFactory =
                    new CompositeSpanFactory(existing, factory);
            factories.put(node, compositeSpanFactory);
        }
    }
    return this;
}
 
Example #14
Source File: YamlFrontMatterTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void literalValue2() {
    final String input = "---" +
            "\nliteral: |" +
            "\n  - hello markdown!" +
            "\n---" +
            "\n" +
            "\ngreat";
    final String rendered = "<p>great</p>\n";

    YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor();
    Node document = PARSER.parse(input);
    document.accept(visitor);

    Map<String, List<String>> data = visitor.getData();

    assertEquals(1, data.size());
    assertTrue(data.containsKey("literal"));
    assertEquals(1, data.get("literal").size());
    assertEquals("- hello markdown!", data.get("literal").get(0));

    assertRendering(input, rendered);
}
 
Example #15
Source File: DocMaker.java    From jeka with Apache License 2.0 5 votes vote down vote up
private List<MenuItem> addAnchorAndNumberingToHeaders(Node node) {
    final List<MenuItem> menuItems = new LinkedList<>();
    final int[] counters = new int[10];
    node.accept(new AbstractVisitor() {

        @Override
        public void visit(Heading heading) {
            final Text text = (Text) heading.getFirstChild();
            final String content = text.getLiteral();
            final boolean intro = "Introduction".equals(content);  // Do not number Introduction
            if (!intro) {
                counters[heading.getLevel()]++;
                for (int i = heading.getLevel() + 1; i < 6; i++) {
                    counters[i] = 0;
                }
            }
            final StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= heading.getLevel(); i++) {
                sb.append(counters[i]).append(".");
            }
            if (sb.length() > 1 && heading.getLevel() > 1) {
                sb.delete(sb.length() - 1, sb.length() );
            }
            final String anchorId = content.replace(" ", "");
            final HtmlInline htmlInline = new HtmlInline();
            htmlInline.setLiteral("<a name=\"" + anchorId + "\"></a>");
            heading.insertBefore(htmlInline);
            final MenuItem menuItem = new MenuItem(content, anchorId, heading.getLevel());
            menuItems.add(menuItem);
        }
    });
    return menuItems;
}
 
Example #16
Source File: MarkwonVisitorImpl.java    From Markwon with Apache License 2.0 5 votes vote down vote up
MarkwonVisitorImpl(
        @NonNull MarkwonConfiguration configuration,
        @NonNull RenderProps renderProps,
        @NonNull SpannableBuilder builder,
        @NonNull Map<Class<? extends Node>, NodeVisitor<? extends Node>> nodes,
        @NonNull BlockHandler blockHandler) {
    this.configuration = configuration;
    this.renderProps = renderProps;
    this.builder = builder;
    this.nodes = nodes;
    this.blockHandler = blockHandler;
}
 
Example #17
Source File: MarkwonSpansFactoryImplTest.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Test
public void get_class() {

    // register one TextNode
    final MarkwonSpansFactoryImpl impl = new MarkwonSpansFactoryImpl(
            Collections.<Class<? extends Node>, SpanFactory>singletonMap(Text.class, mock(SpanFactory.class)));

    // text must be present
    assertNotNull(impl.get(Text.class));

    // we haven't registered ListItem, so null here
    assertNull(impl.get(ListItem.class));
}
 
Example #18
Source File: MarkwonVisitorImplTest.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Test
public void ensure_new_line() {
    // new line will be inserted if length > 0 && last character is not a new line

    final SpannableBuilder builder = new SpannableBuilder();

    final MarkwonVisitorImpl impl = new MarkwonVisitorImpl(
            mock(MarkwonConfiguration.class),
            mock(RenderProps.class),
            builder,
            Collections.<Class<? extends Node>, MarkwonVisitor.NodeVisitor<? extends Node>>emptyMap(),
            mock(MarkwonVisitor.BlockHandler.class));

    // at the start - won't add anything
    impl.ensureNewLine();
    assertEquals(0, builder.length());

    // last char is new line -> won't add anything
    builder.append('\n');
    assertEquals(1, builder.length());
    impl.ensureNewLine();
    assertEquals(1, builder.length());

    // not-empty and last char is not new-line -> add new line
    builder.clear();
    assertEquals(0, builder.length());
    builder.append('a');
    assertEquals(1, builder.length());
    impl.ensureNewLine();
    assertEquals(2, builder.length());
    assertEquals('\n', builder.lastChar());
}
 
Example #19
Source File: Markdown.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/** 
 * Convert input markdown text to HTML.
 * Simple text is not wrapped in <p>...</p>.
 * @param markdown text with Markdown styles. If <code>null</code>, <code>""</code> is returned.
 * @return HTML rendering from the Markdown
 */
public String toHtml(String markdown) {
    if (markdown == null)
        return "";
    Node document = parser.parse(markdown);
    String html = renderer.render(document);
    html = unwrapped(html);
    return html;
}
 
Example #20
Source File: InsTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void delimited() {
    Node document = PARSER.parse("++foo++");
    Ins ins = (Ins) document.getFirstChild().getFirstChild();
    assertEquals("++", ins.getOpeningDelimiter());
    assertEquals("++", ins.getClosingDelimiter());
}
 
Example #21
Source File: InsDelimiterProcessor.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void process(Text opener, Text closer, int delimiterCount) {
    // Wrap nodes between delimiters in ins.
    Node ins = new Ins();

    Node tmp = opener.getNext();
    while (tmp != null && tmp != closer) {
        Node next = tmp.getNext();
        ins.appendChild(tmp);
        tmp = next;
    }

    opener.insertAfter(ins);
}
 
Example #22
Source File: MarkdownUtils.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 获取元数据
 *
 * @param content content
 * @return Map
 */
public static Map<String, List<String>> getFrontMatter(String content) {
    YamlFrontMatterVisitor visitor = new YamlFrontMatterVisitor();
    Node document = PARSER.parse(content);
    document.accept(visitor);
    return visitor.getData();
}
 
Example #23
Source File: EmojiDelimiterProcessor.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
@Override public void process(Text opener, Text closer, int delimiterCount) {
    Node emoji = new Emoji();
    Node tmp = opener.getNext();
    while (tmp != null && tmp != closer) {
        Node next = tmp.getNext();
        emoji.appendChild(tmp);
        tmp = next;
    }
    opener.insertAfter(emoji);
}
 
Example #24
Source File: EmojiNodeRenderer.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
private void renderChildren(Node parent) {
    Node node = parent.getFirstChild();
    while (node != null) {
        Node next = node.getNext();
        context.render(node);
        node = next;
    }
}
 
Example #25
Source File: TaskListItemHtmlNodeRenderer.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void renderChildren(Node parent) {
    Node node = parent.getFirstChild();
    while (node != null) {
        Node next = node.getNext();
        context.render(node);
        node = next;
    }
}
 
Example #26
Source File: MarkwonSpansFactoryImplTest.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Test
public void builder_prepend_factory() {
    // here is what we should validate:
    // * if we call prependFactory and there is none already -> supplied factory
    // * if there is
    // * * if not composite -> make composite
    // * * if composite -> add to it

    final MarkwonSpansFactoryImpl.BuilderImpl builder = new MarkwonSpansFactoryImpl.BuilderImpl();

    final SpanFactory first = mock(SpanFactory.class);
    final SpanFactory second = mock(SpanFactory.class);
    final SpanFactory third = mock(SpanFactory.class);

    final Class<Node> node = Node.class;

    // assert none yet
    assertNull(builder.getFactory(node));

    // add first, none yet -> it should be added without modifications
    builder.prependFactory(node, first);
    assertEquals(first, builder.getFactory(node));

    // add second -> composite factory will be created
    builder.prependFactory(node, second);
    final MarkwonSpansFactoryImpl.CompositeSpanFactory compositeSpanFactory =
            (MarkwonSpansFactoryImpl.CompositeSpanFactory) builder.getFactory(node);
    assertNotNull(compositeSpanFactory);
    assertEquals(Arrays.asList(first, second), compositeSpanFactory.factories);

    builder.prependFactory(node, third);
    assertEquals(compositeSpanFactory, builder.getFactory(node));
    assertEquals(Arrays.asList(first, second, third), compositeSpanFactory.factories);
}
 
Example #27
Source File: MustacheCustomTag.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
    if (node instanceof Link) {
        Link l = (Link) node;
        String destination = StringUtils.trimToEmpty(l.getDestination());
        if (UrlUtils.isAbsoluteUrl(destination)) {
            attributes.put("target", "_blank");
            attributes.put("rel", "nofollow noopener noreferrer");
        }
    }
}
 
Example #28
Source File: OpenBracketInlineProcessor.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Override
protected Node parse() {
    int startIndex = index;
    index++;

    Text node = text("[");

    // Add entry to stack for this opener
    addBracket(Bracket.link(node, startIndex, lastBracket(), lastDelimiter()));

    return node;
}
 
Example #29
Source File: CommonmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void printNode(StringBuilder buf, String indent, Node node) {
	buf.append(indent).append(node.getClass().getSimpleName()).append('[');
	Range range = toSourcePositions().get(node);
	if (range != null)
		buf.append(range.start).append(", ").append(range.end);
	buf.append("]");
	printAttributes(buf, node);
	buf.append('\n');

	indent += "    ";
	for (Node child = node.getFirstChild(); child != null; child = child.getNext())
		printNode(buf, indent, child);
}
 
Example #30
Source File: BulletListIsOrderedWithLettersWhenNestedPlugin.java    From Markwon with Apache License 2.0 5 votes vote down vote up
private static boolean isBulletOrdered(@NonNull Node node) {
    node = node.getParent();
    while (node != null) {
        if (node instanceof OrderedList) {
            return true;
        }
        if (node instanceof BulletList) {
            return false;
        }
        node = node.getParent();
    }
    return false;
}