| 1 |
use std::cmp; |
| 2 |
use std::fmt::{self, Write}; |
| 3 |
|
| 4 |
use crate::character_set::character_set; |
| 5 |
use crate::node_matches; |
| 6 |
use crate::nodes::{ListType, NodeCode, NodeMath, NodeValue}; |
| 7 |
use crate::nodes::{Node, NodeHtmlBlock}; |
| 8 |
use crate::parser::options::{Options, Plugins}; |
| 9 |
|
| 10 |
const MAX_INDENT: u32 = 40; |
| 11 |
|
| 12 |
/// Formats an AST as HTML, modified by the given options. |
| 13 |
pub fn format_document(root: Node<'_>, options: &Options, output: &mut dyn Write) -> fmt::Result { |
| 14 |
// Validate the AST as part of the debug build. See https://github.com/kivikakk/comrak/issues/371. |
| 15 |
#[cfg(debug_assertions)] |
| 16 |
root.validate().unwrap_or_else(|e| { |
| 17 |
panic!("The document to format is ill-formed: {:?}", e); |
| 18 |
}); |
| 19 |
|
| 20 |
format_document_with_plugins(root, options, output, &Plugins::default()) |
| 21 |
} |
| 22 |
|
| 23 |
/// Formats an AST as HTML, modified by the given options. Accepts custom plugins. |
| 24 |
pub fn format_document_with_plugins( |
| 25 |
root: Node<'_>, |
| 26 |
options: &Options, |
| 27 |
output: &mut dyn Write, |
| 28 |
plugins: &Plugins, |
| 29 |
) -> fmt::Result { |
| 30 |
output.write_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")?; |
| 31 |
output.write_str("<!DOCTYPE document SYSTEM \"CommonMark.dtd\">\n")?; |
| 32 |
|
| 33 |
XmlFormatter::new(options, output, plugins).format(root, false) |
| 34 |
} |
| 35 |
|
| 36 |
struct XmlFormatter<'o, 'c> { |
| 37 |
output: &'o mut dyn Write, |
| 38 |
options: &'o Options<'c>, |
| 39 |
_plugins: &'o Plugins<'o>, |
| 40 |
indent: u32, |
| 41 |
} |
| 42 |
|
| 43 |
impl<'o, 'c> XmlFormatter<'o, 'c> { |
| 44 |
fn new(options: &'o Options<'c>, output: &'o mut dyn Write, plugins: &'o Plugins) -> Self { |
| 45 |
XmlFormatter { |
| 46 |
options, |
| 47 |
output, |
| 48 |
_plugins: plugins, |
| 49 |
indent: 0, |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
fn escape(&mut self, buffer: &str) -> fmt::Result { |
| 54 |
let bytes = buffer.as_bytes(); |
| 55 |
const XML_UNSAFE: [bool; 256] = character_set!(b"&<>\"\0"); |
| 56 |
|
| 57 |
let mut offset = 0; |
| 58 |
for (i, &byte) in bytes.iter().enumerate() { |
| 59 |
if XML_UNSAFE[byte as usize] { |
| 60 |
let esc: &str = match byte { |
| 61 |
b'"' => """, |
| 62 |
b'&' => "&", |
| 63 |
b'<' => "<", |
| 64 |
b'>' => ">", |
| 65 |
b'\0' => "\u{fffd}", |
| 66 |
_ => unreachable!(), |
| 67 |
}; |
| 68 |
self.output.write_str(&buffer[offset..i])?; |
| 69 |
self.output.write_str(esc)?; |
| 70 |
offset = i + 1; |
| 71 |
} |
| 72 |
} |
| 73 |
self.output.write_str(&buffer[offset..])?; |
| 74 |
Ok(()) |
| 75 |
} |
| 76 |
|
| 77 |
fn format(&mut self, node: Node<'_>, plain: bool) -> fmt::Result { |
| 78 |
// Traverse the AST iteratively using a work stack, with pre- and |
| 79 |
// post-child-traversal phases. During pre-order traversal render the |
| 80 |
// opening tags, then push the node back onto the stack for the |
| 81 |
// post-order traversal phase, then push the children in reverse order |
| 82 |
// onto the stack and begin rendering first child. |
| 83 |
|
| 84 |
enum Phase { |
| 85 |
Pre, |
| 86 |
Post, |
| 87 |
} |
| 88 |
let mut stack = vec![(node, plain, Phase::Pre)]; |
| 89 |
|
| 90 |
while let Some((node, plain, phase)) = stack.pop() { |
| 91 |
match phase { |
| 92 |
Phase::Pre => { |
| 93 |
let new_plain = if plain { |
| 94 |
match node.data().value { |
| 95 |
NodeValue::Text(ref literal) => { |
| 96 |
self.escape(literal)?; |
| 97 |
} |
| 98 |
NodeValue::Code(NodeCode { ref literal, .. }) |
| 99 |
| NodeValue::HtmlInline(ref literal) |
| 100 |
| NodeValue::Raw(ref literal) => { |
| 101 |
self.escape(literal)?; |
| 102 |
} |
| 103 |
NodeValue::LineBreak | NodeValue::SoftBreak => { |
| 104 |
self.output.write_str(" ")?; |
| 105 |
} |
| 106 |
NodeValue::Math(NodeMath { ref literal, .. }) => { |
| 107 |
self.escape(literal)?; |
| 108 |
} |
| 109 |
_ => (), |
| 110 |
} |
| 111 |
plain |
| 112 |
} else { |
| 113 |
stack.push((node, false, Phase::Post)); |
| 114 |
self.format_node(node, true)?; |
| 115 |
false |
| 116 |
}; |
| 117 |
|
| 118 |
for ch in node.reverse_children() { |
| 119 |
stack.push((ch, new_plain, Phase::Pre)); |
| 120 |
} |
| 121 |
} |
| 122 |
Phase::Post => { |
| 123 |
debug_assert!(!plain); |
| 124 |
self.format_node(node, false)?; |
| 125 |
} |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
Ok(()) |
| 130 |
} |
| 131 |
|
| 132 |
fn indent(&mut self) -> fmt::Result { |
| 133 |
for _ in 0..(cmp::min(self.indent, MAX_INDENT)) { |
| 134 |
self.output.write_str(" ")?; |
| 135 |
} |
| 136 |
Ok(()) |
| 137 |
} |
| 138 |
|
| 139 |
fn format_node(&mut self, node: Node<'_>, entering: bool) -> fmt::Result { |
| 140 |
if !self.options.render.escaped_char_spans && node_matches!(node, NodeValue::Escaped) { |
| 141 |
return Ok(()); |
| 142 |
} |
| 143 |
|
| 144 |
if entering { |
| 145 |
self.indent()?; |
| 146 |
|
| 147 |
let ast = node.data(); |
| 148 |
|
| 149 |
write!(self.output, "<{}", ast.value.xml_node_name())?; |
| 150 |
|
| 151 |
if self.options.render.sourcepos && ast.sourcepos.start.line != 0 { |
| 152 |
write!(self.output, " sourcepos=\"{}\"", ast.sourcepos)?; |
| 153 |
} |
| 154 |
|
| 155 |
let mut was_literal = false; |
| 156 |
|
| 157 |
match ast.value { |
| 158 |
NodeValue::Document => self |
| 159 |
.output |
| 160 |
.write_str(" xmlns=\"http://commonmark.org/xml/1.0\"")?, |
| 161 |
NodeValue::Text(ref literal) => { |
| 162 |
self.output.write_str(" xml:space=\"preserve\">")?; |
| 163 |
self.escape(literal)?; |
| 164 |
write!(self.output, "</{}", ast.value.xml_node_name())?; |
| 165 |
was_literal = true; |
| 166 |
} |
| 167 |
NodeValue::Code(NodeCode { ref literal, .. }) |
| 168 |
| NodeValue::HtmlBlock(NodeHtmlBlock { ref literal, .. }) |
| 169 |
| NodeValue::HtmlInline(ref literal) |
| 170 |
| NodeValue::Raw(ref literal) => { |
| 171 |
self.output.write_str(" xml:space=\"preserve\">")?; |
| 172 |
self.escape(literal)?; |
| 173 |
write!(self.output, "</{}", ast.value.xml_node_name())?; |
| 174 |
was_literal = true; |
| 175 |
} |
| 176 |
#[cfg(feature = "phoenix_heex")] |
| 177 |
NodeValue::HeexBlock(ref nhb) => { |
| 178 |
self.output.write_str(" xml:space=\"preserve\">")?; |
| 179 |
self.escape(&nhb.literal)?; |
| 180 |
write!(self.output, "</{}", ast.value.xml_node_name())?; |
| 181 |
was_literal = true; |
| 182 |
} |
| 183 |
#[cfg(feature = "phoenix_heex")] |
| 184 |
NodeValue::HeexInline(ref literal) => { |
| 185 |
self.output.write_str(" xml:space=\"preserve\">")?; |
| 186 |
self.escape(literal)?; |
| 187 |
write!(self.output, "</{}", ast.value.xml_node_name())?; |
| 188 |
was_literal = true; |
| 189 |
} |
| 190 |
NodeValue::List(ref nl) => { |
| 191 |
match nl.list_type { |
| 192 |
ListType::Bullet => { |
| 193 |
self.output.write_str(" type=\"bullet\"")?; |
| 194 |
} |
| 195 |
ListType::Ordered => { |
| 196 |
write!( |
| 197 |
self.output, |
| 198 |
" type=\"ordered\" start=\"{}\" delim=\"{}\"", |
| 199 |
nl.start, |
| 200 |
nl.delimiter.xml_name() |
| 201 |
)?; |
| 202 |
} |
| 203 |
} |
| 204 |
if nl.is_task_list { |
| 205 |
self.output.write_str(" tasklist=\"true\"")?; |
| 206 |
} |
| 207 |
write!(self.output, " tight=\"{}\"", nl.tight)?; |
| 208 |
} |
| 209 |
NodeValue::FrontMatter(_) => (), |
| 210 |
NodeValue::BlockQuote => {} |
| 211 |
NodeValue::MultilineBlockQuote(..) => {} |
| 212 |
NodeValue::Item(..) => {} |
| 213 |
NodeValue::DescriptionList => {} |
| 214 |
NodeValue::DescriptionItem(..) => (), |
| 215 |
NodeValue::DescriptionTerm => {} |
| 216 |
NodeValue::DescriptionDetails => {} |
| 217 |
NodeValue::Heading(ref nh) => { |
| 218 |
write!(self.output, " level=\"{}\"", nh.level)?; |
| 219 |
} |
| 220 |
NodeValue::CodeBlock(ref ncb) => { |
| 221 |
if !ncb.info.is_empty() { |
| 222 |
self.output.write_str(" info=\"")?; |
| 223 |
self.output.write_str(&ncb.info)?; |
| 224 |
self.output.write_str("\"")?; |
| 225 |
|
| 226 |
if ncb.info.eq("math") { |
| 227 |
self.output.write_str(" math_style=\"display\"")?; |
| 228 |
} |
| 229 |
} |
| 230 |
self.output.write_str(" xml:space=\"preserve\">")?; |
| 231 |
self.escape(&ncb.literal)?; |
| 232 |
write!(self.output, "</{}", ast.value.xml_node_name())?; |
| 233 |
was_literal = true; |
| 234 |
} |
| 235 |
NodeValue::ThematicBreak => {} |
| 236 |
NodeValue::Paragraph => {} |
| 237 |
NodeValue::LineBreak => {} |
| 238 |
NodeValue::SoftBreak => {} |
| 239 |
NodeValue::Strong => {} |
| 240 |
NodeValue::Emph => {} |
| 241 |
NodeValue::Strikethrough => {} |
| 242 |
NodeValue::Highlight => {} |
| 243 |
NodeValue::Insert => {} |
| 244 |
NodeValue::Superscript => {} |
| 245 |
NodeValue::Link(ref nl) | NodeValue::Image(ref nl) => { |
| 246 |
self.output.write_str(" destination=\"")?; |
| 247 |
self.escape(&nl.url)?; |
| 248 |
self.output.write_str("\" title=\"")?; |
| 249 |
self.escape(&nl.title)?; |
| 250 |
self.output.write_str("\"")?; |
| 251 |
} |
| 252 |
NodeValue::Table(..) => { |
| 253 |
// noop |
| 254 |
} |
| 255 |
NodeValue::TableRow(..) => { |
| 256 |
// noop |
| 257 |
} |
| 258 |
NodeValue::TableCell => { |
| 259 |
let mut ancestors = node.ancestors().skip(1); |
| 260 |
|
| 261 |
let header_row = &ancestors.next().unwrap().data().value; |
| 262 |
let table = &ancestors.next().unwrap().data().value; |
| 263 |
|
| 264 |
if let (NodeValue::TableRow(true), NodeValue::Table(nt)) = (header_row, table) { |
| 265 |
let ix = node.preceding_siblings().count() - 1; |
| 266 |
if let Some(xml_align) = nt.alignments[ix].xml_name() { |
| 267 |
write!(self.output, " align=\"{}\"", xml_align)?; |
| 268 |
} |
| 269 |
} |
| 270 |
} |
| 271 |
NodeValue::FootnoteDefinition(ref fd) => { |
| 272 |
self.output.write_str(" label=\"")?; |
| 273 |
self.escape(&fd.name)?; |
| 274 |
self.output.write_str("\"")?; |
| 275 |
} |
| 276 |
NodeValue::FootnoteReference(ref nfr) => { |
| 277 |
self.output.write_str(" label=\"")?; |
| 278 |
self.escape(&nfr.name)?; |
| 279 |
self.output.write_str("\"")?; |
| 280 |
} |
| 281 |
NodeValue::TaskItem(ref nti) => { |
| 282 |
if nti.symbol.is_some() { |
| 283 |
self.output.write_str(" completed=\"true\"")?; |
| 284 |
} else { |
| 285 |
self.output.write_str(" completed=\"false\"")?; |
| 286 |
} |
| 287 |
} |
| 288 |
#[cfg(feature = "shortcodes")] |
| 289 |
NodeValue::ShortCode(ref nsc) => { |
| 290 |
self.output.write_str(" id=\"")?; |
| 291 |
self.escape(&nsc.code)?; |
| 292 |
self.output.write_str("\"")?; |
| 293 |
} |
| 294 |
NodeValue::Escaped => { |
| 295 |
// noop |
| 296 |
} |
| 297 |
NodeValue::Math(ref math, ..) => { |
| 298 |
if math.display_math { |
| 299 |
self.output.write_str(" math_style=\"display\"")?; |
| 300 |
} else { |
| 301 |
self.output.write_str(" math_style=\"inline\"")?; |
| 302 |
} |
| 303 |
self.output.write_str(" xml:space=\"preserve\">")?; |
| 304 |
self.escape(&math.literal)?; |
| 305 |
write!(self.output, "</{}", ast.value.xml_node_name())?; |
| 306 |
was_literal = true; |
| 307 |
} |
| 308 |
NodeValue::WikiLink(ref nl) => { |
| 309 |
self.output.write_str(" destination=\"")?; |
| 310 |
self.escape(&nl.url)?; |
| 311 |
self.output.write_str("\"")?; |
| 312 |
} |
| 313 |
NodeValue::Underline => {} |
| 314 |
NodeValue::Subscript => {} |
| 315 |
NodeValue::SpoileredText => {} |
| 316 |
NodeValue::EscapedTag(data) => { |
| 317 |
self.output.write_str(data)?; |
| 318 |
} |
| 319 |
NodeValue::Alert(ref alert) => { |
| 320 |
self.output.write_str(" type=\"")?; |
| 321 |
self.output |
| 322 |
.write_str(&alert.alert_type.default_title().to_lowercase())?; |
| 323 |
self.output.write_str("\"")?; |
| 324 |
if let Some(title) = &alert.title { |
| 325 |
self.output.write_str(" title=\"")?; |
| 326 |
self.escape(title)?; |
| 327 |
self.output.write_str("\"")?; |
| 328 |
} |
| 329 |
|
| 330 |
if alert.multiline { |
| 331 |
self.output.write_str(" multiline=\"true\"")?; |
| 332 |
} |
| 333 |
} |
| 334 |
NodeValue::Subtext => {} |
| 335 |
NodeValue::BlockDirective(ref nbd) => { |
| 336 |
self.output.write_str(" info=\"")?; |
| 337 |
self.escape(&nbd.info)?; |
| 338 |
self.output.write_str("\"")?; |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
if node.first_child().is_some() { |
| 343 |
self.indent += 2; |
| 344 |
} else if !was_literal { |
| 345 |
self.output.write_str(" /")?; |
| 346 |
} |
| 347 |
self.output.write_str(">\n")?; |
| 348 |
} else if node.first_child().is_some() { |
| 349 |
self.indent -= 2; |
| 350 |
self.indent()?; |
| 351 |
writeln!(self.output, "</{}>", node.data().value.xml_node_name())?; |
| 352 |
} |
| 353 |
Ok(()) |
| 354 |
} |
| 355 |
} |