Files
Library/include/Void/Text/Markdown.hpp
T
faumaray e6745ac8cb Text: add Markdown link/image destination resolver hook
MarkdownOptions::resolver rewrites a validated link/image destination
before it is escaped and emitted, once per destination in document order.
Unsafe schemes (javascript:, data:, ...) are still dropped and never reach
the resolver. A throwing resolver falls back to the original destination;
an overlong result is bounded by MarkdownLimits::max_output.

Closes #59
2026-12-04 21:48:20 +03:00

1162 lines
34 KiB
C++

#pragma once
#include <Void/Text/Html.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <functional>
#include <string>
#include <string_view>
namespace Void::Text
{
// ── Bounded CommonMark-subset parser + safe HTML renderer ────────────────────
//
// Supported block constructs: ATX headings, setext headings, paragraphs,
// fenced code blocks (``` and ~~~), thematic breaks, block quotes and tight or
// loose bullet/ordered lists.
//
// Supported inline constructs: emphasis/strong (* _ ** __), code spans,
// inline links and images ([text](url "title"), ![alt](url)), autolinks
// (<https://…>), backslash escapes and hard line breaks.
//
// Everything else is treated as literal text: raw HTML is never passed
// through, it is escaped. Link/image destinations are allow-listed (http,
// https, mailto, or a relative URL); unsafe schemes such as javascript: and
// data: are dropped, keeping only the label text.
//
// An optional MarkdownOptions::resolver can rewrite a destination (e.g. a
// relative wiki link to a bounded server route) after the allow-list check and
// before escaping. It is called once per emitted link/image destination, in
// document order; its result is escaped like any other destination. Unsafe
// destinations are dropped regardless of the resolver, which is never called
// for them. If the resolver throws, the original validated destination is
// used; an overlong result is reported as MarkdownError::Code::output_limit.
//
// All work is bounded by MarkdownLimits: input size, output size, block count
// and nesting depth.
struct MarkdownLimits
{
std::size_t max_input = 1024 * 1024;
std::size_t max_output = 8 * 1024 * 1024;
std::size_t max_blocks = 16384;
std::size_t max_depth = 32;
};
struct MarkdownError
{
enum class Code : std::uint8_t
{
input_limit,
output_limit,
block_limit,
depth_limit,
};
Code code{Code::block_limit};
std::size_t offset{0};
[[nodiscard]] constexpr bool operator==(const MarkdownError&) const noexcept = default;
};
// Rewrites a validated link/image destination. `image` is true for images.
// The returned string is escaped before being emitted.
using MarkdownResolver = std::function<std::string(std::string_view destination, bool image)>;
struct MarkdownOptions
{
MarkdownLimits limits{};
bool allow_images = true;
MarkdownResolver resolver{};
};
namespace Detail
{
inline constexpr std::size_t npos = std::string_view::npos;
// ── ASCII helpers ─────────────────────────────────────────────────────────────
[[nodiscard]] inline bool is_space_or_tab(char c) noexcept
{
return c == ' ' || c == '\t';
}
[[nodiscard]] inline bool is_blank(std::string_view s) noexcept
{
for (const char c : s) {
if (!is_space_or_tab(c) && c != '\r') {
return false;
}
}
return true;
}
[[nodiscard]] inline bool is_alnum_ascii(char c) noexcept
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
[[nodiscard]] inline char ascii_lower(char c) noexcept
{
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c - 'A' + 'a') : c;
}
[[nodiscard]] inline bool ascii_iequals(std::string_view a, std::string_view b) noexcept
{
if (a.size() != b.size()) {
return false;
}
for (std::size_t i = 0; i < a.size(); ++i) {
if (ascii_lower(a[i]) != ascii_lower(b[i])) {
return false;
}
}
return true;
}
[[nodiscard]] inline bool is_ascii_punct(char c) noexcept
{
const auto u = static_cast<unsigned char>(c);
return (u >= 33 && u <= 47) || (u >= 58 && u <= 64) || (u >= 91 && u <= 96) ||
(u >= 123 && u <= 126);
}
[[nodiscard]] inline std::string_view trim_left(std::string_view s) noexcept
{
while (!s.empty() && is_space_or_tab(s.front())) {
s.remove_prefix(1);
}
return s;
}
[[nodiscard]] inline std::string_view trim_right(std::string_view s) noexcept
{
while (!s.empty() && is_space_or_tab(s.back())) {
s.remove_suffix(1);
}
return s;
}
[[nodiscard]] inline std::string_view trim(std::string_view s) noexcept
{
return trim_right(trim_left(s));
}
// Column width of leading whitespace (tab = 4).
[[nodiscard]] inline std::size_t indent_of(std::string_view s) noexcept
{
std::size_t col = 0;
for (const char c : s) {
if (c == ' ') {
++col;
} else if (c == '\t') {
col += 4;
} else {
break;
}
}
return col;
}
// ── Line helpers ─────────────────────────────────────────────────────────────
[[nodiscard]] inline std::string_view first_line(std::string_view rest) noexcept
{
const std::size_t nl = rest.find('\n');
std::string_view line = (nl == npos) ? rest : rest.substr(0, nl);
if (!line.empty() && line.back() == '\r') {
line.remove_suffix(1);
}
return line;
}
inline void consume_line(std::string_view& rest) noexcept
{
const std::size_t nl = rest.find('\n');
if (nl == npos) {
rest = {};
} else {
rest.remove_prefix(nl + 1);
}
}
// ── Bounded writer ───────────────────────────────────────────────────────────
struct MarkdownWriter
{
std::string out;
std::size_t limit = 0;
bool failed = false;
MarkdownError error{};
void fail(MarkdownError::Code code, std::size_t offset) noexcept
{
if (!failed) {
failed = true;
error = MarkdownError{code, offset};
}
}
void append(std::string_view s)
{
if (failed) {
return;
}
if (s.size() > limit || out.size() > limit - s.size()) {
fail(MarkdownError::Code::output_limit, out.size());
return;
}
out.append(s);
}
void append(char c)
{
if (failed) {
return;
}
if (out.size() >= limit) {
fail(MarkdownError::Code::output_limit, out.size());
return;
}
out.push_back(c);
}
};
inline void append_escaped(MarkdownWriter& w, std::string_view s)
{
for (const char c : s) {
switch (c) {
case '&': w.append("&amp;"); break;
case '<': w.append("&lt;"); break;
case '>': w.append("&gt;"); break;
case '"': w.append("&quot;"); break;
case '\'': w.append("&#39;"); break;
default: w.append(c); break;
}
}
}
// ── URL allow-listing ────────────────────────────────────────────────────────
// Decode the handful of entity spellings that can smuggle a ':' past a naive
// scheme check (e.g. `javascript&colon;alert(1)`).
[[nodiscard]] inline std::string decode_scheme_entities(std::string_view s)
{
std::string out;
out.reserve(s.size());
for (std::size_t i = 0; i < s.size();) {
if (s[i] == '&') {
const std::size_t semi = s.find(';', i + 1);
if (semi != npos && semi - i <= 8) {
const std::string_view body = s.substr(i + 1, semi - i - 1);
if (ascii_iequals(body, "colon") || body == "#58" || ascii_iequals(body, "#x3a")) {
out += ':';
i = semi + 1;
continue;
}
}
}
out += s[i++];
}
return out;
}
[[nodiscard]] inline bool url_is_safe(std::string_view url)
{
if (url.empty()) {
return true;
}
for (const char c : url) {
const auto u = static_cast<unsigned char>(c);
if (u < 0x20 || u == 0x7F || c == ' ') {
return false;
}
}
const std::string normalized = decode_scheme_entities(url);
const std::size_t colon = normalized.find(':');
const std::size_t sep = normalized.find_first_of("/?#");
if (colon != std::string::npos && (sep == std::string::npos || colon < sep)) {
const std::string_view scheme = std::string_view{normalized}.substr(0, colon);
return ascii_iequals(scheme, "http") || ascii_iequals(scheme, "https") ||
ascii_iequals(scheme, "mailto");
}
return true;
}
// ── Block line classifiers ──────────────────────────────────────────────────
[[nodiscard]] inline bool is_fence_open(std::string_view line,
char& fence_char,
std::size_t& fence_len,
std::string_view& info)
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
if (i >= line.size()) {
return false;
}
const char c = line[i];
if (c != '`' && c != '~') {
return false;
}
std::size_t n = 0;
while (i + n < line.size() && line[i + n] == c) {
++n;
}
if (n < 3) {
return false;
}
const std::string_view rest = line.substr(i + n);
if (c == '`' && rest.find('`') != npos) {
return false;
}
fence_char = c;
fence_len = n;
info = rest;
return true;
}
[[nodiscard]] inline bool is_fence_close(std::string_view line, char c, std::size_t len)
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
std::size_t n = 0;
while (i + n < line.size() && line[i + n] == c) {
++n;
}
if (n < len) {
return false;
}
return is_blank(line.substr(i + n));
}
// Returns 1..6 for an ATX heading, else 0.
[[nodiscard]] inline int atx_heading(std::string_view line) noexcept
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
std::size_t n = 0;
while (i + n < line.size() && line[i + n] == '#') {
++n;
}
if (n == 0 || n > 6) {
return 0;
}
if (i + n < line.size() && line[i + n] != ' ') {
return 0;
}
return static_cast<int>(n);
}
[[nodiscard]] inline std::string_view heading_content(std::string_view line, int level)
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
i += static_cast<std::size_t>(level);
if (i < line.size() && line[i] == ' ') {
++i;
}
std::string_view content = trim_right(line.substr(i));
std::size_t end = content.size();
while (end > 0 && content[end - 1] == '#') {
--end;
}
if (end < content.size() && (end == 0 || content[end - 1] == ' ')) {
content = trim_right(content.substr(0, end));
}
return content;
}
[[nodiscard]] inline bool is_thematic_break(std::string_view line) noexcept
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
char marker = 0;
std::size_t count = 0;
for (; i < line.size(); ++i) {
const char c = line[i];
if (is_space_or_tab(c)) {
continue;
}
if (c != '-' && c != '*' && c != '_') {
return false;
}
if (marker == 0) {
marker = c;
} else if (c != marker) {
return false;
}
++count;
}
return count >= 3;
}
[[nodiscard]] inline bool is_blockquote_line(std::string_view line) noexcept
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
return i < line.size() && line[i] == '>';
}
[[nodiscard]] inline std::string_view strip_blockquote(std::string_view line) noexcept
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
++i; // the '>'
if (i < line.size() && line[i] == ' ') {
++i;
}
return line.substr(i);
}
[[nodiscard]] inline bool parse_list_marker(std::string_view line,
bool& ordered,
int& start,
std::size_t& content_offset) noexcept
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
if (i >= line.size()) {
return false;
}
const char c = line[i];
if (c == '-' || c == '*' || c == '+') {
if (i + 1 >= line.size() || line[i + 1] != ' ') {
return false;
}
ordered = false;
start = 1;
content_offset = i + 2;
return true;
}
if (c >= '0' && c <= '9') {
std::size_t n = 0;
long value = 0;
while (i + n < line.size() && line[i + n] >= '0' && line[i + n] <= '9' && n < 9) {
value = value * 10 + (line[i + n] - '0');
++n;
}
if (n == 0 || i + n >= line.size()) {
return false;
}
const char delim = line[i + n];
if (delim != '.' && delim != ')') {
return false;
}
if (i + n + 1 < line.size() && line[i + n + 1] != ' ') {
return false;
}
ordered = true;
start = static_cast<int>(value);
content_offset = i + n + 1;
if (content_offset < line.size()) {
++content_offset;
}
return true;
}
return false;
}
// Returns 1 for '=', 2 for '-', else 0.
[[nodiscard]] inline int setext_underline_level(std::string_view line) noexcept
{
std::size_t i = 0;
while (i < line.size() && i < 3 && line[i] == ' ') {
++i;
}
if (i >= line.size()) {
return 0;
}
const char c = line[i];
if (c != '=' && c != '-') {
return 0;
}
std::size_t n = 0;
while (i + n < line.size() && line[i + n] == c) {
++n;
}
if (n == 0 || !is_blank(line.substr(i + n))) {
return 0;
}
return c == '=' ? 1 : 2;
}
[[nodiscard]] inline bool starts_block(std::string_view line)
{
char fc = 0;
std::size_t fl = 0;
std::string_view fi;
if (is_fence_open(line, fc, fl, fi)) {
return true;
}
if (atx_heading(line) != 0) {
return true;
}
if (is_thematic_break(line)) {
return true;
}
if (is_blockquote_line(line)) {
return true;
}
bool ordered = false;
int start = 1;
std::size_t offset = 0;
return parse_list_marker(line, ordered, start, offset);
}
[[nodiscard]] inline std::string_view first_word(std::string_view s) noexcept
{
std::size_t i = 0;
while (i < s.size() && is_space_or_tab(s[i])) {
++i;
}
std::size_t n = 0;
while (i + n < s.size() && !is_space_or_tab(s[i + n]) && s[i + n] != '\r') {
++n;
}
return s.substr(i, n);
}
// ── Inline parser ───────────────────────────────────────────────────────────
inline void render_inline(std::string_view s,
MarkdownWriter& w,
const MarkdownOptions& opt,
std::size_t depth);
[[nodiscard]] inline std::size_t run_length(std::string_view s, std::size_t pos, char c) noexcept
{
std::size_t n = 0;
while (pos + n < s.size() && s[pos + n] == c) {
++n;
}
return n;
}
[[nodiscard]] inline std::size_t find_closing_bracket(std::string_view s, std::size_t open) noexcept
{
int level = 0;
for (std::size_t i = open; i < s.size(); ++i) {
const char c = s[i];
if (c == '\\') {
++i;
continue;
}
if (c == '[') {
++level;
} else if (c == ']') {
--level;
if (level == 0) {
return i;
}
}
}
return npos;
}
[[nodiscard]] inline std::size_t find_closing_paren(std::string_view s, std::size_t open) noexcept
{
int level = 0;
for (std::size_t i = open + 1; i < s.size(); ++i) {
const char c = s[i];
if (c == '\\') {
++i;
continue;
}
if (c == '<') {
const std::size_t close = s.find('>', i + 1);
if (close == npos) {
return npos;
}
i = close;
continue;
}
if (c == '(') {
++level;
} else if (c == ')') {
if (level == 0) {
return i;
}
--level;
}
}
return npos;
}
[[nodiscard]] inline bool parse_link_target(std::string_view inside,
std::string& dest,
std::string& title)
{
inside = trim(inside);
if (inside.empty()) {
dest.clear();
return true;
}
std::size_t pos = 0;
if (inside.front() == '<') {
const std::size_t close = inside.find('>', 1);
if (close == npos) {
return false;
}
dest = std::string{inside.substr(1, close - 1)};
pos = close + 1;
} else {
std::size_t level = 0;
std::size_t p = 0;
for (; p < inside.size(); ++p) {
const char c = inside[p];
if (c == '\\' && p + 1 < inside.size()) {
++p;
continue;
}
if (c == '(') {
++level;
} else if (c == ')') {
if (level == 0) {
break;
}
--level;
} else if (is_space_or_tab(c) && level == 0) {
break;
}
}
dest = std::string{inside.substr(0, p)};
pos = p;
}
inside = trim(inside.substr(pos));
if (inside.empty()) {
return true;
}
const char open = inside.front();
char close = open;
if (open == '(') {
close = ')';
} else if (open != '"' && open != '\'') {
return false;
}
if (inside.size() < 2 || inside.back() != close) {
return false;
}
title = std::string{inside.substr(1, inside.size() - 2)};
return true;
}
[[nodiscard]] inline bool is_autolink(std::string_view s)
{
if (s.empty() || s.size() > 255) {
return false;
}
for (const char c : s) {
if (c == ' ' || c == '<' || c == '>' || c == '"') {
return false;
}
}
const std::size_t colon = s.find(':');
if (colon == npos) {
return false;
}
const std::string_view scheme = s.substr(0, colon);
if (!ascii_iequals(scheme, "http") && !ascii_iequals(scheme, "https") &&
!ascii_iequals(scheme, "mailto")) {
return false;
}
return url_is_safe(s);
}
[[nodiscard]] inline bool try_emphasis(std::string_view s,
std::size_t& i,
MarkdownWriter& w,
const MarkdownOptions& opt,
std::size_t depth)
{
const char d = s[i];
const std::size_t run = run_length(s, i, d);
if (d == '_' && i > 0 && is_alnum_ascii(s[i - 1])) {
return false;
}
if (i + run < s.size() && is_space_or_tab(s[i + run])) {
return false;
}
const std::size_t use = run >= 2 ? 2 : 1;
std::size_t j = i + use;
while (j < s.size()) {
if (s[j] == '\\') {
j += 2;
continue;
}
if (s[j] != d) {
++j;
continue;
}
const std::size_t close_run = run_length(s, j, d);
const bool boundary_ok =
(d != '_' || j + close_run >= s.size() || !is_alnum_ascii(s[j + close_run])) &&
(j == 0 || !is_space_or_tab(s[j - 1]));
if (close_run >= use && boundary_ok && j > i + use) {
// For `**…***` (and `***…***`) the extra closing delimiter closes
// an inner emphasis run, so fold it into the inner span.
const std::size_t extra = (use == 2 && close_run >= 3) ? close_run - use : 0;
const std::string_view inner = s.substr(i + use, (j + extra) - (i + use));
w.append(use == 2 ? "<strong>" : "<em>");
render_inline(inner, w, opt, depth + 1);
w.append(use == 2 ? "</strong>" : "</em>");
i = j + use + extra;
return true;
}
j += close_run;
}
return false;
}
// Apply the optional resolver to an already-validated destination. A throwing
// resolver falls back to the original destination; the writer bounds the size
// of whatever comes back.
[[nodiscard]] inline std::string resolve_destination(const MarkdownOptions& opt,
std::string_view destination,
bool image)
{
if (!opt.resolver) {
return std::string{destination};
}
try {
return opt.resolver(destination, image);
} catch (...) {
return std::string{destination};
}
}
[[nodiscard]] inline std::size_t try_link(std::string_view s,
std::size_t open,
MarkdownWriter& w,
const MarkdownOptions& opt,
std::size_t depth,
bool image)
{
const std::size_t close = find_closing_bracket(s, open);
if (close == npos || close + 1 >= s.size() || s[close + 1] != '(') {
return npos;
}
const std::size_t paren = find_closing_paren(s, close + 1);
if (paren == npos) {
return npos;
}
const std::string_view label = s.substr(open + 1, close - open - 1);
std::string dest;
std::string title;
if (!parse_link_target(s.substr(close + 2, paren - close - 2), dest, title)) {
return npos;
}
if (!url_is_safe(dest)) {
render_inline(label, w, opt, depth + 1);
return paren + 1;
}
if (image && !opt.allow_images) {
render_inline(label, w, opt, depth + 1);
return paren + 1;
}
const std::string resolved = resolve_destination(opt, dest, image);
if (image) {
w.append("<img src=\"");
append_escaped(w, resolved);
w.append("\" alt=\"");
append_escaped(w, label);
w.append("\" />");
} else {
w.append("<a href=\"");
append_escaped(w, resolved);
w.append("\"");
if (!title.empty()) {
w.append(" title=\"");
append_escaped(w, title);
w.append("\"");
}
w.append(">");
render_inline(label, w, opt, depth + 1);
w.append("</a>");
}
return paren + 1;
}
inline void render_inline(std::string_view s,
MarkdownWriter& w,
const MarkdownOptions& opt,
std::size_t depth)
{
if (w.failed) {
return;
}
if (depth > opt.limits.max_depth) {
w.fail(MarkdownError::Code::depth_limit, 0);
return;
}
std::size_t i = 0;
while (i < s.size() && !w.failed) {
const char c = s[i];
if (c == '\\' && i + 1 < s.size()) {
if (s[i + 1] == '\n') {
w.append("<br />\n");
i += 2;
continue;
}
if (is_ascii_punct(s[i + 1])) {
append_escaped(w, s.substr(i + 1, 1));
i += 2;
continue;
}
}
if (c == '`') {
const std::size_t run = run_length(s, i, '`');
std::size_t j = i + run;
std::size_t close = npos;
while (j < s.size()) {
if (s[j] == '`') {
const std::size_t m = run_length(s, j, '`');
if (m == run) {
close = j;
break;
}
j += m;
} else {
++j;
}
}
if (close != npos) {
std::string_view code = s.substr(i + run, close - i - run);
if (code.size() >= 2 && code.front() == ' ' && code.back() == ' ' &&
code.find_first_not_of(' ') != npos) {
code.remove_prefix(1);
code.remove_suffix(1);
}
w.append("<code>");
append_escaped(w, code);
w.append("</code>");
i = close + run;
} else {
append_escaped(w, s.substr(i, run));
i += run;
}
continue;
}
if (c == '*' || c == '_') {
if (try_emphasis(s, i, w, opt, depth)) {
continue;
}
append_escaped(w, s.substr(i, 1));
++i;
continue;
}
if (c == '[') {
const std::size_t end = try_link(s, i, w, opt, depth, false);
if (end != npos) {
i = end;
continue;
}
append_escaped(w, s.substr(i, 1));
++i;
continue;
}
if (c == '!' && i + 1 < s.size() && s[i + 1] == '[') {
const std::size_t end = try_link(s, i + 1, w, opt, depth, true);
if (end != npos) {
i = end;
continue;
}
append_escaped(w, s.substr(i, 1));
++i;
continue;
}
if (c == '<') {
const std::size_t close = s.find('>', i + 1);
if (close != npos) {
const std::string_view inner = s.substr(i + 1, close - i - 1);
if (is_autolink(inner)) {
w.append("<a href=\"");
append_escaped(w, inner);
w.append("\">");
append_escaped(w, inner);
w.append("</a>");
i = close + 1;
continue;
}
}
append_escaped(w, s.substr(i, 1));
++i;
continue;
}
if (c == '\n') {
if (w.out.size() >= 2 && w.out[w.out.size() - 1] == ' ' &&
w.out[w.out.size() - 2] == ' ') {
w.out.resize(w.out.size() - 2);
w.append("<br />\n");
} else {
w.append('\n');
}
++i;
continue;
}
append_escaped(w, s.substr(i, 1));
++i;
}
}
// ── Block parser ────────────────────────────────────────────────────────────
inline void render_blocks(std::string_view text,
MarkdownWriter& w,
const MarkdownOptions& opt,
std::size_t depth,
std::size_t& blocks,
bool tight = false);
inline void render_blocks(std::string_view text,
MarkdownWriter& w,
const MarkdownOptions& opt,
std::size_t depth,
std::size_t& blocks,
bool tight)
{
if (w.failed) {
return;
}
if (depth > opt.limits.max_depth) {
w.fail(MarkdownError::Code::depth_limit, 0);
return;
}
std::string_view rest = text;
while (!rest.empty() && !w.failed) {
const std::string_view line = first_line(rest);
if (is_blank(line)) {
consume_line(rest);
continue;
}
if (blocks >= opt.limits.max_blocks) {
w.fail(MarkdownError::Code::block_limit, 0);
return;
}
++blocks;
char fence_char = 0;
std::size_t fence_len = 0;
std::string_view info;
if (is_fence_open(line, fence_char, fence_len, info)) {
consume_line(rest);
std::string code;
while (!rest.empty()) {
const std::string_view l = first_line(rest);
if (is_fence_close(l, fence_char, fence_len)) {
consume_line(rest);
break;
}
if (!code.empty()) {
code += '\n';
}
code.append(l);
consume_line(rest);
}
w.append("<pre><code");
const std::string_view lang = first_word(info);
if (!lang.empty()) {
w.append(" class=\"language-");
append_escaped(w, lang);
w.append("\"");
}
w.append(">");
append_escaped(w, code);
w.append("\n</code></pre>\n");
continue;
}
const int level = atx_heading(line);
if (level != 0) {
consume_line(rest);
const std::string_view content = heading_content(line, level);
const char digit = static_cast<char>('0' + level);
w.append("<h");
w.append(digit);
w.append(">");
render_inline(content, w, opt, depth + 1);
w.append("</h");
w.append(digit);
w.append(">\n");
continue;
}
if (is_thematic_break(line)) {
consume_line(rest);
w.append("<hr />\n");
continue;
}
if (is_blockquote_line(line)) {
std::string inner;
while (!rest.empty()) {
const std::string_view l = first_line(rest);
if (is_blockquote_line(l)) {
inner.append(strip_blockquote(l));
inner += '\n';
consume_line(rest);
} else if (is_blank(l)) {
std::string_view ahead = rest;
consume_line(ahead);
if (!ahead.empty() && is_blockquote_line(first_line(ahead))) {
inner += '\n';
consume_line(rest);
} else {
break;
}
} else {
break;
}
}
w.append("<blockquote>\n");
render_blocks(inner, w, opt, depth + 1, blocks, false);
w.append("</blockquote>\n");
continue;
}
bool ordered = false;
int start = 1;
std::size_t offset = 0;
if (parse_list_marker(line, ordered, start, offset)) {
w.append(ordered ? "<ol" : "<ul");
if (ordered && start != 1) {
w.append(" start=\"");
w.append(std::to_string(start));
w.append("\"");
}
w.append(">\n");
while (!rest.empty()) {
const std::string_view l = first_line(rest);
bool o2 = false;
int s2 = 1;
std::size_t off2 = 0;
if (!parse_list_marker(l, o2, s2, off2) || o2 != ordered) {
break;
}
consume_line(rest);
std::string item{l.substr(off2)};
while (!rest.empty()) {
const std::string_view cont = first_line(rest);
if (is_blank(cont)) {
break;
}
bool o3 = false;
int s3 = 1;
std::size_t off3 = 0;
if (parse_list_marker(cont, o3, s3, off3)) {
break;
}
if (indent_of(cont) < 2) {
break;
}
item += '\n';
item.append(trim_left(cont));
consume_line(rest);
}
w.append("<li>");
render_blocks(item, w, opt, depth + 1, blocks, true);
if (!w.failed && !w.out.empty() && w.out.back() == '\n') {
w.out.pop_back();
}
w.append("</li>\n");
}
w.append(ordered ? "</ol>\n" : "</ul>\n");
continue;
}
// Paragraph (possibly promoted to a setext heading).
std::string para;
int setext = 0;
while (!rest.empty()) {
const std::string_view l = first_line(rest);
if (is_blank(l)) {
break;
}
if (!para.empty()) {
const int lvl = setext_underline_level(l);
if (lvl != 0) {
setext = lvl;
consume_line(rest);
break;
}
if (starts_block(l)) {
break;
}
}
if (!para.empty()) {
para += '\n';
}
para.append(l);
consume_line(rest);
}
if (setext != 0) {
const char digit = static_cast<char>('0' + setext);
w.append("<h");
w.append(digit);
w.append(">");
render_inline(para, w, opt, depth + 1);
w.append("</h");
w.append(digit);
w.append(">\n");
} else if (tight) {
render_inline(para, w, opt, depth + 1);
w.append('\n');
} else {
w.append("<p>");
render_inline(para, w, opt, depth + 1);
w.append("</p>\n");
}
}
}
} // namespace Detail
/// Parse a bounded CommonMark subset from `input` and render it to safe HTML.
/// Raw HTML is escaped, never passed through; unsafe link destinations are
/// dropped. Returns a `MarkdownError` when a configured limit is exceeded.
[[nodiscard]] inline std::expected<std::string, MarkdownError>
markdown_to_html(std::string_view input, MarkdownOptions options = {})
{
if (input.size() > options.limits.max_input) {
return std::unexpected{
MarkdownError{MarkdownError::Code::input_limit, options.limits.max_input}};
}
Detail::MarkdownWriter w;
w.limit = options.limits.max_output;
std::size_t blocks = 0;
Detail::render_blocks(input, w, options, 0, blocks, false);
if (w.failed) {
return std::unexpected{w.error};
}
return std::move(w.out);
}
} // namespace Void::Text