dc09rs/src/markdown.rs

366 lines
12 KiB
Rust
Raw Normal View History

use std::{
io::{BufWriter, Write},
path::Path,
};
use pulldown_cmark::{CowStr, Options, Parser};
pub fn compile_markdown(
src: impl AsRef<Path>,
html: impl AsRef<Path>,
gmi: impl AsRef<Path>,
) -> std::io::Result<()> {
let src_text = std::fs::read_to_string(src)?;
let mut html = create_file(html)?;
let mut gmi = create_file(gmi)?;
let mut state = State::Start;
let mut ol = false; // ordered list
let mut counter: u64 = 0;
let mut links: Vec<GmiLink<'_>> = vec![];
for event in Parser::new_ext(&src_text, Options::all()) {
use pulldown_cmark::Event::*;
dbg!(&event);
match event {
Start(tag) => {
use pulldown_cmark::{CodeBlockKind, HeadingLevel, Tag::*};
match tag {
Paragraph => {
html.write_all(b"<p>")?;
write_paragraph_start(&mut gmi, state)?;
}
Heading { level, id, .. } => {
if let Some(id) = id {
html.write_fmt(format_args!("<{} id=\"{}\">", level, id))?;
} else {
html.write_fmt(format_args!("<{}>", level))?;
}
write_paragraph_start(&mut gmi, state)?;
let hashes = match level {
HeadingLevel::H1 => "# ",
HeadingLevel::H2 => "## ",
_ => "### ",
};
gmi.write_all(hashes.as_bytes())?;
state = State::Paragraph;
}
BlockQuote(_kind) => {
html.write_all(b"<blockquote>")?;
write_paragraph_start(&mut gmi, state)?;
gmi.write_all(b"> ")?;
state = State::Quote;
}
CodeBlock(CodeBlockKind::Fenced(lang)) => {
// TODO: highlighting with syntect
html.write_all(b"<pre><code>")?;
write_paragraph_start(&mut gmi, state)?;
gmi.write_fmt(format_args!("```{}\r\n", lang))?;
}
CodeBlock(CodeBlockKind::Indented) => {
html.write_all(b"<pre><code>")?;
write_paragraph_start(&mut gmi, state)?;
gmi.write_all(b"```")?;
}
List(None) => {
html.write_all(b"<ul>")?;
write_paragraph_start(&mut gmi, state)?;
state = State::Start;
}
List(Some(counter_start)) => {
counter = counter_start;
ol = true;
if counter_start == 1 {
html.write_all(b"<ol>")?;
} else {
html.write_fmt(format_args!("<ol start=\"{}\">", counter_start))?;
}
write_paragraph_start(&mut gmi, state)?;
state = State::Start;
}
Item => {
html.write_all(b"<li>")?;
if state != State::Start {
gmi.write_all(b"\r\n")?;
state = State::Paragraph;
}
if ol {
gmi.write_fmt(format_args!("{}. ", counter))?;
counter += 1;
} else {
gmi.write_all(b"* ")?;
}
}
Strong => {
html.write_all(b"<b>")?;
write_inline(&mut gmi, state, "**", &mut links)?;
}
Emphasis => {
html.write_all(b"<i>")?;
write_inline(&mut gmi, state, "*", &mut links)?;
}
Strikethrough => {
html.write_all(b"<s>")?;
write_inline(&mut gmi, state, "~", &mut links)?;
}
Link { dest_url, .. } => {
html.write_fmt(format_args!("<a href=\"{}\">", dest_url))?;
links.push(GmiLink {
title: String::new(),
url: dest_url,
});
state = State::Link;
}
Image { dest_url, .. } => {
links.push(GmiLink {
title: String::new(),
url: dest_url,
});
state = State::Link;
}
Table(_align) => {
html.write_all(b"<table>")?;
write_paragraph_start(&mut gmi, state)?;
// gmi ??
}
TableHead => {
html.write_all(b"<thead><tr>")?;
state = State::TableHead;
}
TableRow => {
html.write_all(b"<tr>")?;
}
TableCell => {
if state == State::TableHead {
html.write_all(b"<th>")?;
} else {
html.write_all(b"<td>")?;
}
}
MetadataBlock(_) => {
state = State::Metadata(state != State::Start);
}
other => {
eprintln!("Unsupported tag: {:?}", other);
}
}
}
End(tag) => {
use pulldown_cmark::TagEnd::*;
match tag {
Paragraph => {
html.write_all(b"</p>")?;
if !links.is_empty() {
gmi.write_all(b"\r\n")?;
for (i, link) in links.iter().enumerate() {
gmi.write_fmt(format_args!(
"\r\n=> {} [{}]: {}", // => https://... [1]: example
link.url, i, link.title,
))?;
}
links.clear();
}
}
Heading(level) => html.write_fmt(format_args!("<{}>", level))?,
BlockQuote(_) => html.write_all(b"</blockquote>")?,
CodeBlock => {
html.write_all(b"</code></pre>")?;
gmi.write_all(b"```")?;
}
List(ordered) => {
if ordered {
html.write_all(b"</ol>")?;
ol = false;
} else {
html.write_all(b"</ul>")?;
}
}
Item => html.write_all(b"</li>")?,
Strong => {
html.write_all(b"</b>")?;
write_inline(&mut gmi, state, "**", &mut links)?;
}
Emphasis => {
html.write_all(b"</i>")?;
write_inline(&mut gmi, state, "*", &mut links)?;
}
Strikethrough => {
html.write_all(b"</s>")?;
write_inline(&mut gmi, state, "~", &mut links)?;
}
Link | Image => {
gmi.write_fmt(format_args!(
"{}[{}]", // example[1] ...\r\n => https://... [1]: example
links.last().unwrap().title,
links.len(),
))?;
}
TableHead => html.write_all(b"</tr></thead><tbody>")?,
TableRow => html.write_all(b"</tr>")?,
TableCell => {
if state == State::TableHead {
html.write_all(b"</th>")?
} else {
html.write_all(b"</td>")?
}
}
Table => html.write_all(b"</tbody></table>")?,
_ => {}
}
match state {
State::Metadata(false) => {
state = State::Start;
}
_ => {
state = State::Paragraph;
}
}
}
Text(text) => {
match state {
State::Metadata(_) => {
// TODO: parse yaml
continue;
}
_ => {}
}
html.write_all(text.as_bytes())?;
write_inline(&mut gmi, state, &text, &mut links)?;
}
Code(code) => {
html.write_all(b"<code>")?;
html.write_all(code.as_bytes())?;
html.write_all(b"</code>")?;
write_inline(&mut gmi, state, "`", &mut links)?;
write_inline(&mut gmi, state, &code, &mut links)?;
write_inline(&mut gmi, state, "`", &mut links)?;
}
SoftBreak => {
html.write_all(b" ")?;
write_inline(&mut gmi, state, " ", &mut links)?;
}
HardBreak => {
html.write_all(b"<br>")?;
gmi.write_all(b"\r\n")?;
if state == State::Quote {
gmi.write_all(b"> ")?;
}
}
Rule => {
html.write_all(b"<hr>")?;
write_paragraph_start(&mut gmi, state)?;
gmi.write_all(b"---")?;
}
TaskListMarker(done) => {
if done {
html.write_all(b"<input type=checkbox checked disabled>")?;
write_inline(&mut gmi, state, "[x] ", &mut links)?;
} else {
html.write_all(b"<input type=checkbox disabled>")?;
write_inline(&mut gmi, state, "[ ] ", &mut links)?;
}
}
other => {
eprintln!("Unsupported event: {:?}", other);
}
}
}
html.flush()?;
gmi.flush()?;
Ok(())
}
#[inline(always)]
fn create_file(path: impl AsRef<Path>) -> std::io::Result<BufWriter<std::fs::File>> {
let f = std::fs::OpenOptions::new()
.create(true)
.write(true)
.open(path)?;
Ok(BufWriter::new(f))
}
#[inline(always)]
fn write_paragraph_start(gmi: &mut impl std::io::Write, state: State) -> std::io::Result<()> {
if state != State::Start && state != State::Quote {
gmi.write_all(b"\r\n\r\n")?;
}
Ok(())
}
#[inline(always)]
fn write_inline(
gmi: &mut impl std::io::Write,
state: State,
text: &str,
links: &mut Vec<GmiLink>,
) -> std::io::Result<()> {
if state == State::Link {
links.last_mut().unwrap().title.push_str(text);
} else {
gmi.write_all(text.as_bytes())?;
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
Start,
Paragraph,
Link,
Quote,
TableHead,
Metadata(bool),
}
struct GmiLink<'link> {
title: String,
url: CowStr<'link>,
}