fix: line breaks and link titles in gemini

This commit is contained in:
DarkCat09 2024-11-21 16:24:59 +04:00
parent be57431311
commit c7c94581b6
Signed by: DarkCat09
GPG key ID: BD3CE9B65916CD82
2 changed files with 127 additions and 49 deletions

View file

@ -9,7 +9,8 @@ mydata: 123
- ненумерованный список, элемент 1
- ненумерованный список, элемент 1,
даже с продолжением
- элемент 2
- element 3
@ -21,9 +22,13 @@ mydata: 123
- [ ] Todo
- [ ] Won't fix
[[x] Task inside link](https://dc09.ru)
> [!WARNING]
>
> Some important quote
> continuing here \
> With line break
text text text `inline code` text text text

View file

@ -16,12 +16,15 @@ pub fn compile_markdown(
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::*};
@ -29,9 +32,7 @@ pub fn compile_markdown(
match tag {
Paragraph => {
html.write_all(b"<p>")?;
if state != State::Start {
gmi.write_all(b"\r\n\r\n")?;
}
write_paragraph_start(&mut gmi, state)?;
}
Heading { level, id, .. } => {
@ -41,95 +42,110 @@ pub fn compile_markdown(
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::GmiPrefix(hashes);
state = State::Paragraph;
}
BlockQuote(_kind) => {
html.write_all(b"<blockquote>")?;
write_paragraph_start(&mut gmi, state)?;
gmi.write_all(b"> ")?;
state = State::GmiPrefix("> ");
state = State::Quote;
}
CodeBlock(CodeBlockKind::Fenced(lang)) => {
html.write_all(b"<pre><code>")?;
// 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>")?;
gmi.write_all(b"**")?;
write_inline(&mut gmi, state, "**", &mut links)?;
}
Emphasis => {
html.write_all(b"<i>")?;
gmi.write_all(b"*")?;
write_inline(&mut gmi, state, "*", &mut links)?;
}
Strikethrough => {
html.write_all(b"<s>")?;
gmi.write_all(b"~")?;
write_inline(&mut gmi, state, "~", &mut links)?;
}
Link {
dest_url, title, ..
} => {
html.write_fmt(format_args!("<a href=\"{}\">{}</a>", dest_url, title))?;
gmi.write_fmt(format_args!("{}[{}]", &title, links.len() + 1))?;
Link { dest_url, .. } => {
html.write_fmt(format_args!("<a href=\"{}\">", dest_url))?;
links.push(GmiLink {
title,
title: String::new(),
url: dest_url,
});
state = State::Link;
}
Image {
dest_url, title, ..
} => {
html.write_fmt(format_args!(
"<img src=\"{}\" alt=\"{}\">",
dest_url, title
))?;
gmi.write_fmt(format_args!("{}[{}]", &title, links.len() + 1))?;
Image { dest_url, .. } => {
links.push(GmiLink {
title,
title: String::new(),
url: dest_url,
});
state = State::Link;
}
Table(_align) => {
html.write_all(b"<table>")?;
write_paragraph_start(&mut gmi, state)?;
// gmi ??
}
@ -150,6 +166,10 @@ pub fn compile_markdown(
}
}
MetadataBlock(_) => {
state = State::Metadata(state != State::Start);
}
other => {
eprintln!("Unsupported tag: {:?}", other);
}
@ -164,10 +184,10 @@ pub fn compile_markdown(
html.write_all(b"</p>")?;
if !links.is_empty() {
gmi.write_all(b"\r\n\r\n")?;
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,
))?;
}
@ -183,6 +203,7 @@ pub fn compile_markdown(
List(ordered) => {
if ordered {
html.write_all(b"</ol>")?;
ol = false;
} else {
html.write_all(b"</ul>")?;
}
@ -190,17 +211,23 @@ pub fn compile_markdown(
Item => html.write_all(b"</li>")?,
Strong => {
html.write_all(b"</b>")?;
gmi.write_all(b"**")?;
write_inline(&mut gmi, state, "**", &mut links)?;
}
Emphasis => {
html.write_all(b"</i>")?;
gmi.write_all(b"*")?;
write_inline(&mut gmi, state, "*", &mut links)?;
}
Strikethrough => {
html.write_all(b"</s>")?;
gmi.write_all(b"~")?;
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(),
))?;
}
Link => {}
TableHead => html.write_all(b"</tr></thead><tbody>")?,
TableRow => html.write_all(b"</tr>")?,
TableCell => {
@ -214,12 +241,27 @@ pub fn compile_markdown(
_ => {}
}
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())?;
gmi.write_all(text.as_bytes())?;
write_inline(&mut gmi, state, &text, &mut links)?;
}
Code(code) => {
@ -227,33 +269,39 @@ pub fn compile_markdown(
html.write_all(code.as_bytes())?;
html.write_all(b"</code>")?;
gmi.write_all(b"`")?;
gmi.write_all(code.as_bytes())?;
gmi.write_all(b"`")?;
write_inline(&mut gmi, state, "`", &mut links)?;
write_inline(&mut gmi, state, &code, &mut links)?;
write_inline(&mut gmi, state, "`", &mut links)?;
}
SoftBreak => {}
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 let State::GmiPrefix(prefix) = state {
gmi.write_all(prefix.as_bytes())?;
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(state) => {
if state {
TaskListMarker(done) => {
if done {
html.write_all(b"<input type=checkbox checked disabled>")?;
gmi.write_all(b"[x]")?;
write_inline(&mut gmi, state, "[x] ", &mut links)?;
} else {
html.write_all(b"<input type=checkbox disabled>")?;
gmi.write_all(b"[ ]")?;
write_inline(&mut gmi, state, "[ ] ", &mut links)?;
}
}
@ -278,15 +326,40 @@ fn create_file(path: impl AsRef<Path>) -> std::io::Result<BufWriter<std::fs::Fil
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,
GmiPrefix(&'static str),
Link,
Quote,
TableHead,
Metadata(bool),
}
struct GmiLink<'link> {
title: CowStr<'link>,
title: String,
url: CowStr<'link>,
}