com.vladsch.flexmark.parser.Parser Java Examples

The following examples show how to use com.vladsch.flexmark.parser.Parser. 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: MarkdownView.java    From MarkdownView with Apache License 2.0 6 votes vote down vote up
private String parseBuildAndRender(String text) {
    Parser parser = Parser.builder(OPTIONS)
            .extensions(EXTENSIONS)
            .build();

    HtmlRenderer renderer = HtmlRenderer.builder(OPTIONS)
            .escapeHtml(mEscapeHtml)
            .attributeProviderFactory(new IndependentAttributeProviderFactory() {
                @Override
                public AttributeProvider create(NodeRendererContext context) {
                    return new CustomAttributeProvider();
                }
            })
            .nodeRendererFactory(new NodeRendererFactoryImpl())
            .extensions(EXTENSIONS)
            .build();

    return renderer.render(parser.parse(text));
}
 
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: MarkdownParser.java    From OmniList with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected String doInBackground(String... strings) {
    Parser parser = Parser.builder(OPTIONS)
            .extensions(EXTENSIONS)
            .build();

    HtmlRenderer renderer = HtmlRenderer.builder(OPTIONS)
            .escapeHtml(true)
            .attributeProviderFactory(new IndependentAttributeProviderFactory() {
                @Override
                public AttributeProvider create(NodeRendererContext context) {
                    return new CustomAttributeProvider();
                }
            })
            .nodeRendererFactory(new NodeRendererFactoryImpl())
            .extensions(EXTENSIONS)
            .build();

    return renderer.render(parser.parse(strings[0]));
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: TestSmartFormat.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static String format(String input, int wrapLength) {
	// parse markdown
	Document document = Parser.builder().build().parse(input);

	// format
	List<Pair<Block, String>> formattedParagraphs = new SmartFormat(null, null)
		.formatParagraphs(document, wrapLength, null, null);

	// build result
	StringBuilder output = new StringBuilder(input);
	for (int i = formattedParagraphs.size() - 1; i >= 0; i--) {
		Pair<Block, String> pair = formattedParagraphs.get(i);
		Block paragraph = pair.getFirst();
		String newText = pair.getSecond();

		int startOffset = paragraph.getStartOffset();
		int endOffset = paragraph.getEndOffset();

		output.replace(startOffset, endOffset, newText);
	}
	return output.toString();
}
 
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: 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 #12
Source File: MarkdownEditorPane.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
Node parseMarkdown(String text) {
	if (parser == null) {
		parser = Parser.builder()
			.extensions(MarkdownExtensions.getFlexmarkExtensions(Options.getMarkdownRenderer()))
			.build();
	}
	return parser.parse(text);
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: PMarkdownOptions.java    From jphp with Apache License 2.0 5 votes vote down vote up
public MutableDataSet getNativeOptions() {
    MutableDataSet dataSet = new MutableDataSet();
    dataSet.set(Parser.EXTENSIONS, parserExtensions);

    for (Entry<DataKey, Object> entry : options.getAll().entrySet()) {
        dataSet.set(entry.getKey(), entry.getValue());
    }

    return dataSet;
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: MarkExtension.java    From MarkdownView with Apache License 2.0 4 votes vote down vote up
@Override
public void extend(Parser.Builder parserBuilder) {
    parserBuilder.customDelimiterProcessor(new MarkDelimiterProcessor());
}
 
Example #25
Source File: PMarkdown.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public void __construct(PMarkdownOptions options) {
    renderer = HtmlRenderer.builder(options.getNativeOptions()).build();
    parser = Parser.builder(options.getNativeOptions()).build();
}
 
Example #26
Source File: PMarkdown.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public void __construct() {
    renderer = HtmlRenderer.builder().build();
    parser = Parser.builder().build();
}
 
Example #27
Source File: PMarkdown.java    From jphp with Apache License 2.0 4 votes vote down vote up
public PMarkdown(Environment env, HtmlRenderer renderer, Parser parser) {
    super(env);
    this.renderer = renderer;
    this.parser = parser;
}
 
Example #28
Source File: MarkExtension.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void extend(Parser.Builder parserBuilder) {
    parserBuilder.customDelimiterProcessor(new MarkDelimiterProcessor());
}
 
Example #29
Source File: MathJaxExtension.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void extend(Parser.Builder parserBuilder) {
    parserBuilder.customDelimiterProcessor(new MathJaxDelimiterProcessor());
}
 
Example #30
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;
}