#include "ui/MarkdownParser.hpp"
#include <algorithm>
#include <cstdlib>
#include <map>
#include "spec/MarkdownTheme.hpp"
namespace dp::ui {
using Lim = spec::MarkdownLimits;
namespace {
// ------------------------------------------------------------------ character helpers
bool isAsciiPunct(char c) {
return (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126);
}
bool isSpaceCh(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; }
bool isAlnum(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
std::string trim(const std::string& s) {
std::size_t a = 0, b = s.size();
while (a < b && isSpaceCh(s[a])) ++a;
while (b > a && isSpaceCh(s[b - 1])) --b;
return s.substr(a, b - a);
}
void appendUtf8(std::string& out, unsigned long cp) {
if (cp == 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) cp = 0xFFFD;
if (cp < 0x80) {
out += static_cast<char>(cp);
} else if (cp < 0x800) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else {
out += static_cast<char>(0xF0 | (cp >> 18));
out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
}
}
// Decodes an entity starting at s[pos] == '&'. Returns the length consumed, 0 when it is not an entity.
std::size_t decodeEntity(const std::string& s, std::size_t pos, std::string& out) {
const std::size_t semi = s.find(';', pos);
if (semi == std::string::npos || semi - pos > 10) return 0;
const std::string name = s.substr(pos + 1, semi - pos - 1);
if (name.empty()) return 0;
if (name[0] == '#') {
const bool hex = name.size() > 1 && (name[1] == 'x' || name[1] == 'X');
const std::string digits = name.substr(hex ? 2 : 1);
if (digits.empty() || digits.size() > 7) return 0;
for (char c : digits) {
const bool ok = hex ? (isAlnum(c) && !(c > 'f' && c <= 'z') && !(c > 'F' && c <= 'Z')) : (c >= '0' && c <= '9');
if (!ok) return 0;
}
appendUtf8(out, std::strtoul(digits.c_str(), nullptr, hex ? 16 : 10));
return semi - pos + 1;
}
static const std::map<std::string, const char*> table = {
{"amp", "&"}, {"lt", "<"}, {"gt", ">"}, {"quot", "\""}, {"apos", "'"}, {"nbsp", "\xC2\xA0"}, {"copy", "\xC2\xA9"},
{"reg", "\xC2\xAE"}, {"hellip", "\xE2\x80\xA6"}, {"mdash", "-"}, {"ndash", "-"}};
auto it = table.find(name);
if (it == table.end()) return 0;
out += it->second;
return semi - pos + 1;
}
// ------------------------------------------------------------------ inline parser
struct Item {
enum class K { Node, Delim, Bracket } k = K::Node;
MdInline node;
char ch = 0;
int count = 0, orig = 0;
bool canOpen = false, canClose = false;
bool image = false, active = true; // Bracket
};
class InlineParser {
public:
explicit InlineParser(const std::string& s) : s_(s) {}
std::vector<MdInline> run() {
while (pos_ < s_.size()) step();
flush();
processEmphasis(items_, 0);
return flatten(items_);
}
private:
void flush() {
if (buf_.empty()) return;
MdInline t;
t.text = std::move(buf_);
buf_.clear();
Item it;
it.node = std::move(t);
items_.push_back(std::move(it));
}
void pushNode(MdInline n) {
flush();
Item it;
it.node = std::move(n);
items_.push_back(std::move(it));
}
bool delimBudget() {
if (delims_ >= Lim::kMaxDelimiters) return false;
++delims_;
return true;
}
char at(std::size_t i) const { return i < s_.size() ? s_[i] : ' '; }
void step() {
const char c = s_[pos_];
switch (c) {
case '\\': return escape();
case '`': return codeSpan();
case '<': return angle();
case '&': {
std::string dec;
const std::size_t n = decodeEntity(s_, pos_, dec);
if (n) { buf_ += dec; pos_ += n; } else { buf_ += c; ++pos_; }
return;
}
case '\n': return newline();
case '*': case '_': case '~': return delimiter();
case '[': return openBracket(false);
case '!':
if (at(pos_ + 1) == '[') return openBracket(true);
buf_ += c; ++pos_;
return;
case ']': return closeBracket();
case 'h': case 'w': case 'H': case 'W':
if (tryBareLink()) return;
buf_ += c; ++pos_;
return;
default: buf_ += c; ++pos_;
}
}
void escape() {
const char n = at(pos_ + 1);
if (pos_ + 1 < s_.size() && n == '\n') {
MdInline b; b.kind = MdInline::Kind::HardBreak;
pushNode(std::move(b));
pos_ += 2;
skipSpaces();
} else if (pos_ + 1 < s_.size() && isAsciiPunct(n)) {
buf_ += n;
pos_ += 2;
} else {
buf_ += '\\';
++pos_;
}
}
void skipSpaces() { while (pos_ < s_.size() && (s_[pos_] == ' ' || s_[pos_] == '\t')) ++pos_; }
void newline() {
std::size_t spaces = 0;
while (spaces < buf_.size() && buf_[buf_.size() - 1 - spaces] == ' ') ++spaces;
buf_.erase(buf_.size() - spaces);
MdInline b;
b.kind = spaces >= 2 ? MdInline::Kind::HardBreak : MdInline::Kind::SoftBreak;
pushNode(std::move(b));
++pos_;
skipSpaces();
}
void codeSpan() {
std::size_t len = 0;
while (pos_ + len < s_.size() && s_[pos_ + len] == '`') ++len;
const int key = static_cast<int>(std::min<std::size_t>(len, 1000));
auto failed = noCloser_.find(key);
if (failed == noCloser_.end() || failed->second > pos_) {
std::size_t p = pos_ + len;
while (p < s_.size()) {
if (s_[p] != '`') { ++p; continue; }
std::size_t run = 0;
while (p + run < s_.size() && s_[p + run] == '`') ++run;
if (run == len) {
std::string content = s_.substr(pos_ + len, p - pos_ - len);
for (char& ch : content) if (ch == '\n') ch = ' ';
if (content.size() >= 2 && content.front() == ' ' && content.back() == ' ' &&
content.find_first_not_of(' ') != std::string::npos) {
content = content.substr(1, content.size() - 2);
}
MdInline n; n.kind = MdInline::Kind::Code; n.text = std::move(content);
pushNode(std::move(n));
pos_ = p + run;
return;
}
p += run;
}
noCloser_[key] = pos_;
}
buf_.append(len, '`');
pos_ += len;
}
void angle() {
const std::size_t end = s_.find('>', pos_ + 1);
if (end != std::string::npos && end - pos_ < Lim::kMaxUrlChars) {
const std::string body = s_.substr(pos_ + 1, end - pos_ - 1);
bool bad = body.empty();
for (char ch : body) if (isSpaceCh(ch) || ch == '<') bad = true;
if (!bad) {
const std::size_t colon = body.find(':');
const bool scheme = colon != std::string::npos && colon >= 2 && colon <= 32 && colon + 1 < body.size() &&
std::isalpha(static_cast<unsigned char>(body[0]));
bool schemeOk = scheme;
for (std::size_t i = 0; scheme && i < colon; ++i) {
if (!(isAlnum(body[i]) || body[i] == '+' || body[i] == '.' || body[i] == '-')) schemeOk = false;
}
const std::size_t at = body.find('@');
const bool email = !schemeOk && at != std::string::npos && at > 0 && at + 1 < body.size() &&
body.find('@', at + 1) == std::string::npos && body.find('.', at) != std::string::npos;
if (schemeOk || email) {
pushLink(email ? "mailto:" + body : body, body);
pos_ = end + 1;
return;
}
}
}
buf_ += '<';
++pos_;
}
void pushLink(const std::string& dest, const std::string& label) {
MdInline link; link.kind = MdInline::Kind::Link; link.text = dest; link.depth = 1;
MdInline t; t.text = label;
link.children.push_back(std::move(t));
pushNode(std::move(link));
}
bool tryBareLink() {
if (openBrackets_ > 0) return false;
if (pos_ > 0 && (isAlnum(s_[pos_ - 1]) || s_[pos_ - 1] == '/' || s_[pos_ - 1] == '@')) return false;
auto starts = [&](const char* p) {
std::size_t i = 0;
for (; p[i]; ++i) if (pos_ + i >= s_.size() || std::tolower(static_cast<unsigned char>(s_[pos_ + i])) != p[i]) return false;
return true;
};
const bool web = starts("http://") || starts("https://");
const bool www = starts("www.");
if (!web && !www) return false;
std::size_t end = pos_;
while (end < s_.size() && !isSpaceCh(s_[end]) && s_[end] != '<' && end - pos_ < Lim::kMaxUrlChars) ++end;
while (end > pos_) {
const char l = s_[end - 1];
if (std::string("?!.,:*_~'\";").find(l) != std::string::npos) { --end; continue; }
if (l == ')') {
const std::string u = s_.substr(pos_, end - pos_);
if (std::count(u.begin(), u.end(), ')') > std::count(u.begin(), u.end(), '(')) { --end; continue; }
}
break;
}
const std::size_t minLen = web ? (starts("https://") ? 9 : 8) : 5;
if (end - pos_ < minLen) return false;
const std::string text = s_.substr(pos_, end - pos_);
pushLink(www ? "http://" + text : text, text);
pos_ = end;
return true;
}
void delimiter() {
const char c = s_[pos_];
std::size_t len = 0;
while (pos_ + len < s_.size() && s_[pos_ + len] == c) ++len;
if ((c == '~' && len > 2) || !delimBudget()) {
buf_.append(len, c);
pos_ += len;
return;
}
const char before = pos_ == 0 ? ' ' : s_[pos_ - 1];
const char after = at(pos_ + len);
const bool wsB = isSpaceCh(before), wsA = isSpaceCh(after);
const bool puB = isAsciiPunct(before), puA = isAsciiPunct(after);
const bool left = !wsA && (!puA || wsB || puB);
const bool right = !wsB && (!puB || wsA || puA);
flush();
Item it;
it.k = Item::K::Delim;
it.ch = c;
it.count = it.orig = static_cast<int>(len);
if (c == '_') {
it.canOpen = left && (!right || puB);
it.canClose = right && (!left || puA);
} else {
it.canOpen = left;
it.canClose = right;
}
items_.push_back(std::move(it));
pos_ += len;
}
void openBracket(bool image) {
if (!delimBudget()) {
buf_ += s_[pos_];
++pos_;
return;
}
flush();
Item it;
it.k = Item::K::Bracket;
it.image = image;
items_.push_back(std::move(it));
++openBrackets_;
pos_ += image ? 2 : 1;
}
// Parses "(dest "title")" starting after the '('. Returns the index after ')' or npos.
std::size_t parseLinkTail(std::size_t p, std::string& dest, std::string& title) const {
auto skipWs = [&] { while (p < s_.size() && isSpaceCh(s_[p])) ++p; };
skipWs();
if (p < s_.size() && s_[p] == '<') {
++p;
while (p < s_.size() && s_[p] != '>' && s_[p] != '\n' && s_[p] != '<') {
if (s_[p] == '\\' && p + 1 < s_.size() && isAsciiPunct(s_[p + 1])) ++p;
dest += s_[p++];
}
if (p >= s_.size() || s_[p] != '>') return std::string::npos;
++p;
} else {
int parens = 0;
while (p < s_.size() && !isSpaceCh(s_[p]) && static_cast<unsigned char>(s_[p]) >= 0x20) {
if (s_[p] == '\\' && p + 1 < s_.size() && isAsciiPunct(s_[p + 1])) { dest += s_[p + 1]; p += 2; continue; }
if (s_[p] == '(') ++parens;
if (s_[p] == ')') { if (parens == 0) break; --parens; }
dest += s_[p++];
if (dest.size() > Lim::kMaxUrlChars) return std::string::npos;
}
if (parens != 0) return std::string::npos;
}
const std::size_t beforeWs = p;
skipWs();
if (p < s_.size() && p > beforeWs && (s_[p] == '"' || s_[p] == '\'' || s_[p] == '(')) {
const char close = s_[p] == '(' ? ')' : s_[p];
++p;
while (p < s_.size() && s_[p] != close) {
if (s_[p] == '\\' && p + 1 < s_.size() && isAsciiPunct(s_[p + 1])) ++p;
title += s_[p++];
if (title.size() > Lim::kMaxUrlChars) return std::string::npos;
}
if (p >= s_.size()) return std::string::npos;
++p;
skipWs();
}
if (p >= s_.size() || s_[p] != ')') return std::string::npos;
return p + 1;
}
void closeBracket() {
flush();
std::size_t o = items_.size();
while (o > 0 && items_[o - 1].k != Item::K::Bracket) --o;
if (o == 0) { buf_ += ']'; ++pos_; return; }
--o;
std::string dest, title;
std::size_t next = std::string::npos;
if (items_[o].active && at(pos_ + 1) == '(' && pos_ + 1 < s_.size()) next = parseLinkTail(pos_ + 2, dest, title);
if (next == std::string::npos) {
// Literal text: the opener becomes "[" or "![" and the closer a plain "]".
Item& op = items_[o];
MdInline t; t.text = op.image ? "![" : "[";
op.k = Item::K::Node;
op.node = std::move(t);
--openBrackets_;
buf_ += ']';
++pos_;
return;
}
std::vector<Item> inner(std::make_move_iterator(items_.begin() + static_cast<long>(o) + 1),
std::make_move_iterator(items_.end()));
items_.resize(o + 1);
--openBrackets_;
for (const Item& x : inner) if (x.k == Item::K::Bracket) --openBrackets_;
const bool image = items_[o].image;
processEmphasis(inner, 0);
MdInline n;
n.kind = image ? MdInline::Kind::Image : MdInline::Kind::Link;
n.text = std::move(dest);
n.title = std::move(title);
n.children = flatten(inner);
int d = 0;
for (const MdInline& ch : n.children) d = std::max(d, ch.depth);
n.depth = d + 1;
items_.pop_back(); // the opener
if (n.depth > Lim::kMaxInlineNesting) {
MdInline t; t.text = MarkdownParser::plainText(n.children);
n = std::move(t);
} else if (!image) {
for (Item& it : items_) if (it.k == Item::K::Bracket && !it.image) it.active = false;
}
Item it;
it.node = std::move(n);
items_.push_back(std::move(it));
pos_ = next;
}
static MdInline delimText(const Item& it) {
MdInline t;
if (it.k == Item::K::Delim) t.text.assign(static_cast<std::size_t>(it.count), it.ch);
else t.text = it.image ? "![" : "[";
return t;
}
static std::vector<MdInline> flatten(std::vector<Item>& v) {
std::vector<MdInline> out;
for (Item& it : v) {
MdInline n = it.k == Item::K::Node ? std::move(it.node) : delimText(it);
if (n.kind == MdInline::Kind::Text && !out.empty() && out.back().kind == MdInline::Kind::Text) {
out.back().text += n.text;
} else if (n.kind != MdInline::Kind::Text || !n.text.empty()) {
out.push_back(std::move(n));
}
}
return out;
}
static void processEmphasis(std::vector<Item>& v, std::size_t lo) {
std::size_t c = lo;
while (c < v.size()) {
if (v[c].k != Item::K::Delim || !v[c].canClose || v[c].count == 0) { ++c; continue; }
std::size_t o = c;
bool found = false;
while (o > lo) {
--o;
const Item& op = v[o];
if (op.k != Item::K::Delim || op.ch != v[c].ch || !op.canOpen || op.count == 0) continue;
if (op.ch == '~') {
if (op.count != v[c].count) continue;
} else if ((op.canClose || v[c].canOpen) && (op.orig + v[c].orig) % 3 == 0 &&
!(op.orig % 3 == 0 && v[c].orig % 3 == 0)) {
continue;
}
found = true;
break;
}
if (!found) { ++c; continue; }
Item& op = v[o];
Item& cl = v[c];
const int use = op.ch == '~' ? op.count : ((op.count >= 2 && cl.count >= 2) ? 2 : 1);
int d = 0;
for (std::size_t x = o + 1; x < c; ++x) if (v[x].k == Item::K::Node) d = std::max(d, v[x].node.depth);
if (d + 1 > Lim::kMaxInlineNesting) { // cap: keep the delimiters literal
v[c].canClose = false;
continue;
}
std::vector<Item> inner(std::make_move_iterator(v.begin() + static_cast<long>(o) + 1),
std::make_move_iterator(v.begin() + static_cast<long>(c)));
MdInline n;
n.kind = op.ch == '~' ? MdInline::Kind::Strike : (use == 2 ? MdInline::Kind::Strong : MdInline::Kind::Emphasis);
n.children = flatten(inner);
n.depth = d + 1;
v.erase(v.begin() + static_cast<long>(o) + 1, v.begin() + static_cast<long>(c));
Item wrap;
wrap.node = std::move(n);
v.insert(v.begin() + static_cast<long>(o) + 1, std::move(wrap));
std::size_t closer = o + 2;
v[o].count -= use;
v[closer].count -= use;
if (v[closer].count == 0) v.erase(v.begin() + static_cast<long>(closer));
if (v[o].count == 0) {
v.erase(v.begin() + static_cast<long>(o));
closer -= 1;
c = (closer < v.size() && v[closer].k == Item::K::Delim && v[closer].count > 0) ? closer : o + 1;
} else {
c = closer < v.size() ? closer : v.size();
}
}
}
const std::string& s_;
std::size_t pos_ = 0;
std::string buf_;
std::vector<Item> items_;
int delims_ = 0;
int openBrackets_ = 0;
std::map<int, std::size_t> noCloser_;
};
// ------------------------------------------------------------------ block parser
using Lines = std::vector<std::string>;
int indentOf(const std::string& l) {
int n = 0;
while (n < static_cast<int>(l.size()) && l[n] == ' ') ++n;
return n;
}
bool blank(const std::string& l) { return l.find_first_not_of(" \t") == std::string::npos; }
std::string dedent(const std::string& l, int n) {
int k = 0;
while (k < n && k < static_cast<int>(l.size()) && l[k] == ' ') ++k;
return l.substr(static_cast<std::size_t>(k));
}
bool atxHeading(const std::string& l, int& level, std::string& text) {
const int ind = indentOf(l);
if (ind > 3) return false;
std::size_t p = static_cast<std::size_t>(ind), n = 0;
while (p + n < l.size() && l[p + n] == '#') ++n;
if (n < 1 || n > 6) return false;
if (p + n < l.size() && l[p + n] != ' ' && l[p + n] != '\t') return false;
level = static_cast<int>(n);
std::string t = trim(l.substr(p + n));
std::size_t e = t.size();
while (e > 0 && t[e - 1] == '#') --e;
if (e == 0) t.clear();
else if (e < t.size() && (t[e - 1] == ' ' || t[e - 1] == '\t')) t = trim(t.substr(0, e));
text = t;
return true;
}
bool isRule(const std::string& l) {
if (indentOf(l) > 3) return false;
char ch = 0;
int n = 0;
for (char c : l) {
if (c == ' ' || c == '\t') continue;
if (c != '-' && c != '*' && c != '_') return false;
if (ch && c != ch) return false;
ch = c;
++n;
}
return n >= 3;
}
bool fenceOf(const std::string& l, char& ch, int& len, int& ind, std::string& info) {
ind = indentOf(l);
if (ind > 3 || ind >= static_cast<int>(l.size())) return false;
ch = l[static_cast<std::size_t>(ind)];
if (ch != '`' && ch != '~') return false;
len = 0;
while (ind + len < static_cast<int>(l.size()) && l[static_cast<std::size_t>(ind + len)] == ch) ++len;
if (len < 3) return false;
info = trim(l.substr(static_cast<std::size_t>(ind + len)));
return !(ch == '`' && info.find('`') != std::string::npos);
}
bool quoteStart(const std::string& l) {
const int ind = indentOf(l);
return ind <= 3 && ind < static_cast<int>(l.size()) && l[static_cast<std::size_t>(ind)] == '>';
}
struct Marker {
bool ok = false;
bool ordered = false;
char ch = 0;
int number = 0;
int contentIndent = 0;
bool empty = false;
};
Marker markerOf(const std::string& l) {
Marker m;
const int ind = indentOf(l);
if (ind > 3 || ind >= static_cast<int>(l.size())) return m;
std::size_t p = static_cast<std::size_t>(ind), after = p;
const char c = l[p];
if (c == '-' || c == '+' || c == '*') {
m.ch = c;
after = p + 1;
} else if (c >= '0' && c <= '9') {
std::size_t d = p;
while (d < l.size() && l[d] >= '0' && l[d] <= '9') ++d;
if (d - p > 9 || d >= l.size() || (l[d] != '.' && l[d] != ')')) return m;
m.ordered = true;
m.ch = l[d];
m.number = std::atoi(l.substr(p, d - p).c_str());
after = d + 1;
} else {
return m;
}
if (after < l.size() && l[after] != ' ' && l[after] != '\t') return m;
std::size_t sp = after;
while (sp < l.size() && (l[sp] == ' ' || l[sp] == '\t')) ++sp;
m.ok = true;
if (sp >= l.size()) {
m.empty = true;
m.contentIndent = static_cast<int>(after) + 1;
} else {
const int spaces = static_cast<int>(sp - after);
m.contentIndent = static_cast<int>(after) + (spaces > 4 ? 1 : spaces);
}
return m;
}
// Lines that end a running paragraph.
bool interrupts(const std::string& l) {
char ch; int len, ind; std::string info; int level; std::string text;
if (fenceOf(l, ch, len, ind, info) || atxHeading(l, level, text) || isRule(l) || quoteStart(l)) return true;
const Marker m = markerOf(l);
return m.ok && !m.empty && (!m.ordered || m.number == 1);
}
int setextLevel(const std::string& l) {
if (indentOf(l) > 3) return 0;
const std::string t = trim(l);
if (t.empty()) return 0;
const char c = t[0];
if (c != '=' && c != '-') return 0;
for (char x : t) if (x != c) return 0;
return c == '=' ? 1 : 2;
}
std::vector<std::string> splitRow(const std::string& line) {
std::string t = trim(line);
if (!t.empty() && t[0] == '|') t.erase(0, 1);
if (!t.empty() && t.back() == '|' && (t.size() < 2 || t[t.size() - 2] != '\\')) t.pop_back();
std::vector<std::string> cells;
std::string cur;
for (std::size_t i = 0; i < t.size(); ++i) {
if (t[i] == '\\' && i + 1 < t.size() && t[i + 1] == '|') { cur += '|'; ++i; }
else if (t[i] == '|') { cells.push_back(trim(cur)); cur.clear(); }
else cur += t[i];
}
cells.push_back(trim(cur));
return cells;
}
bool delimiterRow(const std::string& line, std::vector<MdAlign>& aligns) {
if (line.find('-') == std::string::npos) return false;
aligns.clear();
for (const std::string& c : splitRow(line)) {
if (c.empty()) return false;
const bool l = c.front() == ':', r = c.back() == ':';
const std::string core = c.substr(l ? 1 : 0, c.size() - (l ? 1 : 0) - (r && c.size() > 1 ? 1 : 0));
if (core.empty() || core.find_first_not_of('-') != std::string::npos) return false;
aligns.push_back(l && r ? MdAlign::Center : (l ? MdAlign::Left : (r ? MdAlign::Right : MdAlign::None)));
}
return !aligns.empty();
}
class BlockParser {
public:
MarkdownDocument doc;
void parse(const Lines& lines, int depth, std::vector<MdBlock>& out) {
if (depth > Lim::kMaxBlockNesting) {
std::string joined;
for (const std::string& l : lines) joined += (joined.empty() ? "" : "\n") + trim(l);
if (!trim(joined).empty() && take()) out.push_back(paragraph(joined));
return;
}
std::size_t i = 0;
const std::size_t n = lines.size();
while (i < n) {
if (blank(lines[i])) { ++i; continue; }
if (doc.blockCount >= Lim::kMaxBlocks) { doc.truncated = true; return; }
const std::string& l = lines[i];
char fch; int flen, find; std::string info;
int level; std::string text;
if (fenceOf(l, fch, flen, find, info)) { i = fenced(lines, i, fch, flen, find, info, out); continue; }
if (atxHeading(l, level, text)) {
if (take()) { MdBlock b; b.kind = MdBlock::Kind::Heading; b.level = level; b.inlines = MarkdownParser::parseInline(text); out.push_back(std::move(b)); }
++i;
continue;
}
if (isRule(l)) {
if (take()) { MdBlock b; b.kind = MdBlock::Kind::Rule; out.push_back(std::move(b)); }
++i;
continue;
}
if (quoteStart(l)) { i = quote(lines, i, depth, out); continue; }
if (markerOf(l).ok) { i = list(lines, i, depth, out); continue; }
if (indentOf(l) >= 4) { i = indented(lines, i, out); continue; }
if (const std::size_t t = table(lines, i, out)) { i = t; continue; }
i = para(lines, i, out);
}
}
private:
bool take() {
if (doc.blockCount >= Lim::kMaxBlocks) { doc.truncated = true; return false; }
++doc.blockCount;
return true;
}
static MdBlock paragraph(const std::string& text) {
MdBlock b;
b.kind = MdBlock::Kind::Paragraph;
b.inlines = MarkdownParser::parseInline(text);
return b;
}
std::size_t fenced(const Lines& lines, std::size_t i, char ch, int len, int ind, const std::string& info,
std::vector<MdBlock>& out) {
std::string code;
std::size_t j = i + 1;
bool first = true;
for (; j < lines.size(); ++j) {
char c2; int l2, i2; std::string info2;
if (fenceOf(lines[j], c2, l2, i2, info2) && c2 == ch && l2 >= len && info2.empty()) { ++j; break; }
if (!first) code += '\n';
first = false;
code += dedent(lines[j], ind);
}
if (take()) {
MdBlock b; b.kind = MdBlock::Kind::CodeBlock; b.text = std::move(code); b.info = info;
out.push_back(std::move(b));
}
return j;
}
std::size_t indented(const Lines& lines, std::size_t i, std::vector<MdBlock>& out) {
std::size_t j = i, lastCode = i;
while (j < lines.size() && (indentOf(lines[j]) >= 4 || blank(lines[j]))) {
if (!blank(lines[j])) lastCode = j;
++j;
}
std::string code;
for (std::size_t k = i; k <= lastCode; ++k) {
if (k > i) code += '\n';
code += dedent(lines[k], 4);
}
if (take()) {
MdBlock b; b.kind = MdBlock::Kind::CodeBlock; b.text = std::move(code);
out.push_back(std::move(b));
}
return lastCode + 1;
}
std::size_t quote(const Lines& lines, std::size_t i, int depth, std::vector<MdBlock>& out) {
Lines inner;
std::size_t j = i;
while (j < lines.size()) {
const std::string& l = lines[j];
if (quoteStart(l)) {
std::string s = l.substr(static_cast<std::size_t>(indentOf(l)) + 1);
if (!s.empty() && s[0] == ' ') s.erase(0, 1);
inner.push_back(std::move(s));
} else if (!blank(l) && !inner.empty() && !blank(inner.back()) && !interrupts(l)) {
inner.push_back(trim(l));
} else {
break;
}
++j;
}
if (take()) {
MdBlock b; b.kind = MdBlock::Kind::Quote;
parse(inner, depth + 1, b.children);
out.push_back(std::move(b));
}
return j;
}
std::size_t list(const Lines& lines, std::size_t i, int depth, std::vector<MdBlock>& out) {
const Marker m0 = markerOf(lines[i]);
MdBlock lst;
lst.kind = MdBlock::Kind::List;
lst.ordered = m0.ordered;
lst.start = m0.number;
const std::size_t n = lines.size();
const bool keep = take();
while (i < n) {
const Marker m = markerOf(lines[i]);
Lines item;
item.push_back(m.empty ? "" : lines[i].substr(static_cast<std::size_t>(std::min<int>(m.contentIndent, static_cast<int>(lines[i].size())))));
bool innerBlank = false;
++i;
while (i < n) {
const std::string& l = lines[i];
if (blank(l)) {
std::size_t k = i;
while (k < n && blank(lines[k])) ++k;
if (k < n && indentOf(lines[k]) >= m.contentIndent && !(item.size() == 1 && item[0].empty())) {
for (std::size_t x = i; x < k; ++x) item.emplace_back();
innerBlank = true;
i = k;
continue;
}
break;
}
if (indentOf(l) >= m.contentIndent) { item.push_back(dedent(l, m.contentIndent)); ++i; continue; }
if (!blank(item.back()) && !interrupts(l) && !markerOf(l).ok) { item.push_back(trim(l)); ++i; continue; }
break;
}
MdBlock it;
it.kind = MdBlock::Kind::ListItem;
if (!item.empty()) {
const std::string& f = item[0];
if (f.size() >= 3 && f[0] == '[' && (f[1] == ' ' || f[1] == 'x' || f[1] == 'X') && f[2] == ']' &&
(f.size() == 3 || f[3] == ' ')) {
it.task = f[1] == ' ' ? 0 : 1;
item[0] = f.size() > 4 ? f.substr(4) : "";
}
}
if (take()) {
parse(item, depth + 1, it.children);
if (innerBlank && it.children.size() > 1) lst.tight = false;
lst.children.push_back(std::move(it));
}
std::size_t j = i;
while (j < n && blank(lines[j])) ++j;
if (j < n) {
const Marker nm = markerOf(lines[j]);
if (nm.ok && nm.ordered == m0.ordered && nm.ch == m0.ch && !isRule(lines[j])) {
if (j > i) lst.tight = false;
i = j;
continue;
}
}
break;
}
if (keep) out.push_back(std::move(lst));
return i;
}
std::size_t table(const Lines& lines, std::size_t i, std::vector<MdBlock>& out) {
if (i + 1 >= lines.size() || lines[i].find('|') == std::string::npos) return 0;
std::vector<MdAlign> aligns;
if (!delimiterRow(lines[i + 1], aligns)) return 0;
std::vector<std::string> head = splitRow(lines[i]);
if (head.size() != aligns.size() || head.size() > static_cast<std::size_t>(Lim::kMaxTableColumns)) return 0;
if (!take()) return i + 2;
MdBlock t;
t.kind = MdBlock::Kind::Table;
t.aligns = aligns;
auto row = [&](const std::vector<std::string>& cells, bool header) {
MdBlock r;
r.kind = MdBlock::Kind::TableRow;
r.header = header;
for (std::size_t c = 0; c < aligns.size(); ++c) {
MdBlock cell;
cell.kind = MdBlock::Kind::TableCell;
cell.inlines = MarkdownParser::parseInline(c < cells.size() ? cells[c] : "");
r.children.push_back(std::move(cell));
}
t.children.push_back(std::move(r));
};
row(head, true);
std::size_t j = i + 2;
int rows = 0;
while (j < lines.size() && !blank(lines[j]) && !interrupts(lines[j])) {
if (++rows > Lim::kMaxTableRows) { doc.truncated = true; ++j; continue; }
row(splitRow(lines[j]), false);
++j;
}
out.push_back(std::move(t));
return j;
}
std::size_t para(const Lines& lines, std::size_t i, std::vector<MdBlock>& out) {
std::string text;
std::size_t j = i;
int setext = 0;
for (; j < lines.size() && !blank(lines[j]); ++j) {
if (j > i) {
setext = setextLevel(lines[j]);
if (setext) { ++j; break; }
if (interrupts(lines[j])) break;
}
if (j > i) text += '\n';
text += j == i ? trim(lines[j]) : dedent(lines[j], indentOf(lines[j]));
}
while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) text.pop_back();
if (take()) {
if (setext) {
MdBlock b; b.kind = MdBlock::Kind::Heading; b.level = setext; b.inlines = MarkdownParser::parseInline(text);
out.push_back(std::move(b));
} else {
out.push_back(paragraph(text));
}
}
return j;
}
};
Lines splitLines(const std::string& s) {
Lines lines;
std::string cur;
auto push = [&] {
// Expand leading tabs to the next multiple of 4.
std::string out;
std::size_t k = 0;
int col = 0;
for (; k < cur.size() && (cur[k] == ' ' || cur[k] == '\t'); ++k) {
if (cur[k] == ' ') { out += ' '; ++col; }
else { const int add = 4 - (col % 4); out.append(static_cast<std::size_t>(add), ' '); col += add; }
}
out += cur.substr(k);
lines.push_back(std::move(out));
cur.clear();
};
for (std::size_t i = 0; i < s.size(); ++i) {
const char c = s[i];
if (c == '\r') { if (i + 1 < s.size() && s[i + 1] == '\n') ++i; push(); }
else if (c == '\n') push();
else if (c == '\0') cur += "\xEF\xBF\xBD";
else cur += c;
}
if (!cur.empty()) push();
return lines;
}
} // namespace
MarkdownDocument MarkdownParser::parse(const std::string& markdown) {
BlockParser bp;
std::string input = markdown;
if (input.size() > Lim::kMaxInputChars) {
std::size_t cut = Lim::kMaxInputChars;
while (cut > 0 && (static_cast<unsigned char>(input[cut]) & 0xC0) == 0x80) --cut; // keep UTF-8 whole
input.resize(cut);
bp.doc.truncated = true;
}
const Lines lines = splitLines(input);
bp.parse(lines, 0, bp.doc.blocks);
return std::move(bp.doc);
}
std::vector<MdInline> MarkdownParser::parseInline(const std::string& text) {
InlineParser p(text);
return p.run();
}
std::string MarkdownParser::plainText(const std::vector<MdInline>& nodes) {
std::string out;
for (const MdInline& n : nodes) {
switch (n.kind) {
case MdInline::Kind::Text:
case MdInline::Kind::Code: out += n.text; break;
case MdInline::Kind::SoftBreak:
case MdInline::Kind::HardBreak: out += '\n'; break;
default: out += plainText(n.children);
}
}
return out;
}
} // namespace dp::ui