mirror of
https://github.com/YGGverse/Yoda.git
synced 2025-01-15 09:10:08 +00:00
implement header line parser
This commit is contained in:
parent
d9fd0d12c3
commit
9a130a7422
@ -0,0 +1,79 @@
|
||||
use gtk::glib::{markup_escape_text, GString, Regex, RegexCompileFlags, RegexMatchFlags};
|
||||
|
||||
pub enum Level {
|
||||
H1,
|
||||
H2,
|
||||
H3,
|
||||
}
|
||||
|
||||
pub struct Header {
|
||||
level: Level,
|
||||
text: GString,
|
||||
markup: GString,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
pub fn from(line: &str) -> Option<Header> {
|
||||
// Parse line
|
||||
let parsed = Regex::split_simple(
|
||||
r"^(#{1,3})\s*(.+)$",
|
||||
line,
|
||||
RegexCompileFlags::DEFAULT,
|
||||
RegexMatchFlags::DEFAULT,
|
||||
);
|
||||
|
||||
// Validate match results
|
||||
if let Some(text) = parsed.get(2) {
|
||||
if let Some(level) = parsed.get(1) {
|
||||
// Init level
|
||||
let level = match level.len() {
|
||||
1 => Level::H1,
|
||||
2 => Level::H2,
|
||||
3 => Level::H3,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
// Init text
|
||||
let text = GString::from(text.as_str());
|
||||
|
||||
if text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Init markup
|
||||
let markup = match level {
|
||||
Level::H1 => GString::from(format!(
|
||||
"<span size=\"xx-large\">{}</span>\n",
|
||||
markup_escape_text(&text)
|
||||
)),
|
||||
Level::H2 => GString::from(format!(
|
||||
"<span size=\"x-large\">{}</span>\n",
|
||||
markup_escape_text(&text)
|
||||
)),
|
||||
Level::H3 => GString::from(format!(
|
||||
"<span size=\"large\">{}</span>\n",
|
||||
markup_escape_text(&text)
|
||||
)),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
// Result
|
||||
return Some(Header {
|
||||
level,
|
||||
text,
|
||||
markup,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
None // not header line given
|
||||
}
|
||||
|
||||
pub fn text(&self) -> &GString {
|
||||
&self.text
|
||||
}
|
||||
|
||||
pub fn markup(&self) -> &GString {
|
||||
&self.markup
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
pub mod header;
|
Loading…
x
Reference in New Issue
Block a user