Skip to content
Java project #20Advanced

Markdown to HTML Converter

A line-based Markdown parser with headings and ids, lists, task lists, quotes, fenced code, inline formatting, HTML escaping and unsafe-link filtering, plus a table of contents.

Estimated time
~7 hours to build
Files
6 files · 394 lines
Technologies
Java 21, java.util.regex, StringBuilder, Enums

Introduction

Markdown converters are small compilers: a block-level state machine decides what each line is, and an inline pass turns **bold** and links into tags. Getting the details right — escaping HTML, protecting code spans, rejecting javascript: links — is where the real learning is.

Problem statement

Read Markdown from standard input and print HTML. Support ATX headings with unique, URL-friendly ids; paragraphs joined across lines; ordered, unordered and task lists; block quotes; horizontal rules; fenced code blocks with a language class (contents escaped, not formatted); and inline code, bold, italic, strikethrough, links and images. Escape all HTML special characters, allow only http(s), mailto and relative URLs, and finish with a table of contents and line statistics in an HTML comment.

Objectives

  • Build a block-level state machine
  • Apply ordered regular-expression transformations safely
  • Protect code spans with placeholders
  • Sanitise user-provided URLs

Features

  • Headings with de-duplicated ids and a TOC
  • Lists, task lists, quotes, rules and code blocks
  • Inline formatting with correct nesting order
  • HTML escaping and javascript: link blocking

Concepts demonstrated

  • Parsing
  • State machines
  • Escaping and sanitisation
  • Regular expressions
  • Placeholders

System architecture

MarkdownConverter keeps the currently open block (NONE, PARAGRAPH, UL, OL, QUOTE or CODE). Each line either continues that block or closes it and opens another; close() emits the closing tag. Headings get ids by lower-casing and replacing non-alphanumerics with hyphens, with -2, -3 suffixes for repeats. Inline.render first swaps code spans for placeholders, escapes the rest, applies images before links (so ![..](..) isn't treated as a link), then bold, italic and strikethrough, and finally restores the code spans.

Folder structure

TextProject tree
markdown-to-html/
├── README.md
├── src/Inline.java
├── src/Main.java
├── src/MarkdownConverter.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Inline.java

61 lines
Javasrc/Inline.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Converts inline Markdown (code spans, links, images, bold, italic, strikethrough) to HTML.
* Text is HTML-escaped first; code spans are protected so their contents aren't formatted.
*/
public final class Inline {
private static final Pattern CODE = Pattern.compile("`([^`]+)`");
private static final Pattern IMAGE = Pattern.compile("!\\[([^\\]]*)]\\(([^)\\s]+)\\)");
private static final Pattern LINK = Pattern.compile("\\[([^\\]]+)]\\(([^)\\s]+)\\)");
private static final Pattern BOLD = Pattern.compile("\\*\\*(.+?)\\*\\*");
private static final Pattern ITALIC = Pattern.compile("(?<![*\\w])\\*(?!\\s)(.+?)(?<!\\s)\\*(?![*\\w])");
private static final Pattern STRIKE = Pattern.compile("~~(.+?)~~");
private Inline() { }
public static String escape(String s) {
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
/** Only http(s), mailto and relative URLs are allowed; anything else (e.g. javascript:) becomes "#". */
static String safeUrl(String url) {
String lower = url.toLowerCase();
boolean ok = lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("mailto:") || !lower.contains(":");
return ok ? url : "#";
}
public static String render(String text) {
// 1. Pull out code spans and replace them with placeholders so nothing inside is touched.
java.util.List<String> codes = new java.util.ArrayList<>();
Matcher m = CODE.matcher(text);
StringBuilder sb = new StringBuilder();
while (m.find()) {
codes.add("<code>" + escape(m.group(1)) + "</code>");
m.appendReplacement(sb, "\u0000" + (codes.size() - 1) + "\u0000");
}
m.appendTail(sb);
// 2. Escape HTML, then apply the other inline rules.
String s = escape(sb.toString());
s = replace(IMAGE, s, mm -> "<img src=\"" + safeUrl(mm.group(2)) + "\" alt=\"" + mm.group(1) + "\">");
s = replace(LINK, s, mm -> "<a href=\"" + safeUrl(mm.group(2)) + "\">" + mm.group(1) + "</a>");
s = replace(BOLD, s, mm -> "<strong>" + mm.group(1) + "</strong>");
s = replace(ITALIC, s, mm -> "<em>" + mm.group(1) + "</em>");
s = replace(STRIKE, s, mm -> "<del>" + mm.group(1) + "</del>");
// 3. Put the code spans back.
for (int i = 0; i < codes.size(); i++) s = s.replace("\u0000" + i + "\u0000", codes.get(i));
return s;
}
private static String replace(Pattern p, String s, java.util.function.Function<Matcher, String> f) {
Matcher m = p.matcher(s);
StringBuilder sb = new StringBuilder();
while (m.find()) m.appendReplacement(sb, Matcher.quoteReplacement(f.apply(m)));
m.appendTail(sb);
return sb.toString();
}
}

What each file does

src/Inline.java
Escaping, safe URLs and the inline rules (code, images, links, bold, italic, strikethrough).
src/MarkdownConverter.java
The block state machine, heading ids and the table of contents.
src/Main.java
Reads standard input and prints the HTML and statistics.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
<h1 id="java-notes">Java Notes</h1>
<p>Java is <strong>statically typed</strong> and <em>object-oriented</em>. It runs on the <code>JVM</code> &amp; is <del>slow</del> fast.</p>
<h2 id="getting-started">Getting Started</h2>
<ol>
<li>Install a JDK</li>
<li>Write <code>Main.java</code></li>
<li>Run <code>java Main.java</code></li>
</ol>
<ul>
<li>Use <strong>records</strong> for data</li>
<li>Read the <a href="https://docs.oracle.com/en/java/">official docs</a></li>
<li>Never click <a href="#">this</a></li>
</ul>
<h2 id="example">Example</h2>
<pre><code class="language-java">if (a &lt; b &amp;&amp; list.size() &gt; 0) {
System.out.println(&quot;&lt;done&gt;&quot;);
}
</code></pre>
<blockquote>
<p>Tip: <code>var</code> is not dynamic typing.</p>
<p>It infers a <strong>static</strong> type.</p>
</blockquote>
<hr>
<h2 id="example-2">Example</h2>
<ul>
<li><input type="checkbox" disabled checked> Learn classes</li>
<li><input type="checkbox" disabled> Learn streams</li>
</ul>
<p><img src="images/java.png" alt="logo"> Paragraph after an image with 2 * 3 = 6 and a_b_c.</p>
<!-- table of contents
Java Notes (#java-notes)
Getting Started (#getting-started)
Example (#example)
Example (#example-2)
34 Markdown lines -> 29 HTML lines (17 starting with a tag)
-->
Input
# Java Notes

Java is **statically typed** and *object-oriented*.
It runs on the `JVM` & is ~~slow~~ fast.

## Getting Started

1. Install a JDK
2. Write `Main.java`
3. Run `java Main.java`

- Use **records** for data
- Read the [official docs](https://docs.oracle.com/en/java/)
* Never click [this](javascript:stealCookies)

## Example

```java
if (a < b && list.size() > 0) {
    System.out.println("<done>");
}
```

> Tip: `var` is not dynamic typing.
> It infers a **static** type.

---

## Example

- [x] Learn classes
- [ ] Learn streams

![logo](images/java.png) Paragraph after an image with 2 * 3 = 6 and a_b_c.

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • & and < are escaped everywhere; inside the fenced Java block nothing is formatted.
  • The javascript: link is rewritten to #.
  • The second ## Example heading gets the id example-2.

Common errors

Underscores in a_b_c become italics

Require word boundaries around emphasis markers, as the ITALIC pattern does with look-arounds.

Code examples show <strong> tags

Extract code spans before applying inline rules and restore them afterwards.

Possible improvements

  • Nested lists by indentation
  • Tables in the GitHub Markdown style
  • Wrap the output in a full HTML page with CSS

Additional challenges

  1. 1Add reference-style links [text][id].
  2. 2Support headings written with === and --- underlines.
  3. 3Write unit tests for each rule with JUnit.

Built and tested it yourself? Mark it to update your dashboard.