1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*!
Provides the functions, and format types, to serialize a [`Document`](../model/document/struct.Document.html)
in supported markup formats.

The enum [`OutputFormat`](enum.OutputFormat.html) provides a set of implemented formatters that may
then be used in [`write_document`](fn.write_document.html) and
[`write_document_to_string`](fn.write_document_to_string.html).

# Example

The following uses the `write_document_to_string` convenience function.

```rust
# use somedoc::model::Document;
use somedoc::write::{OutputFormat, write_document_to_string};

# fn make_some_document() -> Document { Document::default() }
let doc = make_some_document();

let doc_str = write_document_to_string(&doc, OutputFormat::Latex).unwrap();
println!("{}", doc_str);
```

# Writer Implementation

Each of the supported output formats implements *at least* the `Writer` and possibly the
`ConfigurableWriter` trait. These provide common functions for construction of the writer struct
and the `write_document` method. The following example constructs two separate writers and emits
the same document into both.

```rust
# use somedoc::model::Document;
use somedoc::write::{ConfigurableWriter, Writer};
use somedoc::write::markdown::{MarkdownFlavor, MarkdownWriter};
use somedoc::write::latex::LatexWriter;

# fn make_some_document() -> Document { Document::default() }
let doc = make_some_document();

let mut out = std::io::stdout();

let writer = MarkdownWriter::new_with(&mut out, MarkdownFlavor::CommonMark);
assert!(writer.write_document(&doc).is_ok());

let writer = LatexWriter::new(&mut out);
assert!(writer.write_document(&doc).is_ok());
```

*/

use std::fmt::{Display, Formatter};
use std::io::Write;
use std::str::FromStr;

use crate::error;
use crate::model::Document;
#[cfg(feature = "fmt_html")]
use crate::write::html::HtmlWriter;
#[cfg(feature = "fmt_json")]
use crate::write::json::JsonWriter;
#[cfg(feature = "fmt_latex")]
use crate::write::latex::LatexWriter;
#[cfg(feature = "fmt_markdown")]
use crate::write::markdown::{MarkdownFlavor, MarkdownWriter};

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

///
/// This indicates the output format to use when writing a document.
///
#[derive(Clone, Debug, PartialEq)]
pub enum OutputFormat {
    /// One of the supported flavors of Markdown, see [`markdown::MarkdownFlavor`](markdown/enum.MarkdownFlavor.html).
    #[cfg(feature = "fmt_markdown")]
    Markdown(MarkdownFlavor),

    /// Generic HTML, supports math via MathJax and code syntax via hightlight.js.
    #[cfg(feature = "fmt_html")]
    Html,

    /// A direct representation of the model in JSON for external tool integration.
    #[cfg(feature = "fmt_json")]
    Json,

    /// Pretty generic LaTeX support, includes a number of packages for support of listings, block
    /// quotes, images, etc.
    #[cfg(feature = "fmt_latex")]
    Latex,
}

///
/// This trait can be implemented by a serializer to provide a common instantiation method.
///
pub trait Writer<'a, W: Write> {
    /// Create a new writer using the write implementation provided.
    fn new(w: &'a mut W) -> Self
    where
        Self: Sized;

    /// Format and write the provided document using the `Write` instance given during construction.
    fn write_document(&self, doc: &Document) -> crate::error::Result<()>;
}

///
/// This trait can be implemented by a serializer to provide a common instantiation method when
/// configuration may be passed to the new instance.
///
pub trait ConfigurableWriter<'a, W: Write, T: Default>: Writer<'a, W> {
    /// Create a new writer using the write implementation provided, and the configuration value(s).
    fn new_with(w: &'a mut W, config: T) -> Self;
}

// ------------------------------------------------------------------------------------------------
// Public Functions
// ------------------------------------------------------------------------------------------------

///
/// Write the provided document `doc`, in the format described by `format`, into the write
/// implementation `w`. This is simply a convenience function
///
pub fn write_document<W: Write>(
    doc: &Document,
    format: OutputFormat,
    w: &mut W,
) -> crate::error::Result<()> {
    match format {
        #[cfg(feature = "fmt_markdown")]
        OutputFormat::Markdown(flavor) => {
            let writer = MarkdownWriter::new_with(w, flavor);
            writer.write_document(doc)
        }
        #[cfg(feature = "fmt_html")]
        OutputFormat::Html => {
            let writer = HtmlWriter::new(w);
            writer.write_document(doc)
        }
        #[cfg(feature = "fmt_json")]
        OutputFormat::Json => {
            let writer = JsonWriter::new(w);
            writer.write_document(doc)
        }
        #[cfg(feature = "fmt_latex")]
        OutputFormat::Latex => {
            let writer = LatexWriter::new(w);
            writer.write_document(doc)
        }
    }
}

///
/// A convenience function that will return a String containing the output of the `write_document`
/// function for the given `Document` instance.
///
pub fn write_document_to_string(
    doc: &Document,
    format: OutputFormat,
) -> crate::error::Result<String> {
    use std::io::Cursor;
    let mut buffer = Cursor::new(Vec::new());
    write_document(doc, format, &mut buffer)?;
    Ok(String::from_utf8(buffer.into_inner()).unwrap())
}

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

impl Default for OutputFormat {
    fn default() -> Self {
        Self::Markdown(Default::default())
    }
}

impl Display for OutputFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                #[cfg(feature = "fmt_markdown")]
                Self::Markdown(f) => f.to_string(),
                #[cfg(feature = "fmt_html")]
                Self::Html => "html".to_string(),
                #[cfg(feature = "fmt_json")]
                Self::Json => "json".to_string(),
                #[cfg(feature = "fmt_latex")]
                Self::Latex => "latex".to_string(),
            }
        )
    }
}

impl FromStr for OutputFormat {
    type Err = error::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            #[cfg(feature = "fmt_markdown")]
            "md" | "markdown" => Ok(Self::Markdown(MarkdownFlavor::GitHub)),
            #[cfg(feature = "fmt_markdown")]
            "xwiki" => Ok(Self::Markdown(MarkdownFlavor::XWiki)),
            #[cfg(feature = "fmt_html")]
            "html" => Ok(Self::Html),
            #[cfg(feature = "fmt_json")]
            "json" => Ok(Self::Json),
            #[cfg(feature = "fmt_latex")]
            "latex" => Ok(Self::Latex),
            _ => Err(error::ErrorKind::UnknownFormat.into()),
        }
    }
}

// ------------------------------------------------------------------------------------------------
// Modules
// ------------------------------------------------------------------------------------------------

#[cfg(feature = "fmt_html")]
pub mod html;

#[cfg(feature = "fmt_json")]
pub mod json;

#[cfg(feature = "fmt_latex")]
pub mod latex;

#[cfg(feature = "fmt_markdown")]
pub mod markdown;

pub(crate) mod utils;