docx_rs/documents/elements/
paragraph_style.rs

1use serde::{Serialize, Serializer};
2use std::io::Write;
3
4use crate::documents::BuildXML;
5use crate::escape::escape;
6use crate::xml_builder::*;
7
8#[derive(Debug, Clone, PartialEq)]
9pub struct ParagraphStyle {
10    pub val: String,
11}
12
13impl Default for ParagraphStyle {
14    fn default() -> Self {
15        ParagraphStyle {
16            val: "Normal".to_owned(),
17        }
18    }
19}
20
21// 17.9.23
22// pStyle (Paragraph Style's Associated Numbering Level)
23// This element specifies the name of a paragraph style which shall automatically this numbering level when
24// applied to the contents of the document. When a paragraph style is defined to include a numbering definition,
25// any numbering level defined by the numPr element (ยง17.3.1.19) shall be ignored, and instead this element shall
26// specify the numbering level associated with that paragraph style.
27impl ParagraphStyle {
28    pub fn new(val: Option<impl Into<String>>) -> ParagraphStyle {
29        if let Some(v) = val {
30            ParagraphStyle {
31                val: escape(&v.into()),
32            }
33        } else {
34            Default::default()
35        }
36    }
37}
38
39impl BuildXML for ParagraphStyle {
40    fn build_to<W: Write>(
41        &self,
42        stream: xml::writer::EventWriter<W>,
43    ) -> xml::writer::Result<xml::writer::EventWriter<W>> {
44        XMLBuilder::from(stream)
45            .paragraph_style(&self.val)?
46            .into_inner()
47    }
48}
49
50impl Serialize for ParagraphStyle {
51    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
52    where
53        S: Serializer,
54    {
55        serializer.serialize_str(&self.val)
56    }
57}
58
59#[cfg(test)]
60mod tests {
61
62    use super::*;
63    #[cfg(test)]
64    use pretty_assertions::assert_eq;
65    use std::str;
66
67    #[test]
68    fn test_p_style() {
69        let c = ParagraphStyle::new(Some("Heading"));
70        let b = c.build();
71        assert_eq!(
72            str::from_utf8(&b).unwrap(),
73            r#"<w:pStyle w:val="Heading" />"#
74        );
75    }
76}