#pragma once
// Spec: SPEC.md UX-MD-01. CommonMark/GFM subset parser producing a plain AST.
// Supported: ATX and setext headings, paragraphs, emphasis, strong, strikethrough, inline code, inline links,
// angle and bare autolinks, images, bullet/ordered/task lists with nesting, blockquotes, fenced and indented code,
// tables, thematic breaks, hard and soft breaks, backslash escapes, common entities.
// Not supported (rendered as literal text): raw HTML, reference-style links and definitions, footnotes.
// All caps come from spec/MarkdownTheme.hpp (MarkdownLimits).
#include <string>
#include <vector>
namespace dp::ui {
struct MdInline {
enum class Kind { Text, Code, Emphasis, Strong, Strike, Link, Image, SoftBreak, HardBreak };
Kind kind = Kind::Text;
std::string text; // Text and Code content; destination for Link and Image
std::string title; // Link and Image title
std::vector<MdInline> children; // Emphasis, Strong, Strike, Link content; Image alt content
int depth = 0; // nesting depth of children, used for the cap
};
enum class MdAlign { None, Left, Center, Right };
struct MdBlock {
enum class Kind { Paragraph, Heading, Quote, List, ListItem, CodeBlock, Table, TableRow, TableCell, Rule };
Kind kind = Kind::Paragraph;
int level = 0; // Heading 1..6
bool ordered = false; // List
bool tight = true; // List
int start = 1; // List first number
int task = -1; // ListItem: -1 none, 0 unchecked, 1 checked
bool header = false; // TableRow
std::string text; // CodeBlock content (without the final newline)
std::string info; // CodeBlock info string
std::vector<MdInline> inlines; // Paragraph, Heading, TableCell
std::vector<MdBlock> children; // Quote, List, ListItem, Table (rows), TableRow (cells)
std::vector<MdAlign> aligns; // Table
};
struct MarkdownDocument {
std::vector<MdBlock> blocks;
bool truncated = false; // input cut at the char cap, or blocks dropped at the block cap
int blockCount = 0;
};
class MarkdownParser {
public:
static MarkdownDocument parse(const std::string& markdown);
// Inline parsing of one text run (soft breaks as "\n"). Exposed for tests.
static std::vector<MdInline> parseInline(const std::string& text);
// Concatenated plain text of inline nodes (image alt text, tests).
static std::string plainText(const std::vector<MdInline>& nodes);
};
} // namespace dp::ui