Debian Codegraph @

src/cm.rs

raw
1 use std::cmp::max;
2 use std::collections::HashSet;
3 use std::fmt::{self, Write};
4 use std::str;
5
6 use crate::Arena;
7 use crate::ctype::{isalpha, isdigit, ispunct, ispunct_char, isspace, isspace_char};
8 use crate::nodes::{
9 ListDelimType, ListType, Node, NodeAlert, NodeBlockDirective, NodeCodeBlock, NodeHeading,
10 NodeHtmlBlock, NodeLink, NodeList, NodeMath, NodeTaskItem, NodeValue, NodeWikiLink,
11 TableAlignment,
12 };
13 use crate::parser::options::{Options, Plugins, WikiLinksMode};
14 #[cfg(feature = "phoenix_heex")]
15 use crate::parser::phoenix_heex::NodeHeexBlock;
16 #[cfg(feature = "shortcodes")]
17 use crate::parser::shortcodes::NodeShortCode;
18 use crate::scanners;
19 use crate::strings::trim_start_match;
20 use crate::{node_matches, strings};
21
22 /// Formats an AST as CommonMark, modified by the given options.
23 pub fn format_document(root: Node<'_>, options: &Options, output: &mut dyn Write) -> fmt::Result {
24 // Formatting an ill-formed AST might lead to invalid output. However, we don't want to pay for
25 // validation in normal workflow. As a middleground, we validate the AST in debug builds. See
26 // https://github.com/kivikakk/comrak/issues/371.
27 #[cfg(debug_assertions)]
28 root.validate().unwrap_or_else(|e| {
29 panic!("The document to format is ill-formed: {:?}", e);
30 });
31
32 format_document_with_plugins(root, options, output, &Plugins::default())
33 }
34
35 /// Formats an AST as CommonMark, modified by the given options. Accepts custom plugins.
36 pub fn format_document_with_plugins(
37 root: Node<'_>,
38 options: &Options,
39 output: &mut dyn Write,
40 _plugins: &Plugins,
41 ) -> fmt::Result {
42 if !options.render.experimental_minimize_commonmark {
43 return format_internal(root, options, output);
44 }
45
46 let mut result = String::new();
47 format_internal(root, options, &mut result)?;
48 minimize_commonmark(&mut result, options);
49
50 output.write_str(&result)
51 }
52
53 // Doesn't honour experimental_minimize_commonmark.
54 fn format_internal(root: Node<'_>, options: &Options, output: &mut dyn Write) -> fmt::Result {
55 let mut f = CommonMarkFormatter::new(root, options, output);
56 f.format(root)
57 }
58
59 struct CommonMarkFormatter<'a, 'o, 'c, 'w> {
60 node: Node<'a>,
61 options: &'o Options<'c>,
62 output: &'w mut dyn Write,
63 /// Buffer used by wrapping implementation; flushed on newline or wrapping
64 /// event.
65 wrap_buffer: String,
66 /// The last two bytes written (to output or wrap_buffer).
67 window: Vec<u8>,
68 /// Contains some assortment of:
69 ///
70 /// * "> " when formatting within a blockquote.
71 /// * " "*n when formatting within a list item (n≥2).
72 /// * " " when formatting within a fenced code block.
73 /// * " " when formatting within a footnote definition.
74 /// * "> " when formatting within an alert.
75 ///
76 /// A prefix when non-empty is therefore guaranteed to have a length of at
77 /// least two. This is relevant in write_prefix.
78 prefix: String,
79 column: usize,
80 need_cr: u8,
81 last_breakable: usize,
82 begin_line: bool,
83 begin_content: bool,
84 no_linebreaks: bool,
85 in_tight_list_item: bool,
86 custom_escape: Option<fn(Node<'a>, char) -> bool>,
87 footnote_ix: u32,
88 ol_stack: Vec<usize>,
89 allow_wrap: bool,
90 }
91
92 #[derive(PartialEq, Clone, Copy)]
93 enum Escaping {
94 Literal,
95 Normal,
96 Url,
97 Title,
98 }
99
100 impl Write for CommonMarkFormatter<'_, '_, '_, '_> {
101 fn write_str(&mut self, s: &str) -> fmt::Result {
102 self.output(s, false, Escaping::Literal)
103 }
104 }
105
106 impl<'a, 'o, 'c, 'w> CommonMarkFormatter<'a, 'o, 'c, 'w> {
107 fn new(node: Node<'a>, options: &'o Options<'c>, output: &'w mut dyn Write) -> Self {
108 CommonMarkFormatter {
109 node,
110 options,
111 output,
112 wrap_buffer: String::new(),
113 window: Vec::with_capacity(2),
114 prefix: String::new(),
115 column: 0,
116 need_cr: 0,
117 last_breakable: 0,
118 begin_line: true,
119 begin_content: true,
120 no_linebreaks: false,
121 in_tight_list_item: false,
122 custom_escape: None,
123 footnote_ix: 0,
124 ol_stack: vec![],
125 allow_wrap: options.render.width > 0 && !options.render.hardbreaks,
126 }
127 }
128
129 /// Writes to self.output, or self.buffer if we're wrapping output, and
130 /// update self.window.
131 fn write(&mut self, s: &str) -> fmt::Result {
132 if s.is_empty() {
133 return Ok(());
134 }
135 // We maintain a window size of 2 bytes at most.
136 if s.len() > 1 {
137 self.window.clear();
138 self.window.extend_from_slice(&s.as_bytes()[s.len() - 2..]);
139 } else {
140 assert_eq!(s.len(), 1);
141 if self.window.len() == 2 {
142 self.window.remove(0);
143 } else {
144 assert!(self.window.len() < 2);
145 }
146 self.window.push(s.as_bytes()[0]);
147 }
148
149 let last_was_cr = self.window.last() == Some(&b'\n');
150
151 if self.options.render.width == 0 {
152 self.output.write_str(s)?;
153 } else if last_was_cr {
154 // Can flush.
155 self.output.write_str(&self.wrap_buffer)?;
156 self.output.write_str(s)?;
157 self.wrap_buffer.clear();
158 } else {
159 self.wrap_buffer.push_str(s);
160 }
161
162 if last_was_cr {
163 self.column = 0;
164 self.begin_line = true;
165 self.begin_content = true;
166 self.last_breakable = 0;
167 }
168
169 Ok(())
170 }
171
172 fn write_prefix(&mut self) -> fmt::Result {
173 // A non-empty prefix is guaranteed to have a length of at least two.
174 if self.prefix.is_empty() {
175 return Ok(());
176 }
177 if self.options.render.width == 0 {
178 self.output.write_str(&self.prefix)?;
179 } else {
180 self.wrap_buffer.push_str(&self.prefix);
181 }
182 self.window.clear();
183 self.window
184 .extend_from_slice(&self.prefix.as_bytes()[self.prefix.len() - 2..]);
185 Ok(())
186 }
187
188 fn output(&mut self, s: &str, wrap: bool, escaping: Escaping) -> fmt::Result {
189 let bytes = s.as_bytes();
190 let wrap = self.allow_wrap && wrap && !self.no_linebreaks;
191
192 if self.in_tight_list_item && self.need_cr > 1 {
193 self.need_cr = 1;
194 }
195
196 let mut last_crs_consume = self
197 .window
198 .iter()
199 .rev()
200 .take_while(|&&b| b == b'\n')
201 .count();
202 while self.need_cr > 0 {
203 if self.window.is_empty() {
204 // nvm
205 } else if last_crs_consume > 0 {
206 last_crs_consume -= 1;
207 } else {
208 self.write("\n")?;
209 if self.need_cr > 1 {
210 self.write_prefix()?;
211 self.column = self.prefix.len();
212 }
213 }
214 self.need_cr -= 1;
215 }
216
217 let mut it = s.char_indices();
218
219 while let Some((mut i, c)) = it.next() {
220 if self.begin_line {
221 self.write_prefix()?;
222 self.column = self.prefix.len();
223 }
224
225 if self.custom_escape.is_some_and(|f| f(self.node, c)) {
226 self.write("\\")?;
227 }
228
229 let nextb = bytes.get(i + 1);
230 if c == ' ' && wrap {
231 if !self.begin_line {
232 let last_nonspace = self.wrap_buffer.len();
233 self.write(" ")?;
234 self.column += 1;
235 self.begin_line = false;
236 self.begin_content = false;
237 while bytes.get(i + 1) == Some(&(b' ')) {
238 (i, _) = it.next().unwrap();
239 }
240 if !bytes.get(i + 1).is_some_and(|&c| isdigit(c)) {
241 self.last_breakable = last_nonspace;
242 }
243 }
244 } else if escaping == Escaping::Literal {
245 if bytes[i] == b'\n' {
246 self.write("\n")?;
247 } else {
248 let cs = char::to_string(&c);
249 self.write(&cs)?;
250 self.column += cs.len();
251 self.begin_line = false;
252 self.begin_content = self.begin_content && isdigit(bytes[i]);
253 }
254 } else {
255 self.outc(c, escaping, nextb)?;
256 self.begin_line = false;
257 self.begin_content = self.begin_content && isdigit(bytes[i]);
258 }
259
260 if self.options.render.width > 0
261 && self.column > self.options.render.width
262 && !self.begin_line
263 && self.last_breakable > 0
264 {
265 self.output
266 .write_str(&self.wrap_buffer[..self.last_breakable])?;
267 self.output.write_str("\n")?;
268 strings::remove_from_start(&mut self.wrap_buffer, self.last_breakable + 1);
269 self.wrap_buffer.insert_str(0, &self.prefix);
270 self.column = self.wrap_buffer.len();
271 self.last_breakable = 0;
272 self.begin_line = false;
273 self.begin_content = false;
274 }
275 }
276 Ok(())
277 }
278
279 fn outc(&mut self, c: char, escaping: Escaping, nextb: Option<&u8>) -> fmt::Result {
280 // NOTE: nextb contains the byte *immediately following the first byte of c*.
281 // If c is a multibyte character, nextb contains the second byte of c!
282 // We rely on it here *only* where we know c to be a single byte
283 // character, in which case it faithfully represents the first byte of the
284 // following character (or is None if the string ends).
285 // Any use of nextb must be conditional on asserting c is a single byte character.
286 let follows_digit = self.window.last().is_some_and(|&b| isdigit(b));
287
288 let nextb = nextb.map_or(0, |&c| c);
289
290 let needs_escaping = (c as u64) < 0x80
291 && escaping != Escaping::Literal
292 && ((escaping == Escaping::Normal
293 && ((c as u64) < 0x20
294 || c == '*'
295 || c == '_'
296 || c == '['
297 || c == ']'
298 || c == '#'
299 || c == '<'
300 || c == '>'
301 || c == '\\'
302 || c == '`'
303 || c == '~'
304 || c == '!'
305 || (self.options.extension.autolink && c == '@')
306 || (c == '&' && isalpha(nextb))
307 || (c == '!' && nextb == 0x5b)
308 || (self.begin_content
309 && self.options.extension.block_directive
310 && c == ':')
311 || (self.begin_content
312 && (c == '-' || c == '+' || c == '=')
313 && !follows_digit)
314 || (self.begin_content
315 && (c == '.' || c == ')')
316 && follows_digit
317 && (nextb == 0 || isspace(nextb)))))
318 || (escaping == Escaping::Url
319 && (c == '`'
320 || c == '<'
321 || c == '>'
322 || isspace_char(c)
323 || c == '\\'
324 || c == ')'
325 || c == '('))
326 || (escaping == Escaping::Title
327 && (c == '`' || c == '<' || c == '>' || c == '"' || c == '\\')));
328
329 if needs_escaping {
330 // (c as u64) < 256 is implied.
331 let out = if escaping == Escaping::Url && isspace_char(c) {
332 format!("%{:2X}", c as u8)
333 } else if ispunct_char(c) {
334 format!("\\{}", c)
335 } else if c == '\0' {
336 "\u{fffd}".to_string()
337 } else {
338 format!("&#{};", c as u8)
339 };
340 self.write(&out)?;
341 self.column += out.len();
342 } else {
343 let cs = char::to_string(&c);
344 self.write(&cs)?;
345 self.column += cs.len();
346 }
347
348 Ok(())
349 }
350
351 fn cr(&mut self) {
352 self.need_cr = max(self.need_cr, 1);
353 }
354
355 fn blankline(&mut self) {
356 self.need_cr = max(self.need_cr, 2);
357 }
358
359 fn format(&mut self, root: Node<'a>) -> fmt::Result {
360 enum Phase {
361 Pre,
362 Post,
363 }
364 let mut stack = vec![(root, Phase::Pre)];
365
366 while let Some((node, phase)) = stack.pop() {
367 match phase {
368 Phase::Pre => {
369 if self.format_node(node, true)? {
370 stack.push((node, Phase::Post));
371 for ch in node.reverse_children() {
372 stack.push((ch, Phase::Pre));
373 }
374 }
375 }
376 Phase::Post => {
377 self.format_node(node, false)?;
378 }
379 }
380 }
381
382 if !self.wrap_buffer.is_empty() {
383 self.output.write_str(&self.wrap_buffer)?;
384 }
385 if !self.window.is_empty() && self.window.last() != Some(&b'\n') {
386 self.output.write_str("\n")?;
387 }
388 Ok(())
389 }
390
391 fn get_in_tight_list_item(&self, node: Node<'a>) -> bool {
392 let tmp = match node.containing_block() {
393 Some(tmp) => tmp,
394 None => return false,
395 };
396
397 match tmp.data().value {
398 NodeValue::Item(..) | NodeValue::TaskItem(..) => {
399 if let NodeValue::List(ref nl) = tmp.parent().unwrap().data().value {
400 return nl.tight;
401 }
402 return false;
403 }
404 _ => {}
405 }
406
407 let parent = match tmp.parent() {
408 Some(parent) => parent,
409 None => return false,
410 };
411
412 match parent.data().value {
413 NodeValue::Item(..) | NodeValue::TaskItem(..) => {
414 if let NodeValue::List(ref nl) = parent.parent().unwrap().data().value {
415 return nl.tight;
416 }
417 }
418 _ => {}
419 }
420
421 false
422 }
423
424 fn format_node(&mut self, node: Node<'a>, entering: bool) -> Result<bool, fmt::Error> {
425 self.node = node;
426
427 let parent_node = node.parent();
428 if entering {
429 if parent_node.is_some()
430 && node_matches!(
431 parent_node.unwrap(),
432 NodeValue::Item(..) | NodeValue::TaskItem(..)
433 )
434 {
435 self.in_tight_list_item = self.get_in_tight_list_item(node);
436 }
437 } else if node_matches!(node, NodeValue::List(..)) {
438 self.in_tight_list_item = parent_node.is_some()
439 && node_matches!(
440 parent_node.unwrap(),
441 NodeValue::Item(..) | NodeValue::TaskItem(..)
442 )
443 && self.get_in_tight_list_item(node);
444 }
445 let next_is_block = node
446 .next_sibling()
447 .is_none_or(|next| next.data().value.block());
448 let text_in_cell = node_matches!(node, NodeValue::Text(..))
449 && parent_node.is_some_and(|n| node_matches!(n, NodeValue::TableCell));
450
451 match node.data().value {
452 NodeValue::Document => (),
453 NodeValue::FrontMatter(ref fm) => self.format_front_matter(fm, entering)?,
454 NodeValue::BlockQuote => self.format_block_quote(entering)?,
455 NodeValue::List(..) => self.format_list(node, entering)?,
456 NodeValue::Item(..) => self.format_item(node, entering)?,
457 NodeValue::DescriptionList => (),
458 NodeValue::DescriptionItem(..) => (),
459 NodeValue::DescriptionTerm => (),
460 NodeValue::DescriptionDetails => self.format_description_details(entering)?,
461 NodeValue::Heading(ref nh) => self.format_heading(nh, entering)?,
462 NodeValue::CodeBlock(ref ncb) => self.format_code_block(node, ncb, entering)?,
463 NodeValue::HtmlBlock(ref nhb) => self.format_html_block(nhb, entering)?,
464 #[cfg(feature = "phoenix_heex")]
465 NodeValue::HeexBlock(ref nhb) => self.format_heex_block(nhb, entering)?,
466 NodeValue::ThematicBreak => self.format_thematic_break(entering)?,
467 NodeValue::Paragraph => self.format_paragraph(entering),
468 NodeValue::Text(ref literal) => {
469 self.format_text(literal, node, entering, !text_in_cell)?
470 }
471 NodeValue::LineBreak => self.format_line_break(entering, next_is_block)?,
472 NodeValue::SoftBreak => self.format_soft_break(entering)?,
473 NodeValue::Code(ref code) => self.format_code(&code.literal, entering)?,
474 NodeValue::HtmlInline(ref literal) => self.format_html_inline(literal, entering)?,
475 #[cfg(feature = "phoenix_heex")]
476 NodeValue::HeexInline(ref literal) => self.format_heex_inline(literal, entering)?,
477 NodeValue::Raw(ref literal) => self.format_raw(literal, entering)?,
478 NodeValue::Strong => {
479 if parent_node.is_none() || !node_matches!(parent_node.unwrap(), NodeValue::Strong)
480 {
481 self.format_strong()?;
482 }
483 }
484 NodeValue::Emph => self.format_emph(node)?,
485 NodeValue::TaskItem(ref nti) => self.format_task_item(nti, node, entering)?,
486 NodeValue::Strikethrough => self.format_strikethrough()?,
487 NodeValue::Highlight => self.format_highlight()?,
488 NodeValue::Insert => self.format_insert()?,
489 NodeValue::Superscript => self.format_superscript()?,
490 NodeValue::Link(ref nl) => return self.format_link(node, nl, entering),
491 NodeValue::Image(ref nl) => self.format_image(nl, entering)?,
492 #[cfg(feature = "shortcodes")]
493 NodeValue::ShortCode(ref ne) => self.format_shortcode(ne, entering)?,
494 NodeValue::Table(..) => self.format_table(entering),
495 NodeValue::TableRow(..) => self.format_table_row(entering)?,
496 NodeValue::TableCell => self.format_table_cell(node, entering)?,
497 NodeValue::FootnoteDefinition(ref nfd) => {
498 self.format_footnote_definition(&nfd.name, entering)?
499 }
500 NodeValue::FootnoteReference(ref nfr) => {
501 self.format_footnote_reference(&nfr.name, entering)?
502 }
503 NodeValue::MultilineBlockQuote(..) => self.format_block_quote(entering)?,
504 NodeValue::Escaped => {
505 // Noop - the character gets escaped as usual, this is just an
506 // AST marker created by escaped_char_spans.
507 }
508 NodeValue::Math(ref math) => self.format_math(math, entering)?,
509 NodeValue::WikiLink(ref nl) => self.format_wikilink(nl, entering)?,
510 NodeValue::Underline => self.format_underline()?,
511 NodeValue::Subscript => self.format_subscript()?,
512 NodeValue::SpoileredText => self.format_spoiler()?,
513 NodeValue::EscapedTag(net) => self.format_escaped_tag(net)?,
514 NodeValue::Alert(ref alert) => self.format_alert(alert, entering)?,
515 NodeValue::Subtext => self.format_subtext(entering)?,
516 NodeValue::BlockDirective(ref nbd) => self.format_block_directive(nbd, entering)?,
517 };
518 Ok(true)
519 }
520
521 fn format_front_matter(&mut self, front_matter: &str, entering: bool) -> fmt::Result {
522 if entering {
523 self.output(front_matter, false, Escaping::Literal)?;
524 }
525 Ok(())
526 }
527
528 fn format_block_quote(&mut self, entering: bool) -> fmt::Result {
529 if entering {
530 write!(self, "> ")?;
531 self.begin_content = true;
532 write!(self.prefix, "> ")?;
533 } else {
534 let new_len = self.prefix.len() - 2;
535 self.prefix.truncate(new_len);
536 self.blankline();
537 }
538 Ok(())
539 }
540
541 fn format_list(&mut self, node: Node<'a>, entering: bool) -> fmt::Result {
542 let ol_start = match node.data().value {
543 NodeValue::List(NodeList {
544 list_type: ListType::Ordered,
545 start,
546 ..
547 }) => Some(start),
548 _ => None,
549 };
550
551 if entering {
552 if let Some(start) = ol_start {
553 self.ol_stack.push(start);
554 }
555 } else {
556 if ol_start.is_some() {
557 self.ol_stack.pop();
558 }
559
560 if match node.next_sibling() {
561 Some(next_sibling) => {
562 node_matches!(next_sibling, NodeValue::CodeBlock(..) | NodeValue::List(..))
563 }
564 _ => false,
565 } {
566 self.cr();
567 write!(self, "<!-- end list -->")?;
568 self.blankline();
569 }
570 }
571 Ok(())
572 }
573
574 fn format_item(&mut self, node: Node<'a>, entering: bool) -> fmt::Result {
575 let parent = match node.parent().unwrap().data().value {
576 NodeValue::List(ref nl) => *nl,
577 _ => unreachable!(),
578 };
579
580 let mut listmarker = String::new();
581
582 let marker_width = if parent.list_type == ListType::Bullet {
583 2
584 } else {
585 let list_number = if let Some(last_stack) = self.ol_stack.last_mut() {
586 let list_number = *last_stack;
587 if entering {
588 *last_stack += 1;
589 list_number
590 } else {
591 list_number - 1
592 }
593 } else {
594 match node.data().value {
595 NodeValue::Item(ref ni) => ni.start,
596 NodeValue::TaskItem(_) => parent.start,
597 _ => unreachable!(),
598 }
599 };
600 let list_delim = parent.delimiter;
601 write!(
602 listmarker,
603 "{}{} ",
604 list_number,
605 if list_delim == ListDelimType::Paren {
606 ")"
607 } else {
608 "."
609 }
610 )?;
611 let mut current_len = listmarker.len();
612
613 while current_len < self.options.render.ol_width.min(12) {
614 write!(listmarker, " ").unwrap();
615 current_len += 1;
616 }
617
618 listmarker.len()
619 };
620
621 if entering {
622 if parent.list_type == ListType::Bullet {
623 let bullet = char::from(self.options.render.list_style as u8);
624 write!(self, "{} ", bullet).unwrap();
625 } else {
626 self.write_str(&listmarker)?;
627 }
628 self.begin_content = true;
629 for _ in 0..marker_width {
630 write!(self.prefix, " ")?;
631 }
632 } else {
633 let new_len = if self.prefix.len() > marker_width {
634 self.prefix.len() - marker_width
635 } else {
636 0
637 };
638 self.prefix.truncate(new_len);
639 self.cr();
640 }
641
642 Ok(())
643 }
644
645 fn format_description_details(&mut self, entering: bool) -> fmt::Result {
646 if entering {
647 write!(self, ": ")?
648 }
649 Ok(())
650 }
651
652 fn format_heading(&mut self, nh: &NodeHeading, entering: bool) -> fmt::Result {
653 if entering {
654 for _ in 0..nh.level {
655 write!(self, "#")?;
656 }
657 write!(self, " ")?;
658 self.begin_content = true;
659 self.no_linebreaks = true;
660 } else {
661 self.no_linebreaks = false;
662 self.blankline();
663 }
664 Ok(())
665 }
666
667 fn format_code_block(
668 &mut self,
669 node: Node<'a>,
670 ncb: &NodeCodeBlock,
671 entering: bool,
672 ) -> fmt::Result {
673 if !entering {
674 return Ok(());
675 }
676
677 let first_in_list_item = node.previous_sibling().is_none()
678 && match node.parent() {
679 Some(parent) => {
680 node_matches!(parent, NodeValue::Item(..) | NodeValue::TaskItem(..))
681 }
682 _ => false,
683 };
684
685 if !first_in_list_item {
686 self.blankline();
687 }
688
689 let info = ncb.info.as_bytes();
690 let literal = ncb.literal.as_bytes();
691
692 #[allow(clippy::len_zero)]
693 if !(info.len() > 0
694 || literal.len() <= 2
695 || isspace(literal[0])
696 || first_in_list_item
697 || self.options.render.prefer_fenced
698 || isspace(literal[literal.len() - 1]) && isspace(literal[literal.len() - 2]))
699 {
700 write!(self, " ")?;
701 write!(self.prefix, " ")?;
702 self.write_str(&ncb.literal)?;
703 let new_len = self.prefix.len() - 4;
704 self.prefix.truncate(new_len);
705 } else {
706 let fence_byte = if info.contains(&b'`') { b'~' } else { b'`' };
707 let numticks = max(3, longest_byte_sequence(literal, fence_byte) + 1);
708 for _ in 0..numticks {
709 write!(self, "{}", fence_byte as char)?;
710 }
711 if !info.is_empty() {
712 self.write_str(&ncb.info)?;
713 }
714 self.cr();
715 self.write_str(&ncb.literal)?;
716 self.cr();
717 for _ in 0..numticks {
718 write!(self, "{}", fence_byte as char)?;
719 }
720 }
721 self.blankline();
722
723 Ok(())
724 }
725
726 fn format_html_block(&mut self, nhb: &NodeHtmlBlock, entering: bool) -> fmt::Result {
727 if entering {
728 self.blankline();
729 self.write_str(&nhb.literal)?;
730 self.blankline();
731 }
732 Ok(())
733 }
734
735 #[cfg(feature = "phoenix_heex")]
736 fn format_heex_block(&mut self, nhb: &NodeHeexBlock, entering: bool) -> fmt::Result {
737 if entering {
738 self.blankline();
739 self.write_str(&nhb.literal)?;
740 self.blankline();
741 }
742 Ok(())
743 }
744
745 fn format_thematic_break(&mut self, entering: bool) -> fmt::Result {
746 if entering {
747 self.blankline();
748 write!(self, "-----")?;
749 self.blankline();
750 }
751 Ok(())
752 }
753
754 fn format_paragraph(&mut self, entering: bool) {
755 if !entering {
756 self.blankline();
757 }
758 }
759
760 fn format_text(
761 &mut self,
762 literal: &str,
763 node: Node<'a>,
764 entering: bool,
765 wrap: bool,
766 ) -> fmt::Result {
767 if entering {
768 // Entity encode a leading or trailing whitespace character if this
769 // is the first or last child of an emphasis node respectively,
770 // otherwise flankingness rules will cause the emph to not be
771 // parsed! (Note that both is possible.)
772 let (leading, trailing) = if node
773 .parent()
774 .is_some_and(|n| is_emphasis_delimiter_node(&n.data().value))
775 {
776 (
777 if node.previous_sibling().is_none() {
778 literal
779 .chars()
780 .next()
781 .and_then(|c| if c.is_whitespace() { Some(c) } else { None })
782 } else {
783 None
784 },
785 if node.next_sibling().is_none() {
786 literal
787 .chars()
788 .next_back()
789 .and_then(|c| if c.is_whitespace() { Some(c) } else { None })
790 } else {
791 None
792 },
793 )
794 } else {
795 (None, None)
796 };
797
798 if let Some(leading) = leading {
799 write!(self, "&#{};", leading as u32)?;
800
801 if leading.len_utf8() == literal.len() {
802 // Deleterious case: the emphasis contains a text node which
803 // is a single whitespace character. Then,leading and trailing
804 // are actually the same (only) character, and the string slice
805 // below will fail.
806 // We can just stop!
807 return Ok(());
808 }
809 }
810
811 self.output(
812 &literal[leading.map_or(0, char::len_utf8)
813 ..literal.len() - trailing.map_or(0, char::len_utf8)],
814 wrap,
815 Escaping::Normal,
816 )?;
817
818 if let Some(trailing) = trailing {
819 write!(self, "&#{};", trailing as u32)?;
820 }
821 }
822 Ok(())
823 }
824
825 fn format_line_break(&mut self, entering: bool, next_is_block: bool) -> fmt::Result {
826 if entering {
827 if !self.options.render.hardbreaks && !next_is_block {
828 // If the next element is a block, a backslash means a
829 // literal backslash instead of a line break. In this case
830 // we can just skip the line break since it's meaningless
831 // before a block.
832 write!(self, "\\")?;
833 }
834 self.cr();
835 }
836 Ok(())
837 }
838
839 fn format_soft_break(&mut self, entering: bool) -> fmt::Result {
840 if entering {
841 if !self.no_linebreaks
842 && self.options.render.width == 0
843 && !self.options.render.hardbreaks
844 {
845 self.cr();
846 } else if self.options.render.hardbreaks {
847 self.output("\n", true, Escaping::Literal)?;
848 } else {
849 self.output(" ", true, Escaping::Literal)?;
850 }
851 }
852 Ok(())
853 }
854
855 fn format_code(&mut self, literal: &str, entering: bool) -> fmt::Result {
856 if entering {
857 let literal_bytes = literal.as_bytes();
858 let numticks = shortest_unused_sequence(literal_bytes, b'`');
859 for _ in 0..numticks {
860 write!(self, "`")?;
861 }
862
863 let all_space = literal_bytes
864 .iter()
865 .all(|&c| c == b' ' || c == b'\r' || c == b'\n');
866 let has_edge_space =
867 literal_bytes[0] == b' ' || literal_bytes[literal_bytes.len() - 1] == b' ';
868 let has_edge_backtick =
869 literal_bytes[0] == b'`' || literal_bytes[literal_bytes.len() - 1] == b'`';
870
871 let pad = literal.is_empty() || has_edge_backtick || (!all_space && has_edge_space);
872 if pad {
873 write!(self, " ")?
874 }
875 self.output(literal, true, Escaping::Literal)?;
876 if pad {
877 write!(self, " ")?;
878 }
879 for _ in 0..numticks {
880 write!(self, "`")?;
881 }
882 }
883
884 Ok(())
885 }
886
887 fn format_html_inline(&mut self, literal: &str, entering: bool) -> fmt::Result {
888 if entering {
889 self.write_str(literal)?;
890 }
891 Ok(())
892 }
893
894 #[cfg(feature = "phoenix_heex")]
895 fn format_heex_inline(&mut self, literal: &str, entering: bool) -> fmt::Result {
896 if entering {
897 self.write_str(literal)?;
898 }
899 Ok(())
900 }
901
902 fn format_raw(&mut self, literal: &str, entering: bool) -> fmt::Result {
903 if entering {
904 self.write_str(literal)?;
905 }
906 Ok(())
907 }
908
909 fn format_strong(&mut self) -> fmt::Result {
910 write!(self, "**")
911 }
912
913 fn format_emph(&mut self, node: Node<'a>) -> fmt::Result {
914 let emph_delim = if match node.parent() {
915 Some(parent) => matches!(parent.data().value, NodeValue::Emph),
916 _ => false,
917 } && node.next_sibling().is_none()
918 && node.previous_sibling().is_none()
919 {
920 "_"
921 } else {
922 "*"
923 };
924
925 self.write_str(emph_delim)?;
926 Ok(())
927 }
928
929 fn format_task_item(
930 &mut self,
931 nti: &NodeTaskItem,
932 node: Node<'a>,
933 entering: bool,
934 ) -> fmt::Result {
935 if node
936 .parent()
937 .map(|p| node_matches!(p, NodeValue::List(_)))
938 .unwrap_or_default()
939 {
940 self.format_item(node, entering)?;
941 }
942 if entering {
943 write!(self, "[{}] ", nti.symbol.unwrap_or(' '))?;
944 }
945 Ok(())
946 }
947
948 fn format_strikethrough(&mut self) -> fmt::Result {
949 write!(self, "~~")?;
950 Ok(())
951 }
952
953 fn format_highlight(&mut self) -> fmt::Result {
954 write!(self, "==")?;
955 Ok(())
956 }
957
958 fn format_insert(&mut self) -> fmt::Result {
959 write!(self, "++")?;
960 Ok(())
961 }
962
963 fn format_superscript(&mut self) -> fmt::Result {
964 write!(self, "^")?;
965 Ok(())
966 }
967
968 fn format_underline(&mut self) -> fmt::Result {
969 write!(self, "__")?;
970 Ok(())
971 }
972
973 fn format_subscript(&mut self) -> fmt::Result {
974 write!(self, "~")?;
975 Ok(())
976 }
977
978 fn format_spoiler(&mut self) -> fmt::Result {
979 write!(self, "||")?;
980 Ok(())
981 }
982
983 fn format_escaped_tag(&mut self, net: &str) -> fmt::Result {
984 self.output(net, false, Escaping::Literal)
985 }
986
987 fn format_link(
988 &mut self,
989 node: Node<'a>,
990 nl: &NodeLink,
991 entering: bool,
992 ) -> Result<bool, fmt::Error> {
993 if is_autolink(node, nl) {
994 if entering {
995 write!(self, "<{}>", trim_start_match(&nl.url, "mailto:"))?;
996 return Ok(false);
997 }
998 } else if entering {
999 write!(self, "[")?;
1000 } else {
1001 write!(self, "](")?;
1002 self.output(&nl.url, false, Escaping::Url)?;
1003 if !nl.title.is_empty() {
1004 write!(self, " \"")?;
1005 self.output(&nl.title, false, Escaping::Title)?;
1006 write!(self, "\"")?;
1007 }
1008 write!(self, ")")?;
1009 }
1010
1011 Ok(true)
1012 }
1013
1014 fn format_wikilink(&mut self, nl: &NodeWikiLink, entering: bool) -> fmt::Result {
1015 if entering {
1016 write!(self, "[[")?;
1017 if self.options.extension.wikilinks() == Some(WikiLinksMode::UrlFirst) {
1018 self.output(&nl.url, false, Escaping::Url)?;
1019 write!(self, "|").unwrap();
1020 }
1021 } else {
1022 if self.options.extension.wikilinks() == Some(WikiLinksMode::TitleFirst) {
1023 write!(self, "|")?;
1024 self.output(&nl.url, false, Escaping::Url)?;
1025 }
1026 write!(self, "]]")?;
1027 }
1028
1029 Ok(())
1030 }
1031
1032 fn format_image(&mut self, nl: &NodeLink, entering: bool) -> fmt::Result {
1033 if entering {
1034 write!(self, "![")?;
1035 } else {
1036 write!(self, "](")?;
1037 self.output(&nl.url, false, Escaping::Url)?;
1038 if !nl.title.is_empty() {
1039 self.output(" \"", true, Escaping::Literal)?;
1040 self.output(&nl.title, false, Escaping::Title)?;
1041 write!(self, "\"")?;
1042 }
1043 write!(self, ")")?;
1044 }
1045 Ok(())
1046 }
1047
1048 #[cfg(feature = "shortcodes")]
1049 fn format_shortcode(&mut self, ne: &NodeShortCode, entering: bool) -> fmt::Result {
1050 if entering {
1051 write!(self, ":")?;
1052 self.output(&ne.code, false, Escaping::Literal)?;
1053 write!(self, ":")?;
1054 }
1055 Ok(())
1056 }
1057
1058 fn format_table(&mut self, entering: bool) {
1059 if entering {
1060 self.custom_escape = Some(table_escape);
1061 } else {
1062 self.custom_escape = None;
1063 }
1064 self.blankline();
1065 }
1066
1067 fn format_table_row(&mut self, entering: bool) -> fmt::Result {
1068 if entering {
1069 self.cr();
1070 write!(self, "|")?;
1071 }
1072 Ok(())
1073 }
1074
1075 fn format_table_cell(&mut self, node: Node<'a>, entering: bool) -> fmt::Result {
1076 if entering {
1077 write!(self, " ")?;
1078 } else {
1079 write!(self, " |")?;
1080
1081 let row = &node.parent().unwrap().data().value;
1082 let in_header = match *row {
1083 NodeValue::TableRow(header) => header,
1084 _ => panic!(),
1085 };
1086
1087 if in_header && node.next_sibling().is_none() {
1088 let table = &node.parent().unwrap().parent().unwrap().data().value;
1089 let alignments = match table {
1090 NodeValue::Table(nt) => &nt.alignments,
1091 _ => panic!(),
1092 };
1093
1094 self.cr();
1095 write!(self, "|")?;
1096 for a in alignments {
1097 write!(
1098 self,
1099 " {} |",
1100 match *a {
1101 TableAlignment::Left => ":--",
1102 TableAlignment::Center => ":-:",
1103 TableAlignment::Right => "--:",
1104 TableAlignment::None => "---",
1105 }
1106 )?;
1107 }
1108 self.cr();
1109 }
1110 }
1111 Ok(())
1112 }
1113
1114 fn format_footnote_definition(&mut self, name: &str, entering: bool) -> fmt::Result {
1115 if entering {
1116 self.footnote_ix += 1;
1117 writeln!(self, "[^{}]:", name)?;
1118 write!(self.prefix, " ")?;
1119 } else {
1120 let new_len = self.prefix.len() - 4;
1121 self.prefix.truncate(new_len);
1122 }
1123 Ok(())
1124 }
1125
1126 fn format_footnote_reference(&mut self, r: &str, entering: bool) -> fmt::Result {
1127 if entering {
1128 self.write_str("[^")?;
1129 self.write_str(r)?;
1130 self.write_str("]")?;
1131 }
1132 Ok(())
1133 }
1134
1135 fn format_math(&mut self, math: &NodeMath, entering: bool) -> fmt::Result {
1136 if entering {
1137 let literal = &math.literal;
1138 let (start_fence, end_fence) = match (
1139 math.dollar_math,
1140 math.display_math,
1141 self.options.extension.math_latex,
1142 self.options.extension.math_dollars,
1143 ) {
1144 (false, _, _, _) => ("$`", "`$"),
1145 (true, true, true, false) => ("\\[", "\\]"),
1146 (true, false, true, false) => ("\\(", "\\)"),
1147 (true, true, _, _) => ("$$", "$$"),
1148 (true, false, _, _) => ("$", "$"),
1149 };
1150
1151 self.output(start_fence, false, Escaping::Literal)?;
1152 self.output(literal, true, Escaping::Literal)?;
1153 self.output(end_fence, false, Escaping::Literal)?;
1154 }
1155 Ok(())
1156 }
1157
1158 fn format_alert(&mut self, alert: &NodeAlert, entering: bool) -> fmt::Result {
1159 if entering {
1160 write!(
1161 self,
1162 "> [!{}]",
1163 alert.alert_type.default_title().to_uppercase()
1164 )?;
1165 if let Some(ref title) = alert.title {
1166 write!(self, " {title}")?;
1167 }
1168 writeln!(self)?;
1169 write!(self, "> ")?;
1170 self.begin_content = true;
1171 write!(self.prefix, "> ")?;
1172 } else {
1173 let new_len = self.prefix.len() - 2;
1174 self.prefix.truncate(new_len);
1175 self.blankline();
1176 }
1177 Ok(())
1178 }
1179
1180 fn format_subtext(&mut self, entering: bool) -> fmt::Result {
1181 if entering {
1182 write!(self, "-# ")?;
1183 self.begin_content = true;
1184 self.no_linebreaks = true;
1185 } else {
1186 self.no_linebreaks = false;
1187 self.blankline();
1188 }
1189 Ok(())
1190 }
1191
1192 fn format_block_directive(&mut self, nbd: &NodeBlockDirective, entering: bool) -> fmt::Result {
1193 if entering {
1194 let fence = ":".repeat(nbd.fence_length.max(3));
1195 if nbd.info.is_empty() {
1196 writeln!(self, "{fence}")?;
1197 } else {
1198 writeln!(self, "{fence}{}", nbd.info)?;
1199 }
1200 self.begin_content = true;
1201 } else {
1202 let fence = ":".repeat(nbd.fence_length.max(3));
1203 write!(self, "{fence}")?;
1204 self.blankline();
1205 }
1206 Ok(())
1207 }
1208 }
1209
1210 fn longest_byte_sequence(buffer: &[u8], ch: u8) -> usize {
1211 let mut longest = 0;
1212 let mut current = 0;
1213 for c in buffer {
1214 if *c == ch {
1215 current += 1;
1216 } else {
1217 if current > longest {
1218 longest = current;
1219 }
1220 current = 0;
1221 }
1222 }
1223 if current > longest {
1224 longest = current;
1225 }
1226 longest
1227 }
1228
1229 fn shortest_unused_sequence(buffer: &[u8], f: u8) -> usize {
1230 let mut used = HashSet::<usize>::new();
1231 let mut current = 0;
1232 for c in buffer {
1233 if *c == f {
1234 current += 1;
1235 } else {
1236 if current > 0 {
1237 used.insert(current);
1238 }
1239 current = 0;
1240 }
1241 }
1242
1243 if current > 0 {
1244 used.insert(current);
1245 }
1246
1247 let mut i = 1;
1248 while used.contains(&i) {
1249 i += 1;
1250 }
1251 i
1252 }
1253
1254 fn is_autolink(node: Node<'_>, nl: &NodeLink) -> bool {
1255 if nl.url.is_empty() || scanners::scheme(&nl.url).is_none() {
1256 return false;
1257 }
1258
1259 if !nl.title.is_empty() {
1260 return false;
1261 }
1262
1263 let link_text = match node.first_child() {
1264 None => return false,
1265 Some(child) => match child.data().value {
1266 NodeValue::Text(ref t) => t.clone(),
1267 _ => return false,
1268 },
1269 };
1270
1271 trim_start_match(&nl.url, "mailto:") == link_text
1272 }
1273
1274 fn table_escape(node: Node<'_>, c: char) -> bool {
1275 match node.data().value {
1276 NodeValue::Table(..) | NodeValue::TableRow(..) | NodeValue::TableCell => false,
1277 _ => c == '|',
1278 }
1279 }
1280
1281 fn minimize_commonmark(text: &mut String, original_options: &Options) {
1282 let mut options_without = original_options.clone();
1283 options_without.render.experimental_minimize_commonmark = false;
1284
1285 let ixs: Vec<usize> = text
1286 .as_bytes()
1287 .iter()
1288 .enumerate()
1289 .filter_map(|(ix, &c)| if c == b'\\' { Some(ix) } else { None })
1290 .collect();
1291 let original = text.clone();
1292
1293 let mut adjust = 0;
1294 for ix in ixs {
1295 text.remove(ix - adjust);
1296
1297 let arena = Arena::new();
1298 let root = crate::parse_document(&arena, text, &options_without);
1299
1300 let mut out = String::new();
1301 format_document(root, &options_without, &mut out).unwrap();
1302
1303 if original == out {
1304 // Removed character is guaranteed to be 1 byte wide, since it's
1305 // always '\\'.
1306 adjust += 1;
1307 } else {
1308 text.insert(ix - adjust, '\\');
1309 }
1310 }
1311 }
1312
1313 /// Escapes the input, rendering it suitable for inclusion in a CommonMark
1314 /// document in a place where regular inline parsing is occurring. Note that
1315 /// this is not minimal --- there will be more escaping backslashes in the
1316 /// output than is strictly necessary. The rendering will not be affected,
1317 /// however.
1318 pub fn escape_inline(text: &str) -> String {
1319 let mut result = String::with_capacity(text.len() * 3 / 2);
1320
1321 for c in text.chars() {
1322 if c < '\x20'
1323 || c == '*'
1324 || c == '_'
1325 || c == '['
1326 || c == ']'
1327 || c == '#'
1328 || c == '<'
1329 || c == '>'
1330 || c == '\\'
1331 || c == '`'
1332 || c == '~'
1333 || c == '!'
1334 || c == '&'
1335 || c == '!'
1336 || c == '-'
1337 || c == '+'
1338 || c == '='
1339 || c == '.'
1340 || c == '('
1341 || c == ')'
1342 || c == '"'
1343 {
1344 if ispunct(c as u8) {
1345 write!(&mut result, "\\{}", c).unwrap();
1346 } else {
1347 write!(&mut result, "&#{};", c as u8).unwrap();
1348 }
1349 } else {
1350 result.push(c);
1351 }
1352 }
1353
1354 result
1355 }
1356
1357 /// Escapes the input URL, rendering it suitable for inclusion as a [link
1358 /// destination] per the CommonMark spec.
1359 ///
1360 /// [link destination]: https://spec.commonmark.org/0.31.2/#link-destination
1361 pub fn escape_link_destination(url: &str) -> String {
1362 let mut result = String::with_capacity(url.len() * 3 / 2);
1363
1364 result.push('<');
1365 for c in url.chars() {
1366 match c {
1367 '<' | '>' => {
1368 result.push('\\');
1369 result.push(c);
1370 }
1371 '\n' => result.push_str("%0A"),
1372 '\r' => result.push_str("%0D"),
1373 _ => result.push(c),
1374 }
1375 }
1376 result.push('>');
1377
1378 result
1379 }
1380
1381 #[inline]
1382 fn is_emphasis_delimiter_node(value: &NodeValue) -> bool {
1383 matches!(
1384 value,
1385 NodeValue::Emph
1386 | NodeValue::Strong
1387 | NodeValue::Strikethrough
1388 | NodeValue::Highlight
1389 | NodeValue::Superscript
1390 | NodeValue::Subscript
1391 | NodeValue::SpoileredText
1392 | NodeValue::Underline
1393 )
1394 }