Skip to content

Markdown to HTML Converter — Java source

Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.

This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// markdown-to-html — escape-first CommonMark subset → HTML renderer. Java port
// (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
// Hand-rolled CommonMark SUBSET — everything is HTML-escaped before the inline
// rules run (raw HTML never passes through; security first), via the shared
// five-char escaper inlined here (`&` first so the entities we emit are never
// re-escaped). Supported blocks: #-headings (1-6), --- /***/ ___ rules, ```
// fenced code (markdown inert inside), > blockquotes (recursive), - * +
// unordered lists, N. ordered lists (source numbers stripped), paragraphs
// (soft line breaks joined with \n). Inline precedence: code spans first
// (placeholder-protected), then images, links, bold, italic, strikethrough —
// non-greedy pairs. Not supported (by design, documented): raw HTML, tables,
// setext headings, nested lists, footnotes, autolinks. Empty or whitespace-only
// input is NOT an error — the tool shows nothing. Never throws.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// Package-private: display snippets keep the repo filename (markdown-to-html.java),
// which need not match the class name.
final class MarkdownToHtml {

    private static final Pattern HEADING = Pattern.compile("^(#{1,6}) (.*)$");
    private static final Pattern HR = Pattern.compile("^(---+|\\*\\*\\*+|___+)\\s*$");
    private static final Pattern UL = Pattern.compile("^[-*+] ");
    private static final Pattern OL = Pattern.compile("^\\d+\\. ");
    private static final Pattern CODE_SPAN = Pattern.compile("`([^`]+)`");
    private static final Pattern IMAGE = Pattern.compile("!\\[([^\\]]*)\\]\\(([^)\\s]+)\\)");
    private static final Pattern LINK = Pattern.compile("\\[([^\\]]+)\\]\\(([^)\\s]+)\\)");

    /** Result union mirror: output + nullable error (always null — never fails). */
    static final class Result {
        final String output;
        final String error;
        Result(String output, String error) { this.output = output; this.error = error; }
    }

    /** JS-style global replace: each match becomes a computed string (no
     *  replacement-template escapes, captured text is emitted verbatim). */
    private interface Replacer { String apply(Matcher m); }

    private static String replaceAll(String s, Pattern p, Replacer f) {
        Matcher m = p.matcher(s);
        StringBuilder out = new StringBuilder();
        int last = 0;
        while (m.find()) {
            out.append(s, last, m.start()).append(f.apply(m));
            last = m.end();
        }
        return out.append(s.substring(last)).toString();
    }

    /** Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first
     *  so the entities we emit are never re-escaped. */
    static String encodeHtml(String text) {
        return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
                .replace("'", "&apos;").replace("\"", "&quot;");
    }

    /** Inline pass: code spans first (placeholder-protected), then images,
     *  links, bold, italic, strikethrough — non-greedy pairs. */
    private static String renderInline(String s) {
        List<String> codes = new ArrayList<>();
        String text = replaceAll(s, CODE_SPAN, m -> {
            codes.add("<code>" + encodeHtml(m.group(1)) + "</code>");
            return "\u0000" + (codes.size() - 1) + "\u0000";
        });
        text = encodeHtml(text);
        text = replaceAll(text, IMAGE, m -> "<img src=\"" + m.group(2) + "\" alt=\"" + m.group(1) + "\">");
        text = replaceAll(text, LINK, m -> "<a href=\"" + m.group(2) + "\">" + m.group(1) + "</a>");
        text = replaceAll(text, Pattern.compile("\\*\\*([^*]+)\\*\\*"), m -> "<strong>" + m.group(1) + "</strong>");
        text = replaceAll(text, Pattern.compile("__([^_]+)__"), m -> "<strong>" + m.group(1) + "</strong>");
        text = replaceAll(text, Pattern.compile("\\*([^*]+)\\*"), m -> "<em>" + m.group(1) + "</em>");
        text = replaceAll(text, Pattern.compile("_([^_]+)_"), m -> "<em>" + m.group(1) + "</em>");
        text = replaceAll(text, Pattern.compile("~~([^~]+)~~"), m -> "<del>" + m.group(1) + "</del>");
        return replaceAll(text, Pattern.compile("\u0000(\\d+)\u0000"),
                m -> codes.get(Integer.parseInt(m.group(1))));
    }

    /** True when a line STARTS a new block — the paragraph terminator. Any new
     *  block type must register here and in the renderBlock dispatch below. */
    private static boolean isBlockStart(String line) {
        return HEADING.matcher(line).find() || HR.matcher(line).find()
                || line.startsWith("```") || line.startsWith("> ")
                || UL.matcher(line).find() || OL.matcher(line).find();
    }

    /** Render consecutive lines (one blank-line-separated chunk). */
    private static void renderBlock(List<String> lines, List<String> out) {
        int i = 0;
        while (i < lines.size()) {
            String line = lines.get(i);

            Matcher heading = HEADING.matcher(line);
            if (heading.find()) {
                int level = heading.group(1).length();
                out.add("<h" + level + ">" + renderInline(heading.group(2).trim()) + "</h" + level + ">");
                i++;
                continue;
            }

            if (HR.matcher(line).find()) {
                out.add("<hr>");
                i++;
                continue;
            }

            if (line.startsWith("```")) {
                String lang = line.substring(3).trim();
                List<String> body = new ArrayList<>();
                i++;
                while (i < lines.size() && !lines.get(i).startsWith("```")) {
                    body.add(lines.get(i));
                    i++;
                }
                i++; // past the closing fence (or past the end of an unclosed fence)
                String cls = lang.isEmpty() ? "" : " class=\"language-" + encodeHtml(lang) + "\"";
                out.add("<pre><code" + cls + ">" + encodeHtml(String.join("\n", body)) + "</code></pre>");
                continue;
            }

            if (line.startsWith("> ")) {
                List<String> quoted = new ArrayList<>();
                while (i < lines.size() && lines.get(i).startsWith("> ")) {
                    quoted.add(lines.get(i).substring(2));
                    i++;
                }
                List<String> inner = new ArrayList<>();
                renderBlock(quoted, inner);
                out.add("<blockquote>\n" + String.join("\n", inner) + "\n</blockquote>");
                continue;
            }

            if (UL.matcher(line).find()) {
                List<String> items = new ArrayList<>();
                while (i < lines.size() && UL.matcher(lines.get(i)).find()) {
                    items.add("<li>" + renderInline(lines.get(i).replaceFirst("^[-*+] ", "")) + "</li>");
                    i++;
                }
                out.add("<ul>\n" + String.join("\n", items) + "\n</ul>");
                continue;
            }

            if (OL.matcher(line).find()) {
                List<String> items = new ArrayList<>();
                while (i < lines.size() && OL.matcher(lines.get(i)).find()) {
                    Matcher om = OL.matcher(lines.get(i));
                    om.find();
                    items.add("<li>" + renderInline(lines.get(i).substring(om.end())) + "</li>");
                    i++;
                }
                out.add("<ol>\n" + String.join("\n", items) + "\n</ol>");
                continue;
            }

            List<String> para = new ArrayList<>();
            while (i < lines.size() && !isBlockStart(lines.get(i))) {
                para.add(renderInline(lines.get(i).trim()));
                i++;
            }
            out.add("<p>" + String.join("\n", para) + "</p>");
        }
    }

    /** Convert the supported Markdown subset to HTML. Never fails. */
    static Result markdownToHtml(String raw) {
        String text = (raw == null ? "" : raw.replaceAll("\r\n?", "\n")).trim();
        if (text.isEmpty()) return new Result("", null); // NOT an error
        List<String> out = new ArrayList<>();
        for (String block : text.split("\n{2,}")) {
            List<String> lines = new ArrayList<>();
            for (String l : block.split("\n")) {
                if (!l.trim().isEmpty()) lines.add(l);
            }
            renderBlock(lines, out);
        }
        return new Result(String.join("\n", out), null);
    }
}

// Example:
// MarkdownToHtml.markdownToHtml("## Hello *world*").output
// → "<h2>Hello <em>world</em></h2>"
// MarkdownToHtml.markdownToHtml("```js\nconst x = 1; // <b>\n```").output
// → "<pre><code class=\"language-js\">const x = 1; // &lt;b&gt;</code></pre>"
// MarkdownToHtml.markdownToHtml("<script>alert(1)</script>").output
// → "<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>"

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →