com.vladsch.flexmark.util.ast.Node Java Examples

The following examples show how to use com.vladsch.flexmark.util.ast.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: FlexmarkLinkResolver.java    From markdown-page-generator-plugin with MIT License 6 votes vote down vote up
@Override
public ResolvedLink resolveLink(Node node, LinkResolverContext context, ResolvedLink link) {
    ResolvedLink result = link;

    for (String inputFileExtension : inputFileExtensions) {
        if (link.getLinkType() == LinkType.LINK) {
            String url = link.getUrl();
            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                if (url.endsWith("." + inputFileExtension)) {
                    url = url.substring(0, url.length() - inputFileExtension.length()) + "html";
                    result = result.withStatus(LinkStatus.VALID).withUrl(url);
                    return result;
                } else if (url.contains("." + inputFileExtension + "#")) {
                    url = url.replace("." + inputFileExtension + "#", ".html#");
                    result = result.withStatus(LinkStatus.VALID).withUrl(url);
                    return result;
                }
            }
        }
    }

    return result;
}
 
Example #2
Source File: MarkDownModel.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
protected String load() {
    String markDownValue = markDawnModel.getObject();
    if (Strings.isEmpty(markDownValue)) {
        return "";
    }
    try {
        MutableDataSet options = new MutableDataSet();
        options.set(Parser.EXTENSIONS, createExtensions());
        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        Node node = parser.parse(markDawnModel.getObject());
        markDownValue = renderer.render(node);
    } catch (Exception e) {
        throw new WicketRuntimeException("Can't use flexmark-java for markups", e);
    }
    return markDownValue;
}
 
Example #3
Source File: MarkdownEditerController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public String convert2html() {
    try {
        if (parserOptions == null || parser == null || renderer == null) {
            makeConverter();
        }
        Node document = parser.parse(mainArea.getText());
        String html = renderer.render(document);
        String style;
        if (message("ConsoleStyle").equals(styleSelector.getValue())) {
            style = HtmlTools.ConsoleStyle;
        } else if (message("DefaultStyle").equals(styleSelector.getValue())) {
            style = HtmlTools.DefaultStyle;
        } else {
            style = null;
        }
        html = HtmlTools.html(titleInput.getText(), style, html);
        return html;
    } catch (Exception e) {
        return e.toString();
    }
}
 
Example #4
Source File: MarkdownEditerController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public String convert2text() {
    try {
        // https://github.com/vsch/flexmark-java/blob/master/flexmark-java-samples/src/com/vladsch/flexmark/samples/MarkdownToText.java
        DataHolder OPTIONS = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL);
        MutableDataSet FORMAT_OPTIONS = new MutableDataSet();
        FORMAT_OPTIONS.set(Parser.EXTENSIONS, OPTIONS.get(Parser.EXTENSIONS));
        Parser PARSER = Parser.builder(OPTIONS).build();

        Node document = PARSER.parse(mainArea.getText());
        TextCollectingVisitor textCollectingVisitor = new TextCollectingVisitor();
        String text = textCollectingVisitor.collectAndGetText(document);
        return text;
    } catch (Exception e) {
        return e.toString();
    }
}
 
Example #5
Source File: MarkdownUtils.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Render Markdown content
 *
 * @param markdown content
 * @return String
 */
public static String renderHtml(String markdown) {
    if (StringUtils.isBlank(markdown)) {
        return StringUtils.EMPTY;
    }

    // Render netease music short url.
    if (markdown.contains(HaloConst.NETEASE_MUSIC_PREFIX)) {
        markdown = markdown.replaceAll(HaloConst.NETEASE_MUSIC_REG_PATTERN, HaloConst.NETEASE_MUSIC_IFRAME);
    }

    // Render bilibili video short url.
    if (markdown.contains(HaloConst.BILIBILI_VIDEO_PREFIX)) {
        markdown = markdown.replaceAll(HaloConst.BILIBILI_VIDEO_REG_PATTERN, HaloConst.BILIBILI_VIDEO_IFRAME);
    }

    // Render youtube video short url.
    if (markdown.contains(HaloConst.YOUTUBE_VIDEO_PREFIX)) {
        markdown = markdown.replaceAll(HaloConst.YOUTUBE_VIDEO_REG_PATTERN, HaloConst.YOUTUBE_VIDEO_IFRAME);
    }

    Node document = PARSER.parse(markdown);

    return RENDERER.render(document);
}
 
Example #6
Source File: DataRequirementsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
private String markdownToHtml(Parser parser, HtmlRenderer renderer, String markdown) {
    if (Strings.isNullOrEmpty(markdown)) {
        return null;
    }

    Node document = parser.parse(markdown);
    return renderer.render(document);
}
 
Example #7
Source File: FlexmarkAttributeProvider.java    From markdown-page-generator-plugin with MIT License 5 votes vote down vote up
@Override
public void setAttributes(Node node, AttributablePart part, Attributes attributes) {
    if (attributeMap != null) {
        Attributes attributes1 = attributeMap.get(node.getClass().getSimpleName());
        if (attributes1 != null) {
            attributes.replaceValues(attributes1);
        }
    }
}
 
Example #8
Source File: MarkdownDialog.java    From gpx-animator with Apache License 2.0 5 votes vote down vote up
private String convertMarkdownToHTML(final String md) {
    final MutableDataSet options = new MutableDataSet();
    final Parser parser = Parser.builder(options).build();
    final HtmlRenderer renderer = HtmlRenderer.builder(options).build();
    final Node document = parser.parse(md);
    return renderer.render(document);
}
 
Example #9
Source File: MarkdownParser.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Compute the number of lines for reaching the given node.
 *
 * @param node the node.
 * @return the line number for the node.
 */
protected static int computeLineNo(Node node) {
	final int offset = node.getStartOffset();
	final BasedSequence seq = node.getDocument().getChars();
	int tmpOffset = seq.endOfLine(0);
	int lineno = 1;
	while (tmpOffset < offset) {
		++lineno;
		tmpOffset = seq.endOfLineAnyEOL(tmpOffset + seq.eolStartLength(tmpOffset));
	}
	return lineno;
}
 
Example #10
Source File: MarkdownParser.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Apply link transformation on the Markdown links.
 *
 * @param content the original content.
 * @param references the references into the document.
 * @return the result of the transformation.
 */
protected String transformMardownLinks(String content, ReferenceContext references) {
	if (!isMarkdownToHtmlReferenceTransformation()) {
		return content;
	}

	// Prepare replacement data structures
	final Map<BasedSequence, String> replacements = new TreeMap<>((cmp1, cmp2) -> {
		final int cmp = Integer.compare(cmp2.getStartOffset(), cmp1.getStartOffset());
		if (cmp != 0) {
			return cmp;
		}
		return Integer.compare(cmp2.getEndOffset(), cmp1.getEndOffset());
	});

	// Visit the links and record the transformations
	final MutableDataSet options = new MutableDataSet();
	final Parser parser = Parser.builder(options).build();
	final Node document = parser.parse(content);
	final NodeVisitor visitor = new NodeVisitor(
			new VisitHandler<>(Link.class, it -> {
				URL url = FileSystem.convertStringToURL(it.getUrl().toString(), true);
				url = transformURL(url, references);
				if (url != null) {
					replacements.put(it.getUrl(), convertURLToString(url));
				}
			}));
	visitor.visitChildren(document);

	// Apply the replacements
	if (!replacements.isEmpty()) {
		final StringBuilder buffer = new StringBuilder(content);
		for (final Entry<BasedSequence, String> entry : replacements.entrySet()) {
			final BasedSequence seq = entry.getKey();
			buffer.replace(seq.getStartOffset(), seq.getEndOffset(), entry.getValue());
		}
		return buffer.toString();
	}
	return content;
}
 
Example #11
Source File: UMLBlockQuoteParser.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public BlockContinue tryContinue(ParserState state) {
  if (hadClose) {
    return BlockContinue.none();
  }

  final int index = state.getIndex();

  BasedSequence line = state.getLineWithEOL();
  final Matcher matcher = YUML_BLOCK_END.matcher(line.subSequence(index));
  if (!matcher.matches()) {
    return BlockContinue.atIndex(index);
  } else {
    // if have open gitlab block quote last child then let them handle it
    Node lastChild = block.getLastChild();
    if (lastChild instanceof UMLBlockQuote) {
      final BlockParser parser = state.getActiveBlockParser((Block) lastChild);
      if (parser instanceof UMLBlockQuoteParser && !((UMLBlockQuoteParser) parser).hadClose) {
        // let the child handle it
        return BlockContinue.atIndex(index);
      }
    }
    hadClose = true;
    block.setClosingMarker(state.getLine().subSequence(index, index + 3));
    block.setClosingTrailing(state.getLineWithEOL().subSequence(matcher.start(1),
        matcher.end(1)));
    return BlockContinue.atIndex(state.getLineEndIndex());
  }
}
 
Example #12
Source File: DataRequirementsProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
private String markdownToHtml(Parser parser, HtmlRenderer renderer, String markdown) {
    if (Strings.isNullOrEmpty(markdown)) {
        return null;
    }

    Node document = parser.parse(markdown);
    return renderer.render(document);
}
 
Example #13
Source File: MarkDownUtil.java    From smart-doc with Apache License 2.0 5 votes vote down vote up
/**
 * Convert markdown to html.
 *
 * @param content markdown contents
 * @return html contents
 */
public static String toHtml(String content) {
    MutableDataSet options = new MutableDataSet();
    options.setFrom(ParserEmulationProfile.MARKDOWN);
    // enable table parse!
    options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

    Parser parser = Parser.builder(options).build();
    HtmlRenderer renderer = HtmlRenderer.builder(options).build();

    Node document = parser.parse(content);
    return renderer.render(document);
}
 
Example #14
Source File: JenkinsConfiguredWithReadmeRule.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private List<String> transformFencedCodeBlockFromMarkdownToString(InputStream markdownContent) throws IOException {
    ArrayList<String> results = new ArrayList<String>();
    final MutableDataSet FORMAT_OPTIONS = new MutableDataSet();
    FORMAT_OPTIONS.set(Parser.EXTENSIONS, OPTIONS.get(Parser.EXTENSIONS));
    Reader targetReader = new InputStreamReader(markdownContent);
    Node document = PARSER.parseReader(targetReader);
    TextCollectingVisitor textCollectingVisitor = new TextCollectingVisitor();
    Node fencedCodeBlock = document.getChildOfType(FencedCodeBlock.class);
    while (fencedCodeBlock != null) {
        results.add(textCollectingVisitor.collectAndGetText(fencedCodeBlock));
        fencedCodeBlock = fencedCodeBlock.getNextAny(FencedCodeBlock.class);
    }
    return results;
}
 
Example #15
Source File: MarkdownUtils.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get front-matter
 *
 * @param markdown markdown
 * @return Map
 */
public static Map<String, List<String>> getFrontMatter(String markdown) {
    AbstractYamlFrontMatterVisitor visitor = new AbstractYamlFrontMatterVisitor();
    Node document = PARSER.parse(markdown);
    visitor.visit(document);
    return visitor.getData();
}
 
Example #16
Source File: MarkdownToHtmlController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public String handleFile(File srcFile, File targetPath) {
    try {
        countHandling(srcFile);
        File target = makeTargetFile(srcFile, targetPath);
        if (target == null) {
            return AppVariables.message("Skip");
        }
        Node document = parser.parse(FileTools.readTexts(srcFile));
        String html = renderer.render(document);
        String style;
        if (message("ConsoleStyle").equals(styleSelector.getValue())) {
            style = HtmlTools.ConsoleStyle;
        } else if (message("DefaultStyle").equals(styleSelector.getValue())) {
            style = HtmlTools.DefaultStyle;
        } else {
            style = null;
        }
        html = HtmlTools.html(titleInput.getText(), style, html);

        FileTools.writeFile(target, html);
        if (verboseCheck == null || verboseCheck.isSelected()) {
            updateLogs(MessageFormat.format(message("ConvertSuccessfully"),
                    srcFile.getAbsolutePath(), target.getAbsolutePath()));
        }
        targetFileGenerated(target);
        return AppVariables.message("Successful");
    } catch (Exception e) {
        logger.error(e.toString());
        return AppVariables.message("Failed");
    }
}
 
Example #17
Source File: HelpActivity.java    From mhzs with MIT License 5 votes vote down vote up
/**
     * 展示网页
     */
    private void showHtml(String md) {
        DataHolder OPTIONS = PegdownOptionsAdapter.flexmarkOptions(true,
                Extensions.NONE);
        Parser parser = Parser.builder(OPTIONS).build();
        HtmlRenderer renderer = HtmlRenderer.builder(OPTIONS).build();

        Node document = parser.parse(md);
        String html = renderer.render(document);

//        LogUtil.e(html);

        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.loadData(html, "text/html; charset=UTF-8", null);
    }
 
Example #18
Source File: AppDetailPanel.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public void setHumans(String humans) {
    if (humans != null && !humans.isEmpty()) {
        this.humansTextHeader.setVisible(true);
        this.humans.setVisible(true);
        Node document = MARKDOWN_PARSER.parse(humans);
        String html = MARKDOWN_RENDER.render(document);
        this.humans.setText(html);
    } else {
        this.humansTextHeader.setVisible(false);
        this.humans.setVisible(false);
        this.humans.setText("");
    }
}
 
Example #19
Source File: FileUtils.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Markdown转Html
 * @param markdown
 * @return
 */
public static String markdownToHtml(String markdown) {
    MutableDataSet options = new MutableDataSet();
    Parser parser = Parser.builder(options).build();
    HtmlRenderer renderer = HtmlRenderer.builder(options).build();
    Node document = parser.parse(markdown);
    String html = renderer.render(document);
    return html;
}
 
Example #20
Source File: FlexmarkParser.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public String render(String markdownText) {
  Node document = parser.parse(markdownText);
  String html = renderer.render(document);
  return wrapWithMarkdownClassDiv(html);
}
 
Example #21
Source File: MarkdownParser.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Extract all the referencable objects from the given content.
 *
 * @param text the content to parse.
 * @return the referencables objects
 */
@SuppressWarnings("static-method")
protected ReferenceContext extractReferencableElements(String text) {
	final ReferenceContext context = new ReferenceContext();

	// Visit the links and record the transformations
	final MutableDataSet options = new MutableDataSet();
	final Parser parser = Parser.builder(options).build();
	final Node document = parser.parse(text);
	final Pattern pattern = Pattern.compile(SECTION_PATTERN_AUTONUMBERING);
	NodeVisitor visitor = new NodeVisitor(
			new VisitHandler<>(Paragraph.class, it -> {
				final CharSequence paragraphText = it.getContentChars();
				final Matcher matcher = pattern.matcher(paragraphText);
				if (matcher.find()) {
					final String number = matcher.group(2);
					final String title = matcher.group(3);
					final String key1 = computeHeaderId(number, title);
					final String key2 = computeHeaderId(null, title);
					context.registerSection(key1, key2, title);
				}
			}));
	visitor.visitChildren(document);

	final Pattern pattern1 = Pattern.compile(SECTION_PATTERN_TITLE_EXTRACTOR_WITHOUT_MD_PREFIX);
	visitor = new NodeVisitor(
			new VisitHandler<>(Heading.class, it -> {
				String key = it.getAnchorRefId();
				String title = it.getText().toString();
				// Sometimes, the title already contains the section number.
				// It should be removed.
				final Matcher matcher = pattern1.matcher(title);
				if (matcher.find()) {
					final String number = matcher.group(1);
					title = matcher.group(2);
					if (Strings.isEmpty(key)) {
						key = computeHeaderId(number, title);
					}
				}
				final String key2 = computeHeaderId(null, title);
				if (Strings.isEmpty(key)) {
					key = key2;
				}
				context.registerSection(key, key2, title);
			}));
	visitor.visitChildren(document);

	return context;
}
 
Example #22
Source File: MarkdownUtils.java    From rebuild with GNU General Public License v3.0 2 votes vote down vote up
/**
    * MD 渲染,支持表格
    *
 * @param md
 * @return
 */
public static String render(String md) {
	Node document = PARSER.parse(md);
	return RENDERER.render(document);
}