org.commonmark.node.Text Java Examples

The following examples show how to use org.commonmark.node.Text. 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: BangInlineProcessor.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Override
protected Node parse() {
    int startIndex = index;
    index++;
    if (peek() == '[') {
        index++;

        Text node = text("![");

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

        return node;
    } else {
        return text("!");
    }
}
 
Example #2
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 #3
Source File: CommonmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void printAttributes(StringBuilder buf, Node node) {
	if (node instanceof Text)
		printAttribute(buf, "literal", ((Text)node).getLiteral());
	else if (node instanceof Code)
		printAttribute(buf, "literal", ((Code)node).getLiteral());
	else if (node instanceof IndentedCodeBlock)
		printAttribute(buf, "literal", ((IndentedCodeBlock)node).getLiteral());
	else if (node instanceof FencedCodeBlock)
		printAttribute(buf, "literal", ((FencedCodeBlock)node).getLiteral());
	else if (node instanceof HtmlBlock)
		printAttribute(buf, "literal", ((HtmlBlock)node).getLiteral());
	else if (node instanceof HtmlInline)
		printAttribute(buf, "literal", ((HtmlInline)node).getLiteral());
	else if (node instanceof Link) {
		printAttribute(buf, "destination", ((Link)node).getDestination());
		printAttribute(buf, "title", ((Link)node).getTitle());
	} else if (node instanceof Image) {
		printAttribute(buf, "destination", ((Image)node).getDestination());
		printAttribute(buf, "title", ((Image)node).getTitle());
	} else if (node instanceof Heading)
		printAttribute(buf, "level", ((Heading)node).getLevel());
}
 
Example #4
Source File: EmphasisDelimiterProcessor.java    From commonmark-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void process(Text opener, Text closer, int delimiterUse) {
    String singleDelimiter = String.valueOf(getOpeningCharacter());
    Node emphasis = delimiterUse == 1
            ? new Emphasis(singleDelimiter)
            : new StrongEmphasis(singleDelimiter + singleDelimiter);

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

    opener.insertAfter(emphasis);
}
 
Example #5
Source File: AutolinkPostProcessor.java    From commonmark-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void linkify(Text textNode) {
    String literal = textNode.getLiteral();

    Node lastNode = textNode;

    for (Span span : linkExtractor.extractSpans(literal)) {
        String text = literal.substring(span.getBeginIndex(), span.getEndIndex());
        if (span instanceof LinkSpan) {
            String destination = getDestination((LinkSpan) span, text);
            Text contentNode = new Text(text);
            Link linkNode = new Link(destination, null);
            linkNode.appendChild(contentNode);
            lastNode = insertNode(linkNode, lastNode);
        } else {
            lastNode = insertNode(new Text(text), lastNode);
        }
    }

    // Original node no longer needed
    textNode.unlink();
}
 
Example #6
Source File: MarkwonInlineParser.java    From Markwon with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to parse delimiters like emphasis, strong emphasis or custom delimiters.
 */
@Nullable
private Node parseDelimiters(DelimiterProcessor delimiterProcessor, char delimiterChar) {
    DelimiterData res = scanDelimiters(delimiterProcessor, delimiterChar);
    if (res == null) {
        return null;
    }
    int length = res.count;
    int startIndex = index;

    index += length;
    Text node = text(input, startIndex, index);

    // Add entry to stack for this opener
    lastDelimiter = new Delimiter(node, delimiterChar, res.canOpen, res.canClose, lastDelimiter);
    lastDelimiter.length = length;
    lastDelimiter.originalLength = length;
    if (lastDelimiter.previous != null) {
        lastDelimiter.previous.next = lastDelimiter;
    }

    return node;
}
 
Example #7
Source File: InlineParserUtils.java    From Markwon with Apache License 2.0 6 votes vote down vote up
public static void mergeIfNeeded(Text first, Text last, int textLength) {
    if (first != null && last != null && first != last) {
        StringBuilder sb = new StringBuilder(textLength);
        sb.append(first.getLiteral());
        Node node = first.getNext();
        Node stop = last.getNext();
        while (node != stop) {
            sb.append(((Text) node).getLiteral());
            Node unlink = node;
            node = node.getNext();
            unlink.unlink();
        }
        String literal = sb.toString();
        first.setLiteral(literal);
    }
}
 
Example #8
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 #9
Source File: SimpleExtDelimiterProcessor.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Text opener, Text closer, int delimiterUse) {

    final Node node = new SimpleExtNode(spanFactory);

    Node tmp = opener.getNext();
    Node next;

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

    opener.insertAfter(node);
}
 
Example #10
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 #11
Source File: MarkwonSpansFactoryImplTest.java    From Markwon with Apache License 2.0 6 votes vote down vote up
@Test
public void require_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.require(Text.class));

    // we haven't registered ListItem, so null here
    try {
        impl.require(ListItem.class);
        fail();
    } catch (NullPointerException e) {
        assertTrue(true);
    }
}
 
Example #12
Source File: EmphasisDelimiterProcessor.java    From 1Rramp-Android with MIT License 6 votes vote down vote up
@Override
public void process(Text opener, Text closer, int delimiterUse) {
    String singleDelimiter = String.valueOf(getOpeningCharacter());
    Node emphasis = delimiterUse == 1
            ? new Emphasis(singleDelimiter)
            : new StrongEmphasis(singleDelimiter + singleDelimiter);

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

    opener.insertAfter(emphasis);
}
 
Example #13
Source File: MentionDelimiterProcessor.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 mention = new Mention();
    Node tmp = opener.getNext();
    while (tmp != null && tmp != closer) {
        Node next = tmp.getNext();
        mention.appendChild(tmp);
        tmp = next;
    }
    opener.insertAfter(mention);
}
 
Example #14
Source File: Delimiter.java    From 1Rramp-Android with MIT License 5 votes vote down vote up
public Delimiter(Text node, char delimiterChar, boolean canOpen, boolean canClose, Delimiter previous) {
    this.node = node;
    this.delimiterChar = delimiterChar;
    this.canOpen = canOpen;
    this.canClose = canClose;
    this.previous = previous;
}
 
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: DelimiterProcessorTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void render(Node node) {
    UpperCaseNode upperCaseNode = (UpperCaseNode) node;
    for (Node child = upperCaseNode.getFirstChild(); child != null; child = child.getNext()) {
        if (child instanceof Text) {
            Text text = (Text) child;
            text.setLiteral(text.getLiteral().toUpperCase(Locale.ENGLISH));
        }
        context.render(child);
    }
}
 
Example #17
Source File: DelimiterProcessorTest.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 delimiterUse) {
    UpperCaseNode content = new UpperCaseNode();
    Node tmp = opener.getNext();
    while (tmp != null && tmp != closer) {
        Node next = tmp.getNext();
        content.appendChild(tmp);
        tmp = next;
    }
    opener.insertAfter(content);
}
 
Example #18
Source File: Bracket.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Bracket(Text node, int index, Bracket previous, Delimiter previousDelimiter, boolean image) {
    this.node = node;
    this.index = index;
    this.image = image;
    this.previous = previous;
    this.previousDelimiter = previousDelimiter;
}
 
Example #19
Source File: Delimiter.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Delimiter(Text node, char delimiterChar, boolean canOpen, boolean canClose, Delimiter previous) {
    this.node = node;
    this.delimiterChar = delimiterChar;
    this.canOpen = canOpen;
    this.canClose = canClose;
    this.previous = previous;
}
 
Example #20
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 #21
Source File: StrikethroughDelimiterProcessor.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 strikethrough.
    Node strikethrough = new Strikethrough();

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

    opener.insertAfter(strikethrough);
}
 
Example #22
Source File: Bracket.java    From 1Rramp-Android with MIT License 5 votes vote down vote up
private Bracket(Text node, int index, Bracket previous, Delimiter previousDelimiter, boolean image) {
    this.node = node;
    this.index = index;
    this.image = image;
    this.previous = previous;
    this.previousDelimiter = previousDelimiter;
}
 
Example #23
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 #24
Source File: InlineParserUtils.java    From Markwon with Apache License 2.0 5 votes vote down vote up
public static void mergeTextNodesInclusive(Node fromNode, Node toNode) {
    Text first = null;
    Text last = null;
    int length = 0;

    Node node = fromNode;
    while (node != null) {
        if (node instanceof Text) {
            Text text = (Text) node;
            if (first == null) {
                first = text;
            }
            length += text.getLiteral().length();
            last = text;
        } else {
            mergeIfNeeded(first, last, length);
            first = null;
            last = null;
            length = 0;
        }
        if (node == toNode) {
            break;
        }
        node = node.getNext();
    }

    mergeIfNeeded(first, last, length);
}
 
Example #25
Source File: PageTextRenderer.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void render(Node node) {
    Text text = (Text) node;
    if (text.getParent() != null && text.getParent() instanceof Link) {
        html.text(text.getLiteral());
    } else {
        CreateInnerLinksResult result = keywordService.createInnerLinks(text.getLiteral());
        if (result.inserted) {
            html.raw(result.result);
        } else {
            html.text(text.getLiteral());
        }
    }
}
 
Example #26
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 #27
Source File: MarkwonVisitorImplTest.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Test
public void set_spans_for_node() {
    // internally requests spanFactory via `require` call (thus throwing exception)
    // configuration.spansFactory().require(node).getSpans(configuration, renderProps)

    final MarkwonConfiguration configuration = mock(MarkwonConfiguration.class);
    final MarkwonSpansFactory spansFactory = mock(MarkwonSpansFactory.class);
    final SpanFactory factory = mock(SpanFactory.class);

    when(configuration.spansFactory()).thenReturn(spansFactory);
    when(spansFactory.require(eq(Node.class))).thenReturn(factory);
    when(spansFactory.require(eq(Text.class))).thenThrow(new NullPointerException());

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

    impl.setSpansForNode(Node.class, 0);

    verify(configuration, times(1)).spansFactory();
    verify(spansFactory, times(1)).require(eq(Node.class));
    verify(factory, times(1)).getSpans(eq(configuration), any(RenderProps.class));

    try {
        impl.setSpansForNode(Text.class, 0);
        fail();
    } catch (NullPointerException e) {
        assertTrue(true);
    }
}
 
Example #28
Source File: MarkwonSpansFactoryTest.java    From Markwon with Apache License 2.0 5 votes vote down vote up
@Test
public void builder_set() {
    final SpanFactory factory = mock(SpanFactory.class);
    builder.setFactory(Text.class, factory);
    builder.setFactory(Text.class, factory);
    assertEquals(factory, builder.build().get(Text.class));
    assertEquals(factory, builder.build().require(Text.class));
}
 
Example #29
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 #30
Source File: MarkdownAssert.java    From doov with Apache License 2.0 5 votes vote down vote up
public IntegerAssert countText() {
    final AtomicInteger count = new AtomicInteger();
    actual.accept(new AbstractVisitor() {

        @Override
        public void visit(Text text) {
            count.incrementAndGet();
            super.visit(text);
        }
    });
    return new IntegerAssert(count.get());
}