[&mut] [Context], giving access to rendering
/// options, plugins, and output appending via its [Write]
/// implementation.
/// * `node`: the [&][&][Node] being formatted, when the
/// [`NodeValue`]'s contents aren't enough.
/// * `entering`: [`true`] when the node is being first descended into,
/// [`false`] when being exited.
///
/// By default, an overridden formatter will return [`ChildRendering::HTML`],
/// causing children of the node to be rendered as HTML as usual. You can
/// return one of these enum values (wrapped in [`Ok`]) from within your
/// override to change this behaviour, in some or all cases. These values are
/// only noted when `entering` a node.
///
/// If you supply a type parameter after the name of your formatter, it will be
/// taken as an additional argument on the generated `format_document` method,
/// is available on the [`Context`] as the `user` property, and becomes the
/// return value of `format_document`.
///
/// ```rust
/// # use comrak::{create_formatter, parse_document, Arena, Options, nodes::NodeValue, html::ChildRendering};
/// # use std::fmt::Write;
/// create_formatter!(CustomFormatterHello, world.
\n/IMG.PNG
\n" /// ); /// /// assert_eq!(converted_count, 4); /// ``` #[macro_export] macro_rules! create_formatter { ($name:ident, { $( $pat:pat => | $( $capture:ident ),* | $case:tt ),* $(,)? }) => { $crate::create_formatter!(@inner $name<()>, { $( $pat => | $( $capture ),* | $case ),*, }); }; ($name:ident<$type:ty>, { $( $pat:pat => | $( $capture:ident ),* | $case:tt ),* $(,)? }) => { $crate::create_formatter!(@inner $name<$type, $type>, { $( $pat => | $( $capture ),* | $case ),*, }); }; // Actual implementation (@inner $name:ident<$type:ty $(, $user_type:ty)?>, { $( $pat:pat => | $( $capture:ident ),* | $case:tt ),* $(,)? }) => { #[allow(missing_copy_implementations)] #[allow(missing_debug_implementations)] /// Created by [`comrak::create_formatter!`][crate::create_formatter]. pub struct $name; impl $name { /// Formats an AST as HTML, modified by the given options. #[inline] pub fn format_document<'a>( root: &'a $crate::nodes::AstNode<'a>, options: &$crate::Options, output: &mut dyn ::std::fmt::Write, $(user: $user_type,)? ) -> ::std::result::Result<$type, ::std::fmt::Error> { // Validate the AST as part of the debug build. See https://github.com/kivikakk/comrak/issues/371. #[cfg(debug_assertions)] root.validate().unwrap_or_else(|e| { panic!("The document to format is ill-formed: {:?}", e); }); #[allow(unused_mut)] let mut maybe_user = None$(::<$user_type>)?; $(maybe_user = Some::<$user_type>(user);)? $crate::html::format_document_with_formatter( root, options, output, &$crate::options::Plugins::default(), Self::formatter, maybe_user.unwrap_or(<$type>::default()), ) } /// Formats an AST as HTML, modified by the given options. Accepts custom plugins. #[inline] pub fn format_document_with_plugins<'a, 'o, 'c: 'o>( root: &'a $crate::nodes::AstNode<'a>, options: &'o $crate::Options<'c>, output: &'o mut dyn ::std::fmt::Write, plugins: &'o $crate::options::Plugins<'o>, $(user: $user_type,)? ) -> ::std::result::Result<$type, ::std::fmt::Error> { #[allow(unused_mut)] let mut maybe_user = None$(::<$user_type>)?; $(maybe_user = Some::<$user_type>(user);)? $crate::html::format_document_with_formatter( root, options, output, plugins, Self::formatter, maybe_user.unwrap_or(<$type>::default()), ) } fn formatter<'a>( context: &mut $crate::html::Context<$type>, node: &'a $crate::nodes::AstNode<'a>, entering: bool, ) -> ::std::result::Result<$crate::html::ChildRendering, ::std::fmt::Error> { match node.data().value { $( $pat => { $crate::formatter_captures!((context, node, entering), ($( $capture ),*)); $case // Don't warn on unconditional return in user code. #[allow(unreachable_code)] ::std::result::Result::Ok($crate::html::ChildRendering::HTML) } ),* _ => $crate::html::format_node_default(context, node, entering), } } } }; } /// This must be exported so its uses in [`create_formatter!`] can be expanded, /// but it's not intended for direct use. #[doc(hidden)] #[macro_export] macro_rules! formatter_captures { (($context:ident, $node:ident, $entering:ident), context, $bind:ident) => { let $bind = $context; }; (($context:ident, $node:ident, $entering:ident), node, $bind:ident) => { let $bind = $node; }; (($context:ident, $node:ident, $entering:ident), entering, $bind:ident) => { let $bind = $entering; }; (($context:ident, $node:ident, $entering:ident), $unknown:ident, $bind:ident) => { compile_error!(concat!("unknown capture '", stringify!($unknown), "'; available are 'context', 'node', 'entering'")); }; (($context:ident, $node:ident, $entering:ident), ($capture:ident)) => { $crate::formatter_captures!(($context, $node, $entering), $capture, $capture); }; (($context:ident, $node:ident, $entering:ident), ($capture:ident, $( $rest:ident ),*)) => { $crate::formatter_captures!(($context, $node, $entering), $capture, $capture); $crate::formatter_captures!(($context, $node, $entering), ($( $rest ),*)); }; } /// Formats the given AST with all options and formatter function specified. /// /// The default formatter as used by [`format_document`] is /// [`format_node_default`]. It is given the [`Context`], [`Node`], and a /// boolean indicating whether the node is being entered into or exited. The /// returned [`ChildRendering`] is used to inform whether and how the node's /// children are recursed into automatically. pub fn format_document_with_formatter<'a, 'o, 'c: 'o, T>( root: Node<'a>, options: &'o Options<'c>, output: &'o mut dyn Write, plugins: &'o Plugins<'o>, formatter: fn( context: &mut Context")?; context.lf()?; } else { context.cr()?; context.write_str("")?; context.lf()?; } Ok(ChildRendering::HTML) } fn render_code
")?;
context.escape(&nc.literal)?;
context.write_str("")?;
}
Ok(ChildRendering::HTML)
}
fn render_code_block")?; } else { if let Some(parent) = node.parent() { if let NodeValue::FootnoteDefinition(ref nfd) = parent.data().value { if node.next_sibling().is_none() { context.write_str(" ")?; put_footnote_backref(context, nfd)?; } } } context.write_str("
")?; context.lf()?; } } Ok(ChildRendering::HTML) } fn render_soft_break`.
pub fn render_math_code_block(
context: &mut Context,
node: Node<'_>,
literal: &str,
) -> Result {
context.cr()?;
// use vectors to ensure attributes always written in the same order,
// for testing stability
let mut pre_attributes: Vec<(&str, Cow)> = Vec::new();
let mut code_attributes: Vec<(&str, Cow)> = Vec::new();
let lang_str = "math";
if context.options.render.github_pre_lang {
pre_attributes.push(("lang", lang_str.into()));
pre_attributes.push(("data-math-style", "display".into()));
} else {
let code_attr = format!("language-{}", lang_str);
code_attributes.push(("class", code_attr.into()));
code_attributes.push(("data-math-style", "display".into()));
}
if context.options.render.sourcepos {
let ast = node.data();
pre_attributes.push(("data-sourcepos", ast.sourcepos.to_string().into()));
}
write_opening_tag(context, "pre", pre_attributes.into_iter())?;
write_opening_tag(context, "code", code_attributes.into_iter())?;
context.escape(literal)?;
context.write_str(" ")?;
context.lf()?;
Ok(ChildRendering::HTML)
}
fn render_multiline_block_quote")?; context.lf()?; } else { context.cr()?; context.write_str("")?; context.lf()?; } Ok(ChildRendering::HTML) } fn render_raw
")?; } else { write!(context, "
")?; context.lf()?; } Ok(ChildRendering::HTML) } fn render_superscript