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
pub mod nodes;
pub mod parsers;
pub mod plugins;
pub mod state;
use crate::nodes::{Node, Nodes, RenderableNode};
use crate::plugins::SharedPlugin;
use crate::state::*;
use chonk::prelude::*;
use std::fmt::{Display, Formatter, Result as FormatResult};
use std::fs::read_to_string;
use std::path::{Path, PathBuf};
pub type Errors = Vec<Error>;
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
DocumentNotFound(PathBuf),
DocumentSyntax(PathBuf, String),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult {
match self {
Error::DocumentNotFound(path) => write!(f, "Document not found: {}", path.display()),
Error::DocumentSyntax(_, error) => write!(f, "{}", error),
}
}
}
#[derive(Clone, Default, Debug)]
pub struct Intext {
errors: Errors,
state: SharedState,
nodes: Nodes,
}
impl Intext {
pub fn with_document<P: AsRef<Path>>(mut self, filename: P) -> Self {
let filename = filename.as_ref().to_path_buf();
let source = read_to_string(filename.clone()).unwrap();
let parent = filename.parent();
if let Some(parent) = parent {
self.state.borrow_mut().paths.push(parent.to_path_buf());
}
match parsers::block::document(self.state.clone()).parse(&source) {
Ok((_, nodes)) => {
self.nodes.append(
&mut nodes
.into_iter()
.map(|node| node.finish(self.state.clone()))
.collect(),
);
}
Err((_, error)) => {
println!("{:#?}", error);
}
}
if let Some(_) = parent {
self.state.borrow_mut().paths.pop();
}
self
}
pub fn with_plugin(self, plugin: SharedPlugin) -> Self {
self.state.borrow_mut().plugins.push(plugin);
self
}
pub fn document(self) -> Result<Option<Node>, Errors> {
if self.errors.is_empty() {
Ok(Some(Node::Fragment {
children: Some(self.nodes),
}))
} else {
Err(self.errors)
}
}
pub fn render(self) -> Result<String, Errors> {
if self.errors.is_empty() {
Ok(self.nodes.html())
} else {
Err(self.errors)
}
}
}
#[test]
fn example() {
use crate::plugins::*;
let metadata = MetadataPlugin::new();
let word_count = WordCountPlugin::new();
let etch = Intext::default()
.with_plugin(metadata.clone())
.with_plugin(word_count.clone())
.with_plugin(SyntectPlugin::new())
.with_plugin(WidowedWordsPlugin::new())
.with_document("samples/example.intxt");
println!("{:#?}", etch.render());
println!("{:#?}", metadata);
println!("{:#?}", word_count);
}