tbot/markup/
italic.rs

1use super::{html, markdown_v2, Formattable, Nesting};
2use std::fmt::{self, Formatter};
3
4/// Formats text in italic. Can be created with [`italic`].
5///
6/// [`italic`]: ./fn.italic.html
7#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
8#[must_use = "formatters need to be formatted with `markdown_v2` or `html`"]
9pub struct Italic<T>(T);
10
11/// Formats text in italic.
12pub fn italic<T: Formattable>(text: T) -> Italic<T> {
13    Italic(text)
14}
15
16impl<T: Formattable> markdown_v2::Formattable for Italic<T> {
17    fn format(
18        &self,
19        formatter: &mut Formatter,
20        nesting: Nesting,
21    ) -> fmt::Result {
22        if !nesting.italic {
23            formatter.write_str("\r_")?;
24        }
25        markdown_v2::Formattable::format(
26            &self.0,
27            formatter,
28            Nesting {
29                italic: true,
30                ..nesting
31            },
32        )?;
33        if !nesting.italic {
34            formatter.write_str("\r_")?;
35        }
36        Ok(())
37    }
38}
39
40impl<T: Formattable> html::Formattable for Italic<T> {
41    fn format(
42        &self,
43        formatter: &mut Formatter,
44        nesting: Nesting,
45    ) -> fmt::Result {
46        formatter.write_str("<i>")?;
47        html::Formattable::format(&self.0, formatter, nesting)?;
48        formatter.write_str("</i>")
49    }
50}
51
52#[cfg(tests)]
53mod tests {
54    use super::{italic, markdown_v2};
55    #[test]
56    fn sibling_italics_are_displayed_correctly() {
57        assert_eq!(
58            markdown_v2((italic("a"), italic("b"))).to_string(),
59            "\r_a\r_\r_b\r_"
60        );
61    }
62}