orgize/examples/custom.rs

72 lines
1.8 KiB
Rust
Raw Normal View History

use std::convert::From;
use std::env::args;
2019-06-26 18:53:50 +01:00
use std::fs;
use std::io::{Error as IOError, Write};
use std::result::Result;
use std::string::FromUtf8Error;
2019-06-26 18:53:50 +01:00
use orgize::export::*;
use orgize::{Container, Org};
use slugify::slugify;
#[derive(Debug)]
2019-06-26 18:53:50 +01:00
enum MyError {
IO(IOError),
Heading,
Utf8(FromUtf8Error),
}
2019-06-26 18:53:50 +01:00
// From<std::io::Error> trait is required for custom error type
impl From<IOError> for MyError {
fn from(err: IOError) -> Self {
MyError::IO(err)
}
}
2019-06-26 18:53:50 +01:00
impl From<FromUtf8Error> for MyError {
fn from(err: FromUtf8Error) -> Self {
MyError::Utf8(err)
}
}
2019-06-27 07:03:42 +01:00
struct MyHtmlHandler;
2019-06-27 07:03:42 +01:00
impl HtmlHandler<MyError> for MyHtmlHandler {
2019-06-26 18:53:50 +01:00
fn start<W: Write>(&mut self, mut w: W, container: Container<'_>) -> Result<(), MyError> {
let mut default_handler = DefaultHtmlHandler;
match container {
Container::Headline(hdl) => {
if hdl.level > 6 {
return Err(MyError::Heading);
} else {
let slugify = slugify!(hdl.title);
write!(
w,
"<h{0}><a id=\"{1}\" href=\"#{1}\">{2}</a></h{0}>",
hdl.level, slugify, hdl.title,
)?;
}
}
_ => default_handler.start(w, container)?,
}
2019-06-26 18:53:50 +01:00
Ok(())
}
}
2019-06-26 18:53:50 +01:00
fn main() -> Result<(), MyError> {
let args: Vec<_> = args().collect();
if args.len() < 2 {
2019-06-26 18:53:50 +01:00
eprintln!("Usage: {} <org-file>", args[0]);
} else {
2019-06-26 18:53:50 +01:00
let contents = String::from_utf8(fs::read(&args[1])?)?;
2019-06-27 06:20:21 +01:00
let mut writer = Vec::new();
2019-06-27 07:03:42 +01:00
Org::parse(&contents).html(&mut writer, MyHtmlHandler)?;
2019-06-26 18:53:50 +01:00
println!("{}", String::from_utf8(writer)?);
}
Ok(())
}