Skip to content

HTML to Markdown Converter — Java source

Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.

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

// html-to-markdown — supported HTML subset → Markdown converter.
//
// Language: Java (17, standard library only).
// CosmoDev polyglot showcase port of the `html-to-markdown` tool.
// Ported from src/lib/html-to-markdown.ts (the canonical TypeScript lib);
// the Go CLI twin lives at cli/html-to-markdown/html-to-markdown.go.
//
// A hand-rolled single-scan tag parser (no DOM) builds a node forest, then a
// renderer emits Markdown blocks: h1-h6, p/div/blockquote, pre fences with
// the language taken from class="language-*", ul/ol with 2-space (ul) and
// 4-space (ol) nested indent, hr, br as two-spaces-newline; inline marks
// strong/b/em/i/del/s/code render empty emphasis as nothing, links keep
// verbatim titles, images decode alt/src. Unknown tags are transparent,
// stray closers are ignored, unclosed tags auto-close at EOF, and text nodes
// backslash-escape \ ` * _ [ ]. A '<' with no closing '>' is the one error
// ("Unclosed tag").
//
// Entity decode: the JDK has no WHATWG table, so this port hand-rolls the
// fallback — numeric (&#NN; / &#xHH;) plus the six named entities (amp lt gt
// quot apos nbsp), single pass, no double-decode ("x &amp;lt; y" stays
// "x &lt; y"; the Go twin uses the full stdlib html.UnescapeString table).
//
// display source — part of CosmoDev's polyglot tool pages.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final class HtmlToMarkdownTool {
    private HtmlToMarkdownTool() {}

    /** Result mirrors HtmlToMarkdownResult in the TS lib: on success output
     * is set and error is null; on failure output is empty. Empty or
     * whitespace-only input is NOT an error — the tool shows nothing. */
    record Result(String output, String error) {
        static Result ok(String output) { return new Result(output, null); }
        static Result err(String message) { return new Result("", message); }
    }

    private static final String UNCLOSED_TAG = "Unclosed tag";

    /** VOID in the TS lib — tags that never open a scope. */
    private static final Set<String> VOID =
            Set.of("br", "hr", "img", "meta", "link", "input", "source");

    /** BLOCK_TAGS in the TS lib — tags rendered as Markdown blocks. */
    private static final Set<String> BLOCK_TAGS = Set.of(
            "p", "div", "blockquote", "pre", "ul", "ol", "hr",
            "h1", "h2", "h3", "h4", "h5", "h6");

    /** The six named entities decoded by the hand-rolled scanner. */
    private static final Map<String, String> NAMED = Map.of(
            "amp", "&", "lt", "<", "gt", ">", "quot", "\"", "apos", "'", "nbsp", " ");

    private static final Pattern TAG_NAME = Pattern.compile("^([a-zA-Z][a-zA-Z0-9-]*)");
    private static final Pattern ATTR =
            Pattern.compile("([a-zA-Z-]+)(?:\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+))?");
    private static final Pattern LANG_CLASS = Pattern.compile("language-([\\w-]+)");
    private static final Pattern MD_ESCAPE = Pattern.compile("[\\\\`*_\\[\\]]");
    private static final Pattern WS_RUN = Pattern.compile("\\s+");

    /** One forest node: text (elem false) or element. */
    private static final class Node {
        final boolean elem;
        String text = "";
        String tag = "";
        final Map<String, String> attrs = new HashMap<>();
        final List<Node> children = new ArrayList<>();

        Node(String text) { this.elem = false; this.text = text; }
        private Node() { this.elem = true; }
        static Node ofText(String text) { return new Node(text); }
        static Node ofElem(String tag) { Node n = new Node(); n.tag = tag; return n; }
    }

    /** Append sink: the current open element's children, else the roots. */
    private static List<Node> top(List<Node> roots, List<Node> stack) {
        return stack.isEmpty() ? roots : stack.get(stack.size() - 1).children;
    }

    /** Decode one character reference starting at s[i] == '&'. Returns the
     * decoded string with its new index in end[0], or null when the '&' is
     * not a well-known reference (emit it literally — decode never fails). */
    private static String decodeReference(String s, int i, int[] end) {
        int len = s.length();
        int p = i + 1;
        if (p < len && s.charAt(p) == '#') { // &#NN; / &#xHH;
            boolean hex = p + 1 < len && (s.charAt(p + 1) == 'x' || s.charAt(p + 1) == 'X');
            int d = hex ? p + 2 : p + 1;
            int start = d;
            while (d < len && isRefDigit(s.charAt(d), hex)) d++;
            if (d > start && d < len && s.charAt(d) == ';') {
                try {
                    int num = Integer.parseInt(s.substring(start, d), hex ? 16 : 10);
                    if ((num >= 0xD800 && num <= 0xDFFF) || num > 0x10FFFF) return null;
                    end[0] = d + 1;
                    return new StringBuilder().appendCodePoint(num).toString();
                } catch (NumberFormatException ignored) {
                    return null; // overflow → out of range → keep the reference
                }
            }
            return null;
        }
        // &name; — first char a letter, rest letters/digits (TS [A-Za-z][A-Za-z0-9]*).
        if (p < len && isAsciiLetter(s.charAt(p))) {
            int d = p + 1;
            while (d < len && (isAsciiLetter(s.charAt(d)) || isAsciiDigit(s.charAt(d)))) d++;
            if (d < len && s.charAt(d) == ';') {
                String named = NAMED.get(s.substring(p, d));
                if (named != null) { end[0] = d + 1; return named; }
            }
        }
        return null;
    }

    private static boolean isAsciiLetter(char c) {
        return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
    }

    private static boolean isAsciiDigit(char c) { return c >= '0' && c <= '9'; }

    private static boolean isRefDigit(char c, boolean hex) {
        return isAsciiDigit(c) || (hex && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')));
    }

    /** Resolve character references in one pass — no double-decode:
     * "x &amp;lt; y" stays "x &lt; y". Unknown refs pass through. */
    private static String decodeEntities(String s) {
        StringBuilder b = new StringBuilder(s.length());
        int i = 0;
        int[] end = new int[1];
        while (i < s.length()) {
            char c = s.charAt(i);
            if (c == '&') {
                String rep = decodeReference(s, i, end);
                if (rep != null) { b.append(rep); i = end[0]; continue; }
            }
            b.append(c);
            i++;
        }
        return b.toString();
    }

    /** Backslash-escape the Markdown-significant \ ` * _ [ ]. */
    private static String escapeMarkdown(String s) {
        return MD_ESCAPE.matcher(s).replaceAll("\\\\$0");
    }

    /** Collapse any run of whitespace to a single space (TS \s+ pass; NBSP
     * is JS \s but not Java \s, so normalize it explicitly first). */
    private static String collapseWhitespace(String s) {
        return WS_RUN.matcher(s.replace("\u00a0", " ")).replaceAll(" ");
    }

    /** Parse into a node forest. Attribute values may be double-quoted,
     * single-quoted or bare; a quoted value may contain '>'. */
    private record ParseResult(List<Node> roots, String error) {}

    private static ParseResult parseHtml(String raw) {
        List<Node> roots = new ArrayList<>();
        List<Node> stack = new ArrayList<>();
        int i = 0;
        int len = raw.length();
        while (i < len) {
            int lt = raw.indexOf('<', i);
            if (lt == -1) {
                top(roots, stack).add(Node.ofText(raw.substring(i)));
                break;
            }
            if (lt > i) top(roots, stack).add(Node.ofText(raw.substring(i, lt)));
            // Find the tag's '>', skipping quoted attribute values.
            int j = lt + 1;
            char quote = 0;
            while (j < len && (raw.charAt(j) != '>' || quote != 0)) {
                char c = raw.charAt(j);
                if (quote == 0 && (c == '"' || c == '\'')) quote = c;
                else if (quote != 0 && c == quote) quote = 0;
                j++;
            }
            if (j >= len) return new ParseResult(null, UNCLOSED_TAG);
            String inner = raw.substring(lt + 1, j).strip();
            i = j + 1;

            if (inner.startsWith("!--")) continue; // comment
            if (inner.startsWith("!")) continue; // doctype
            boolean closing = inner.startsWith("/");
            String body = closing ? inner.substring(1) : inner.replaceFirst("/$", "");
            Matcher nm = TAG_NAME.matcher(body);
            if (!nm.find()) continue; // not a real tag — browsers would show it as text; we drop it
            String tag = nm.group(1).toLowerCase(Locale.ROOT);

            if (closing) {
                for (int k = stack.size() - 1; k >= 0; k--) {
                    if (stack.get(k).tag.equals(tag)) {
                        stack.subList(k, stack.size()).clear();
                        break;
                    }
                }
                continue;
            }

            Node elem = Node.ofElem(tag);
            Matcher am = ATTR.matcher(body);
            while (am.find()) {
                // Values stay RAW here; href/src/alt are entity-decoded at
                // use, titles stay verbatim. The strip mirrors TS
                // am[2].slice(1, -1): quoted values lose their quotes, bare
                // values lose their first and last characters (same quirk
                // the Go twin keeps for lock-step).
                String val = am.group(2);
                String stripped = val != null && val.length() >= 2
                        ? val.substring(1, val.length() - 1) : "";
                elem.attrs.put(am.group(1).toLowerCase(Locale.ROOT), stripped);
            }
            top(roots, stack).add(elem);
            if (!VOID.contains(tag) && !body.endsWith("/")) stack.add(elem);
        }
        return new ParseResult(roots, null);
    }

    private static boolean isBlock(Node n) {
        return n.elem && BLOCK_TAGS.contains(n.tag);
    }

    /** Inline content of one block: marks, links, images, escaped text. */
    private static String renderInline(List<Node> nodes) {
        StringBuilder out = new StringBuilder();
        for (Node n : nodes) {
            if (!n.elem) {
                out.append(collapseWhitespace(escapeMarkdown(decodeEntities(n.text))));
            } else {
                switch (n.tag) {
                    case "br" -> out.append("  \n");
                    case "strong", "b" -> {
                        String inner = renderInline(n.children).strip();
                        if (!inner.isEmpty()) out.append("**").append(inner).append("**"); // empty emphasis renders as nothing
                    }
                    case "em", "i" -> {
                        String inner = renderInline(n.children).strip();
                        if (!inner.isEmpty()) out.append("*").append(inner).append("*");
                    }
                    case "del", "s" -> {
                        String inner = renderInline(n.children).strip();
                        if (!inner.isEmpty()) out.append("~~").append(inner).append("~~");
                    }
                    case "code" -> {
                        String inner = renderInline(n.children).strip();
                        if (!inner.isEmpty()) out.append("`").append(inner).append("`");
                    }
                    case "a" -> {
                        String href = decodeEntities(n.attrs.getOrDefault("href", ""));
                        String title = n.attrs.getOrDefault("title", "").isEmpty()
                                ? "" : " \"" + n.attrs.get("title") + "\"";
                        String label = renderInline(n.children).strip();
                        if (label.isEmpty()) label = href;
                        out.append("[").append(label).append("](").append(href).append(title).append(")");
                    }
                    case "img" -> {
                        String alt = escapeMarkdown(decodeEntities(n.attrs.getOrDefault("alt", ""))).strip();
                        out.append("![").append(alt).append("](")
                                .append(decodeEntities(n.attrs.getOrDefault("src", ""))).append(")");
                    }
                    default -> out.append(renderInline(n.children)); // span and unknown tags are transparent
                }
            }
        }
        return out.toString();
    }

    /** Concatenate the entity-decoded text under nodes (pre content only). */
    private static String textOf(List<Node> nodes) {
        StringBuilder b = new StringBuilder();
        for (Node c : nodes) {
            b.append(c.elem ? textOf(c.children) : decodeEntities(c.text));
        }
        return b.toString();
    }

    /** Render a sequence of nodes as Markdown blocks. */
    private static List<String> renderBlocks(List<Node> nodes) {
        List<String> out = new ArrayList<>();
        List<Node> para = new ArrayList<>();
        Runnable[] flushHolder = new Runnable[1];
        flushHolder[0] = () -> {
            if (!para.isEmpty()) {
                String text = renderInline(para).strip();
                if (!text.isEmpty()) out.add(text);
                para.clear();
            }
        };
        Runnable flush = flushHolder[0];
        for (Node n : nodes) {
            if (!isBlock(n)) {
                para.add(n);
                continue;
            }
            flush.run();
            switch (n.tag) {
                case "hr" -> out.add("---");
                case "p" -> {
                    String text = renderInline(n.children).strip();
                    if (!text.isEmpty()) out.add(text);
                }
                case "div" -> out.addAll(renderBlocks(n.children));
                case "blockquote" -> {
                    String inner = String.join("\n\n", renderBlocks(n.children));
                    List<String> lines = new ArrayList<>();
                    for (String l : inner.split("\n", -1)) {
                        lines.add(l.isEmpty() ? ">" : "> " + l);
                    }
                    out.add(String.join("\n", lines));
                }
                case "pre" -> {
                    Node codeElem = null;
                    for (Node c : n.children) {
                        if (c.elem && c.tag.equals("code")) { codeElem = c; break; }
                    }
                    String lang = "";
                    if (codeElem != null) {
                        Matcher lm = LANG_CLASS.matcher(codeElem.attrs.getOrDefault("class", ""));
                        if (lm.find()) lang = lm.group(1);
                    }
                    String body = textOf((codeElem != null ? codeElem : n).children)
                            .replaceFirst("\\n+$", "");
                    out.add("```" + lang + "\n" + body + "\n```");
                }
                case "ul", "ol" -> out.add(renderList(n, 0));
                default -> { // h1-h6
                    int level = n.tag.length() >= 2 && n.tag.charAt(1) >= '1' && n.tag.charAt(1) <= '6'
                            ? n.tag.charAt(1) - '0' : 0;
                    out.add("#".repeat(level) + " " + renderInline(n.children).strip());
                }
            }
        }
        flush.run();
        return out;
    }

    /** ul/ol at nesting depth: 2-space indent under ul, 4-space under ol,
     * numbering restarted per list. */
    private static String renderList(Node list, int depth) {
        List<Node> items = new ArrayList<>();
        for (Node c : list.children) {
            if (c.elem && c.tag.equals("li")) items.add(c);
        }
        boolean ordered = list.tag.equals("ol");
        List<String> lines = new ArrayList<>();
        for (int idx = 0; idx < items.size(); idx++) {
            Node li = items.get(idx);
            String marker = ordered ? (idx + 1) + "." : "-";
            String indent = " ".repeat(depth == 0 ? 0 : ordered ? 4 : 2);
            // Split li children into inline content + nested lists.
            List<Node> inline = new ArrayList<>();
            List<String> nested = new ArrayList<>();
            for (Node c : li.children) {
                if (c.elem && (c.tag.equals("ul") || c.tag.equals("ol"))) {
                    nested.add(renderList(c, depth + 1));
                } else {
                    inline.add(c);
                }
            }
            String text = renderInline(inline).strip();
            lines.add(text.isEmpty() ? indent + marker : indent + marker + " " + text);
            lines.addAll(nested);
        }
        return String.join("\n", lines);
    }

    /** Convert the supported HTML subset to Markdown. Never throws — the
     * result carries output/error, mirroring HtmlToMarkdownResult. */
    static Result htmlToMarkdown(String raw) {
        if (raw.strip().isEmpty()) return Result.ok("");
        ParseResult parsed = parseHtml(raw);
        if (parsed.error() != null) return Result.err(parsed.error());
        return Result.ok(String.join("\n\n", renderBlocks(parsed.roots())));
    }

    public static void main(String[] args) {
        Result r = htmlToMarkdown("<h1>Title</h1><p>a &amp; <b>b</b></p><ul><li>x<ul><li>y</li></ul></li></ul>");
        System.out.println(r.output());
        System.out.println("error: " + r.error());
    }
}

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 →