Java Code Examples for com.vladsch.flexmark.parser.Parser#parse()

The following examples show how to use com.vladsch.flexmark.parser.Parser#parse() . 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: MarkdownEngine.java    From jbake with MIT License 6 votes vote down vote up
@Override
public void processBody(final ParserContext context) {
    List<String> mdExts = context.getConfig().getMarkdownExtensions();

    int extensions = PegdownExtensions.NONE;

    for (String ext : mdExts) {
        if (ext.startsWith("-")) {
            ext = ext.substring(1);
            extensions = removeExtension(extensions, extensionFor(ext));
        } else {
            if (ext.startsWith("+")) {
                ext = ext.substring(1);
            }
            extensions = addExtension(extensions, extensionFor(ext));
        }
    }

    DataHolder options = PegdownOptionsAdapter.flexmarkOptions(extensions);

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

    Document document = parser.parse(context.getBody());
    context.setBody(renderer.render(document));
}
 
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: MarkdownHandler.java    From 1Rramp-Android with MIT License 6 votes vote down vote up
public static String getHtmlFromMarkdown(String md){
  MutableDataSet options = new MutableDataSet();

  // uncomment to set optional extensions
  //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

  // uncomment to convert soft-breaks to hard breaks
  //options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

  Parser parser = Parser.builder(options).build();
  HtmlRenderer renderer = HtmlRenderer.builder(options).build();
  Node document = parser.parse(md);
  String html = renderer.render(document);
  //do some more formatting
  html = RegexUtils.replaceMarkdownImage(html);
  html = RegexUtils.replacePlainImageLinks(html);
  return html;
}
 
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: DocumentationGenerator.java    From TestingApp with Apache License 2.0 6 votes vote down vote up
public String getInstructionsAsHTML() {
    MutableDataSet options = new MutableDataSet();

    // uncomment to set optional extensions
    //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

    // uncomment to convert soft-breaks to hard breaks
    options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

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

    String markdown = getInstructionsAsMarkdown();

    // You can re-use parser and renderer instances
    Node document = parser.parse(markdown);
    return renderer.render(document);
}
 
Example 6
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 7
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 8
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 9
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 10
Source File: DefaultMarkdownManager.java    From onedev with MIT License 5 votes vote down vote up
@Override
public String render(String markdown) {
	List<Extension> extensions = new ArrayList<>();
	extensions.add(AnchorLinkExtension.create());
	extensions.add(TablesExtension.create());
	extensions.add(TaskListExtension.create());
	extensions.add(DefinitionExtension.create());
	extensions.add(TocExtension.create());
	extensions.add(AutolinkExtension.create());
	extensions.addAll(contributedExtensions);

	MutableDataHolder options = new MutableDataSet()
			.set(HtmlRenderer.GENERATE_HEADER_ID, true)
			.set(AnchorLinkExtension.ANCHORLINKS_SET_NAME, true)
			.set(AnchorLinkExtension.ANCHORLINKS_WRAP_TEXT, false)
			.set(AnchorLinkExtension.ANCHORLINKS_TEXT_PREFIX, "<span class='header-anchor'></span>")
			.set(Parser.SPACE_IN_LINK_URLS, true)
			.setFrom(ParserEmulationProfile.GITHUB_DOC)
			.set(TablesExtension.COLUMN_SPANS, false)
			.set(TablesExtension.APPEND_MISSING_COLUMNS, true)
			.set(TablesExtension.DISCARD_EXTRA_COLUMNS, true)
			.set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true)
			.set(Parser.EXTENSIONS, extensions);

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

	HtmlRenderer htmlRenderer = HtmlRenderer.builder(options).build();
	
	Node document = parser.parse(markdown);
	return htmlRenderer.render(document);
}
 
Example 11
Source File: Markdown2HtmlUtil.java    From plumemo with Apache License 2.0 5 votes vote down vote up
/**
 * Markdownz转为Html
 * @param content
 * @return
 */
public static String html(String content){

    MutableDataSet options = new MutableDataSet();
    options.setFrom(ParserEmulationProfile.MARKDOWN);
    options.set(Parser.EXTENSIONS, Arrays.asList(new Extension[]{TablesExtension.create()}));
    Parser parser = Parser.builder(options).build();
    HtmlRenderer renderer = HtmlRenderer.builder(options).build();
    Node document = parser.parse(content);

    return renderer.render(document);
}
 
Example 12
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 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: HtmlExportHelper.java    From mdw with Apache License 2.0 4 votes vote down vote up
public String getHtml(String markdown) {
    Parser parser = FlexmarkInstances.getParser(null);
    HtmlRenderer renderer = FlexmarkInstances.getRenderer(null);
    Node document = parser.parse(markdown);
    return renderer.render(document);
}
 
Example 15
Source File: BloggerBlogServiceImpl.java    From BlogSystem with Apache License 2.0 4 votes vote down vote up
private BlogTitleIdDTO analysisAndInsertMdFile(Parser parser, HtmlRenderer renderer, ZipEntry entry,
                                               InputStreamReader reader, int bloggerId, Long cateId) throws IOException {
    String name = entry.getName();

    if (!name.endsWith(".md")) return null;

    StringBuilder b = new StringBuilder((int) entry.getSize());
    int len = 0;
    char[] buff = new char[1024];
    while ((len = reader.read(buff)) > 0) {
        b.append(buff, 0, len);
    }

    // reader.close();
    // zip 文件关闭由 370行:zipFile.close() 统一关闭

    // 内容
    String mdContent = b.toString();

    // 对应的 html 内容
    Document document = parser.parse(mdContent);
    String htmlContent = renderer.render(document);

    // 摘要
    String firReg = htmlContent.replaceAll("<.*?>", ""); // 避免 subString 使有遗留的 html 标签,前端显示时会出错
    String tmpStr = firReg.length() > 500 ? firReg.substring(0, 500) : firReg;
    String aftReg = tmpStr.replaceAll("\\n", "");
    String summary = aftReg.length() > 200 ? aftReg.substring(0, 200) : aftReg;

    // UPDATE: 2018/4/4 更新 图片引用

    // 文件名作为标题
    String title = cateId == -1 ? name.replace(".md", "") :
            name.substring(name.lastIndexOf("/") + 1).replace(".md", "");

    int[] cts = {Math.toIntExact(cateId)};
    int id = insertBlog(bloggerId,
            cts,
            null,
            PUBLIC,
            title,
            htmlContent,
            mdContent,
            summary,
            null,
            false);
    if (id < 0) return null;

    BlogTitleIdDTO node = new BlogTitleIdDTO();
    node.setTitle(title);
    node.setId(id);

    return node;
}
 
Example 16
Source File: FlexmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private Node parseMarkdown(String text) {
	Parser parser = Parser.builder()
			.extensions(MarkdownExtensions.getFlexmarkExtensions())
			.build();
	return parser.parse(text);
}
 
Example 17
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 18
Source File: FlexmarkMarkDownProcessorImpl.java    From maven-confluence-plugin with Apache License 2.0 3 votes vote down vote up
/**
 *
 * @param content
 * @return
 */
@Override
public String processMarkdown( MarkdownParserContext context, final String content) throws IOException {

    final Parser parser = Parser.builder(FlexmarkConfluenceWikiVisitor.OPTIONS()).build();

    final Document doc = parser.parse( content );

    throw new UnsupportedOperationException("Flexmark parser is not implememnted yet!");

}