#![allow(clippy::result_large_err)]
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use tabnas::{AltSpec, Plugin, PluginError, Value, TIN_ZZ};
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub mod ast;
pub mod block;
pub mod common;
pub mod commonmark;
pub mod engine_block;
pub mod engine_inline;
mod entities;
pub mod html;
pub mod inline;
pub mod node;
pub mod options;
pub use ast::{resolve_references, to_ast};
pub use block::MAX_CONTAINER_NESTING;
pub use html::{render_html, render_html_with, DISALLOWED_TAGS};
pub use inline::MAX_INLINE_NESTING;
pub use node::{
Align, Definition, DefinitionSite, ListData, ListType, MdNode, NodeId, NodeType, ReferenceType,
SourcePos, TableAlign, Tree, WalkEvent, Walker,
};
pub use options::{Options, RefDef, RefMap, DEFAULT_OPTIONS};
pub use tabnas::Tabnas;
pub const VERSION: &str = "0.7.14";
pub use tabnas::TabnasError as MarkdownError;
pub const PLUGIN_NAME: &str = "Markdown";
pub fn parse_document(src: &str, options: &Options) -> Value {
to_ast(
&commonmark::parse_keeping_references(src, *options),
options,
)
}
pub fn parse_inline(text: &str, options: &Options) -> Vec<Value> {
let doc = parse_document(text, options);
let Some(Value::Array(children)) = engine_block::value_get(&doc, "children") else {
return Vec::new();
};
let Some(first) = children.first() else {
return Vec::new();
};
if !matches!(engine_block::value_get(first, "type"), Some(Value::String(t)) if t == "paragraph")
{
return Vec::new();
}
match engine_block::value_get(first, "children") {
Some(Value::Array(inlines)) => inlines.as_ref().clone(),
_ => Vec::new(),
}
}
pub fn to_html(src: &str, options: &Options) -> String {
render_html_with(&commonmark::parse(src, *options), *options)
}
pub fn parse_tree(src: &str, options: &Options) -> Tree {
commonmark::parse(src, *options)
}
pub fn markdown(tn: &mut Tabnas, options: &Options) -> Result<(), PluginError> {
let opts = *options;
let mut tins: HashMap<&'static str, tabnas::Tin> = HashMap::new();
tins.insert(engine_block::LINE_TOKEN, tn.token(engine_block::LINE_TOKEN));
tins.insert(engine_block::END_TOKEN, tn.token(engine_block::END_TOKEN));
for n in engine_block::NODE_RULES {
tins.insert(n.token, tn.token(n.token));
}
tn.set_options(|o| {
o.fixed.lex = false;
o.space.lex = false;
o.line.lex = false;
o.text.lex = false;
o.string.lex = false;
o.comment.lex = false;
o.number.lex = false;
o.value.lex = false;
o.lex.empty_result = empty_document();
o.rule.start = "markdown".to_string();
o.rule.exclude = if opts.gfm {
String::new()
} else {
"gfm".to_string()
};
})?;
let inline_tn = Arc::new(engine_inline::make_inline_tn(&opts));
tn.options.lex.matchers.insert(
engine_block::MD_BLOCK_MATCHER.to_string(),
tabnas::LexMatcher {
name: engine_block::MD_BLOCK_MATCHER.to_string(),
order: engine_block::MD_BLOCK_ORDER,
matcher: None,
imperative: Some(Arc::new(engine_block::make_md_block_matcher(
opts,
tins.clone(),
Arc::clone(&inline_tn),
))),
factory: None,
},
);
tn.options.parse.named_prepare.insert(
engine_block::MD_PREPARE.to_string(),
tabnas::ParsePrepare::Context(Arc::new(engine_block::make_md_prepare(opts))),
);
let token = |name: &str| tins[name];
let slot: Vec<tabnas::Tin> = std::iter::once(token(engine_block::LINE_TOKEN))
.chain(engine_block::NODE_RULES.iter().map(|n| token(n.token)))
.collect();
let finish = engine_block::make_md_finish(opts, Arc::clone(&inline_tn));
tn.define_rule("markdown", |rs| {
rs.clear();
let mut begin = AltSpec {
p: Some("children".to_string()),
..Default::default()
};
begin.add_action(engine_block::md_begin);
rs.add_open(begin);
let mut end = AltSpec {
s: vec![vec![TIN_ZZ]],
..Default::default()
};
end.add_action(finish);
rs.add_close(end);
});
tn.define_rule("children", |rs| {
rs.clear();
for n in engine_block::NODE_RULES {
rs.add_open(AltSpec {
s: vec![vec![token(n.token)]],
b: 1,
p: Some(n.rule.to_string()),
g: if n.gfm {
"gfm".to_string()
} else {
String::new()
},
..Default::default()
});
}
rs.add_open(AltSpec {
s: vec![vec![token(engine_block::LINE_TOKEN)]],
..Default::default()
});
rs.add_open(AltSpec::default());
rs.add_close(AltSpec {
s: vec![slot.clone()],
b: 1,
r: Some("children".to_string()),
..Default::default()
});
rs.add_close(AltSpec::default());
});
for n in engine_block::NODE_RULES {
tn.define_rule(n.rule, |rs| {
rs.clear();
if n.container {
let mut open = AltSpec {
s: vec![vec![token(n.token)]],
p: Some("children".to_string()),
..Default::default()
};
open.add_action(engine_block::md_open);
rs.add_open(open);
let mut close = AltSpec {
s: vec![vec![token(engine_block::END_TOKEN)]],
..Default::default()
};
close.add_action(engine_block::md_close);
rs.add_close(close);
} else {
let mut open = AltSpec {
s: vec![vec![token(n.token)]],
..Default::default()
};
open.add_action(engine_block::md_leaf);
rs.add_open(open);
rs.add_close(AltSpec::default());
}
});
}
Ok(())
}
fn empty_document() -> Value {
let mut map = indexmap::IndexMap::with_capacity(2);
map.insert("type".to_string(), Value::String("document".to_string()));
map.insert("children".to_string(), Value::array(Vec::new()));
Value::object(map)
}
pub fn plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |tn, options| {
markdown(tn, &Options::resolve(options))
})
.with_defaults(DEFAULT_OPTIONS.to_value())
}
pub fn make_with(options: &Options) -> Tabnas {
let mut tn = Tabnas::new();
tn.use_plugin(plugin(), Some(options.to_value()))
.expect("the Markdown plugin installs on a bare engine");
tn.set_options(|o| o.lex.window = true)
.expect("the window option installs on the parser this package makes");
tn
}
pub fn make() -> Tabnas {
make_with(&DEFAULT_OPTIONS)
}
pub fn parse(src: &str) -> Result<Value, MarkdownError> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
DEFAULT.get_or_init(make).parse(src)
}
pub fn parse_keep_tree(tn: &Tabnas, src: &str) -> Result<(Value, Option<Tree>), MarkdownError> {
let _ = engine_block::take_kept_tree();
let mut md = indexmap::IndexMap::with_capacity(1);
md.insert("keepTree".to_string(), Value::Bool(true));
let mut meta = indexmap::IndexMap::with_capacity(1);
meta.insert("md".to_string(), Value::object(md));
let ast = tn.parse_with_meta(src, Value::object(meta))?;
Ok((ast, engine_block::take_kept_tree()))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
pub entry: &'static str,
pub source: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
pub manifest: &'static str,
pub lift: Option<TranslationPart>,
pub embed: Option<TranslationPart>,
pub render: Option<TranslationPart>,
pub transduce: Option<TranslationPart>,
}
const TRANSLATION: TranslationParts = TranslationParts {
manifest: include_str!("../translate/manifest.json"),
lift: Some(TranslationPart {
entry: "markdown-lift",
source: Some(include_str!("../translate/lift.alc")),
}),
embed: None,
render: Some(TranslationPart {
entry: "markdown-render",
source: Some(include_str!("../translate/render.alc")),
}),
transduce: Some(TranslationPart {
entry: "markdown-transduce",
source: Some(include_str!("../translate/transduce.alc")),
}),
};
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
Some(TRANSLATION)
}
pub fn manifest_text() -> &'static str {
TRANSLATION.manifest
}
pub fn lift_text() -> &'static str {
match TRANSLATION.lift {
Some(part) => part.source.unwrap_or_default(),
None => "",
}
}
pub fn transduce_text() -> &'static str {
match TRANSLATION.transduce {
Some(part) => part.source.unwrap_or_default(),
None => "",
}
}
pub fn render_text() -> &'static str {
match TRANSLATION.render {
Some(part) => part.source.unwrap_or_default(),
None => "",
}
}