com.vladsch.flexmark.util.data.MutableDataSet Java Examples

The following examples show how to use com.vladsch.flexmark.util.data.MutableDataSet. 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: FileUtils.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Html 转 Markdown
 * @param html
 * @return
 */
public static String htmlToMarkdown(String html) {
    MutableDataSet options = new MutableDataSet();
    String markdown = FlexmarkHtmlConverter.builder(options).build().convert(html);
    return markdown;
}
 
Example #2
Source File: MarkdownEditerController.java    From MyBox with Apache License 2.0 6 votes vote down vote up
protected void makeConverter() {
    try {
        parserOptions = new MutableDataSet();
        parserOptions.setFrom(ParserEmulationProfile.valueOf(emulationSelector.getValue()));
        parserOptions.set(Parser.EXTENSIONS, Arrays.asList(
                //                    AbbreviationExtension.create(),
                //                    DefinitionExtension.create(),
                //                    FootnoteExtension.create(),
                //                    TypographicExtension.create(),
                TablesExtension.create()
        ));
        parserOptions.set(HtmlRenderer.INDENT_SIZE, indentSize)
                //                    .set(HtmlRenderer.PERCENT_ENCODE_URLS, true)
                //                    .set(TablesExtension.COLUMN_SPANS, false)
                .set(TablesExtension.TRIM_CELL_WHITESPACE, trimCheck.isSelected())
                .set(TablesExtension.APPEND_MISSING_COLUMNS, appendCheck.isSelected())
                .set(TablesExtension.DISCARD_EXTRA_COLUMNS, discardCheck.isSelected())
                .set(TablesExtension.APPEND_MISSING_COLUMNS, appendCheck.isSelected());

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

    } catch (Exception e) {
        logger.error(e.toString());
    }
}
 
Example #3
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 #4
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 #5
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 #6
Source File: MarkdownToHtmlController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean makeMoreParameters() {
    try {
        parserOptions = new MutableDataSet();
        parserOptions.setFrom(ParserEmulationProfile.valueOf(emulationSelector.getValue()));
        parserOptions.set(Parser.EXTENSIONS, Arrays.asList(
                //                    AbbreviationExtension.create(),
                //                    DefinitionExtension.create(),
                //                    FootnoteExtension.create(),
                //                    TypographicExtension.create(),
                TablesExtension.create()
        ));
        parserOptions.set(HtmlRenderer.INDENT_SIZE, indentSize)
                //                    .set(HtmlRenderer.PERCENT_ENCODE_URLS, true)
                //                    .set(TablesExtension.COLUMN_SPANS, false)
                .set(TablesExtension.TRIM_CELL_WHITESPACE, trimCheck.isSelected())
                .set(TablesExtension.APPEND_MISSING_COLUMNS, appendCheck.isSelected())
                .set(TablesExtension.DISCARD_EXTRA_COLUMNS, discardCheck.isSelected())
                .set(TablesExtension.APPEND_MISSING_COLUMNS, appendCheck.isSelected());

        parser = Parser.builder(parserOptions).build();
        renderer = HtmlRenderer.builder(parserOptions).build();
    } catch (Exception e) {
        logger.error(e.toString());
        return false;
    }

    return super.makeMoreParameters();
}
 
Example #7
Source File: HtmlToMarkdownController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
@Override
public boolean makeMoreParameters() {
    try {
        parserOptions = new MutableDataSet();
    } catch (Exception e) {
        logger.error(e.toString());
        return false;
    }

    return super.makeMoreParameters();
}
 
Example #8
Source File: HtmlEditorController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
protected void html2markdown(String contents) {
    if (contents == null || contents.isEmpty()) {
        markdownArea.setText("");
        return;
    }
    synchronized (this) {
        if (task != null) {
            return;
        }
        task = new SingletonTask<Void>() {

            private String md;

            @Override
            protected boolean handle() {
                try {
                    MutableDataSet options = new MutableDataSet();
                    md = FlexmarkHtmlConverter.builder(options).build().convert(contents);
                    return md != null;
                } catch (Exception e) {
                    error = e.toString();
                    return false;
                }
            }

            @Override
            protected void whenSucceeded() {
                markdownArea.setText(md);
            }

        };
        openHandlingStage(task, Modality.WINDOW_MODAL);
        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();
    }
}
 
Example #9
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 #10
Source File: FlexmarkParser.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public FlexmarkParser() {
  MutableDataSet options = new MutableDataSet();
  options.set(Parser.EXTENSIONS, Arrays.asList(StrikethroughExtension.create(),
      TablesExtension.create(),
      UMLExtension.create(),
      AutolinkExtension.create(),
      WikiLinkExtension.create(),
      TypographicExtension.create()));
  options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");
  parser = Parser.builder(options).build();
  renderer = HtmlRenderer.builder(options).build();
}
 
Example #11
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 #12
Source File: Utils.java    From para with Apache License 2.0 5 votes vote down vote up
private static MutableDataHolder getMarkdownOptions() {
	return new MutableDataSet()
			.set(HtmlRenderer.ESCAPE_HTML, true)
			.set(EmojiExtension.USE_IMAGE_TYPE, EmojiImageType.UNICODE_FALLBACK_TO_IMAGE)
			// for full GFM table compatibility add the following table extension options:
			.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, Arrays.asList(TablesExtension.create(), EmojiExtension.create(),
					StrikethroughExtension.create(), TaskListExtension.create()));
}
 
Example #13
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 #14
Source File: DataRequirementsProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
private CqfMeasure processMarkDown(CqfMeasure measure) {

        MutableDataSet options = new MutableDataSet();

        options.setFrom(ParserEmulationProfile.GITHUB_DOC);
        options.set(Parser.EXTENSIONS, Arrays.asList(
                AutolinkExtension.create(),
                //AnchorLinkExtension.create(),
                //EmojiExtension.create(),
                StrikethroughExtension.create(),
                TablesExtension.create(),
                TaskListExtension.create()
        ));

        // uncomment and define location of emoji images from https://github.com/arvida/emoji-cheat-sheet.com
        // options.set(EmojiExtension.ROOT_IMAGE_PATH, "");

        // Uncomment if GFM anchor links are desired in headings
        // options.set(AnchorLinkExtension.ANCHORLINKS_SET_ID, false);
        // options.set(AnchorLinkExtension.ANCHORLINKS_ANCHOR_CLASS, "anchor");
        // options.set(AnchorLinkExtension.ANCHORLINKS_SET_NAME, true);
        // options.set(AnchorLinkExtension.ANCHORLINKS_TEXT_PREFIX, "<span class=\"octicon octicon-link\"></span>");

        // References compatibility
        options.set(Parser.REFERENCES_KEEP, KeepType.LAST);

        // Set GFM table parsing options
        options.set(TablesExtension.COLUMN_SPANS, false)
                .set(TablesExtension.MIN_HEADER_ROWS, 1)
                .set(TablesExtension.MAX_HEADER_ROWS, 1)
                .set(TablesExtension.APPEND_MISSING_COLUMNS, true)
                .set(TablesExtension.DISCARD_EXTRA_COLUMNS, true)
                .set(TablesExtension.WITH_CAPTION, false)
                .set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true);

        // Setup List Options for GitHub profile which is kramdown for documents
        options.setFrom(ParserEmulationProfile.GITHUB_DOC);

        options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");


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

        measure.setDescription(markdownToHtml(parser, renderer, measure.getDescription()));
        measure.setPurpose(markdownToHtml(parser, renderer, measure.getPurpose()));
        // measure.setCopyright(markdownToHtml(parser, renderer, measure.getCopyright()));
        measure.setRationale(markdownToHtml(parser, renderer, measure.getRationale()));
        measure.setClinicalRecommendationStatement(markdownToHtml(parser, renderer, measure.getClinicalRecommendationStatement()));
        measure.setGuidance(markdownToHtml(parser, renderer, measure.getGuidance()));

        measure.setDefinition(measure.getDefinition().stream()
            .map(x -> markdownToHtml(parser, renderer, x.getValueAsString()))
            .map(x -> new MarkdownType(x))
            .collect(Collectors.toList()));

        return measure;
    }
 
Example #15
Source File: DataRequirementsProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
private CqfMeasure processMarkDown(CqfMeasure measure) {

        MutableDataSet options = new MutableDataSet();

        options.setFrom(ParserEmulationProfile.GITHUB_DOC);
        options.set(Parser.EXTENSIONS, Arrays.asList(
                AutolinkExtension.create(),
                //AnchorLinkExtension.create(),
                //EmojiExtension.create(),
                StrikethroughExtension.create(),
                TablesExtension.create(),
                TaskListExtension.create()
        ));

        // uncomment and define location of emoji images from https://github.com/arvida/emoji-cheat-sheet.com
        // options.set(EmojiExtension.ROOT_IMAGE_PATH, "");

        // Uncomment if GFM anchor links are desired in headings
        // options.set(AnchorLinkExtension.ANCHORLINKS_SET_ID, false);
        // options.set(AnchorLinkExtension.ANCHORLINKS_ANCHOR_CLASS, "anchor");
        // options.set(AnchorLinkExtension.ANCHORLINKS_SET_NAME, true);
        // options.set(AnchorLinkExtension.ANCHORLINKS_TEXT_PREFIX, "<span class=\"octicon octicon-link\"></span>");

        // References compatibility
        options.set(Parser.REFERENCES_KEEP, KeepType.LAST);

        // Set GFM table parsing options
        options.set(TablesExtension.COLUMN_SPANS, false)
                .set(TablesExtension.MIN_HEADER_ROWS, 1)
                .set(TablesExtension.MAX_HEADER_ROWS, 1)
                .set(TablesExtension.APPEND_MISSING_COLUMNS, true)
                .set(TablesExtension.DISCARD_EXTRA_COLUMNS, true)
                .set(TablesExtension.WITH_CAPTION, false)
                .set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true);

        // Setup List Options for GitHub profile which is kramdown for documents
        options.setFrom(ParserEmulationProfile.GITHUB_DOC);

        options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");


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

        measure.setDescription(markdownToHtml(parser, renderer, measure.getDescription()));
        measure.setPurpose(markdownToHtml(parser, renderer, measure.getPurpose()));
        // measure.setCopyright(markdownToHtml(parser, renderer, measure.getCopyright()));
        measure.setRationale(markdownToHtml(parser, renderer, measure.getRationale()));
        measure.setClinicalRecommendationStatement(markdownToHtml(parser, renderer, measure.getClinicalRecommendationStatement()));
        measure.setGuidance(markdownToHtml(parser, renderer, measure.getGuidance()));

        measure.setDefinition(measure.getDefinition().stream()
            .map(x -> markdownToHtml(parser, renderer, x.getValueAsString()))
            .map(MarkdownType::new)
            .collect(Collectors.toList()));

        return measure;
    }
 
Example #16
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;
}