Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions crates/formats/src/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,18 @@ fn attr(attrs: &str, key: &str) -> Option<String> {
attrs.get(start..start + end).map(unescape)
}

fn font_size(attrs: &str) -> Option<u8> {
let style = attr(attrs, "style")?;
style.split(';').find_map(|declaration| {
let (property, value) = declaration.split_once(':')?;
if !property.trim().eq_ignore_ascii_case("font-size") {
return None;
}
let points = value.trim().strip_suffix("pt")?.trim().parse::<u8>().ok()?;
(8..=72).contains(&points).then_some(points)
})
}

#[derive(Default)]
struct Writer {
out: String,
Expand All @@ -267,6 +279,7 @@ struct Writer {
div_diagram: bool,
in_math: bool,
in_math_block: bool,
span_sizes: Vec<Option<u8>>,
href: Vec<Option<String>>,
row: Option<Vec<String>>,
cell: String,
Expand Down Expand Up @@ -465,8 +478,23 @@ impl Writer {
self.out.push_str("```");
self.block_break();
}
("span", false) if attrs.to_lowercase().contains("math") => self.in_math = true,
("span", true) => self.in_math = false,
("span", false) => {
let size = font_size(attrs);
self.span_sizes.push(size);
if let Some(size) = size {
self.push(&format!("<span style=\"font-size: {size}pt\">"));
}
if attrs.to_lowercase().contains("math") {
self.in_math = true;
}
}
("span", true) => {
if self.span_sizes.pop().flatten().is_some() {
self.push("</span>");
} else {
self.in_math = false;
}
}
("a", false) => {
let href = attr(attrs, "href");
self.push("[");
Expand Down
98 changes: 93 additions & 5 deletions crates/formats/src/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
//! (nested by indentation), block quotes, fenced code (a `mermaid` fence is kept as
//! code with its language), math blocks (`$$ ... $$`), tables, rules and standalone
//! images. Supported inline: bold, italic, strikethrough, code, links, images and
//! `$math$`. Not supported: reference links, HTML inside Markdown, nested block
//! quotes and lists inside quotes, setext headings, footnotes.
//! `$math$`, and NoteCraft font-size spans. Other HTML is not supported. Also not
//! supported: reference links, nested block quotes and lists inside quotes, setext
//! headings, footnotes.

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Span {
Expand All @@ -15,6 +16,8 @@ pub struct Span {
pub strike: bool,
pub code: bool,
pub math: bool,
/// Font size in points, carried by a NoteCraft inline `<span>`.
pub font_size: Option<u8>,
/// Link target, if this span is part of a link.
pub link: Option<String>,
/// Image source, if this span is an inline image (the text is the alt text).
Expand Down Expand Up @@ -53,6 +56,7 @@ struct Style {
bold: bool,
italic: bool,
strike: bool,
font_size: Option<u8>,
}

/// Parses inline Markdown into styled spans.
Expand All @@ -76,17 +80,80 @@ fn slice(chars: &[char], a: usize, b: usize) -> &[char] {

fn push_text(out: &mut Vec<Span>, buf: &mut String, st: Style, link: &Option<String>) {
if !buf.is_empty() {
out.push(Span { text: std::mem::take(buf), bold: st.bold, italic: st.italic, strike: st.strike, link: link.clone(), ..Span::default() });
out.push(Span {
text: std::mem::take(buf),
bold: st.bold,
italic: st.italic,
strike: st.strike,
font_size: st.font_size,
link: link.clone(),
..Span::default()
});
}
}

fn span_open_end(chars: &[char], start: usize) -> Option<usize> {
let remaining = chars.get(start..)?;
let end = remaining.iter().position(|c| *c == '>')?;
let tag: String = remaining.get(..=end)?.iter().collect();
tag.to_ascii_lowercase().starts_with("<span ").then_some(start + end + 1)
}

fn font_size_open(chars: &[char], start: usize) -> Option<(u8, usize)> {
let end = span_open_end(chars, start)?;
let tag: String = chars.get(start..end)?.iter().collect();
let lower = tag.to_ascii_lowercase();
let style_start = lower.find("style=\"")? + "style=\"".len();
let style_end = lower.get(style_start..)?.find('"')? + style_start;
let style = lower.get(style_start..style_end)?;
let value = style.split(';').find_map(|declaration| {
let (property, value) = declaration.split_once(':')?;
property.trim().eq("font-size").then(|| value.trim())
})?;
let points = value.strip_suffix("pt")?.parse::<u8>().ok()?;
(8..=72).contains(&points).then_some((points, end))
}

fn font_size_close(chars: &[char], start: usize) -> Option<usize> {
let close = ['<', '/', 's', 'p', 'a', 'n', '>'];
let mut depth = 1usize;
let mut at = start;
while at < chars.len() {
if chars.get(at..at + close.len()) == Some(close.as_slice()) {
depth = depth.saturating_sub(1);
if depth == 0 {
return Some(at);
}
at += close.len();
} else if let Some(after) = span_open_end(chars, at) {
depth += 1;
at = after;
} else {
at += 1;
}
}
None
}

fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize) -> Vec<Span> {
let mut out = Vec::new();
let mut buf = String::new();
let mut i = 0;
while i < chars.len() {
let c = chars.get(i).copied().unwrap_or(' ');
let next = chars.get(i + 1).copied();
if c == '<'
&& depth < MAX_DEPTH
&& let Some((font_size, content_start)) = font_size_open(chars, i)
&& let Some(content_end) = font_size_close(chars, content_start)
{
push_text(&mut out, &mut buf, st, &link);
let mut sized = st;
sized.font_size = Some(font_size);
out.extend(inline(slice(chars, content_start, content_end), sized, link.clone(), depth + 1));
i = content_end + "</span>".chars().count();
continue;
}
match c {
'\\' if next.is_some() => {
if let Some(n) = next {
Expand All @@ -104,6 +171,7 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize) -> Vec<
bold: st.bold,
italic: st.italic,
strike: st.strike,
font_size: st.font_size,
link: link.clone(),
..Span::default()
});
Expand Down Expand Up @@ -162,7 +230,13 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize) -> Vec<
'$' => match find(chars, i + 1, &['$']) {
Some(end) if end > i + 1 && !slice(chars, i + 1, end).contains(&'\n') => {
push_text(&mut out, &mut buf, st, &link);
out.push(Span { text: slice(chars, i + 1, end).iter().collect(), math: true, link: link.clone(), ..Span::default() });
out.push(Span {
text: slice(chars, i + 1, end).iter().collect(),
math: true,
font_size: st.font_size,
link: link.clone(),
..Span::default()
});
i = end + 1;
}
_ => {
Expand All @@ -175,7 +249,7 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize) -> Vec<
push_text(&mut out, &mut buf, st, &link);
// Preserve the surrounding link when an image is nested in one. This is
// how attachment cards (`[![icon](icon) name](file)`) retain their target.
out.push(Span { text: alt, image: Some(url), link: link.clone(), ..Span::default() });
out.push(Span { text: alt, image: Some(url), font_size: st.font_size, link: link.clone(), ..Span::default() });
i = after;
}
None => {
Expand Down Expand Up @@ -415,6 +489,20 @@ mod tests {
assert!(s.iter().any(|x| x.bold && x.italic && x.text == "italic"));
}

#[test]
fn font_size_spans_round_trip_and_nest() {
let source = "<span style=\"font-size: 18pt\">outer <span style=\"font-size: 12pt\">inner</span> outer</span>";
let spans = parse_inline(source);
assert!(spans.iter().any(|span| span.text == "outer " && span.font_size == Some(18)));
assert!(spans.iter().any(|span| span.text == "inner" && span.font_size == Some(12)));
assert!(spans.iter().any(|span| span.text == " outer" && span.font_size == Some(18)));
assert_eq!(parse_inline(&crate::render::spans_to_markdown(&spans)), spans);

let invalid = parse_inline("<span style=\"font-size: 73pt\">too large</span>");
assert_eq!(text_of(&invalid), "<span style=\"font-size: 73pt\">too large</span>");
assert!(invalid.iter().all(|span| span.font_size.is_none()));
}

#[test]
fn links_images_and_math() {
let s = parse_inline("see [the **site**](https://x.test) and ![pic](assets/a.png) with $E=mc^2$");
Expand Down
51 changes: 41 additions & 10 deletions crates/formats/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,21 +214,27 @@ fn marked(spans: &[Span], level: usize) -> String {

/// One span with nothing but its code, picture, maths or link written round it.
fn leaf(s: &Span) -> String {
let sized = |text: String| match s.font_size {
Some(size) => format!("<span style=\"font-size: {size}pt\">{text}</span>"),
None => text,
};
if let Some(src) = &s.image {
let image = format!("![{}]({src})", s.text);
return match &s.link {
let image = match &s.link {
Some(target) => format!("[{image}]({target})"),
None => image,
};
return sized(image);
}
if s.math {
return format!("${}$", s.text);
return sized(format!("${}$", s.text));
}
let text = if s.code { format!("`{}`", s.text) } else { s.text.clone() };
match &s.link {
let text = match &s.link {
Some(target) => format!("[{text}]({target})"),
None => text,
}
};
sized(text)
}

/// Blocks as the HTML body of a page: the inside of `<body>`, one block per line.
Expand Down Expand Up @@ -324,15 +330,22 @@ pub fn spans_to_html(spans: &[Span]) -> String {
let mut out = String::new();
for s in spans {
if let Some(src) = &s.image {
let image = format!("<img src=\"{}\" alt=\"{}\">", escape(src), escape(&s.text));
let mut image = format!("<img src=\"{}\" alt=\"{}\">", escape(src), escape(&s.text));
if let Some(size) = s.font_size {
image = format!("<span style=\"font-size: {size}pt\">{image}</span>");
}
match &s.link {
Some(target) => out.push_str(&format!("<a href=\"{}\">{image}</a>", escape(target))),
None => out.push_str(&image),
}
continue;
}
if s.math {
out.push_str(&format!("<span class=\"math\">${}$</span>", escape(&s.text)));
let mut math = format!("<span class=\"math\">${}$</span>", escape(&s.text));
if let Some(size) = s.font_size {
math = format!("<span style=\"font-size: {size}pt\">{math}</span>");
}
out.push_str(&math);
continue;
}
let mut text = escape(&s.text);
Expand All @@ -349,10 +362,15 @@ pub fn spans_to_html(spans: &[Span]) -> String {
text = format!("<b>{text}</b>");
}
}
match &s.link {
Some(target) => out.push_str(&format!("<a href=\"{}\">{text}</a>", escape(target))),
None => out.push_str(&text),
}
let text = match &s.link {
Some(target) => format!("<a href=\"{}\">{text}</a>", escape(target)),
None => text,
};
let text = match s.font_size {
Some(size) => format!("<span style=\"font-size: {size}pt\">{text}</span>"),
None => text,
};
out.push_str(&text);
}
out
}
Expand Down Expand Up @@ -533,4 +551,17 @@ fn b() {}"
assert!(html.contains("<b>bold</b>"), "{html}");
assert!(html.contains("<a href=\"https://example.com\">a link</a>"), "{html}");
}

#[test]
fn inline_font_size_round_trips_through_cmgfm_and_html() {
let source = "<span style=\"font-size: 18pt\">larger text</span>";
let blocks = parse(source);

let markdown = blocks_to_markdown(&blocks);
assert_eq!(parse(&markdown), blocks, "CMGFM retains the size");

let html = blocks_to_html(&blocks);
assert!(html.contains("<span style=\"font-size: 18pt\">larger text</span>"), "{html}");
assert_eq!(parse(&html::to_markdown(&html)), blocks, "HTML retains the size");
}
}
34 changes: 34 additions & 0 deletions crates/ui-egui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2745,6 +2745,7 @@ impl NoteCraftApp {
act,
ribbon::Act::Clipboard(_)
| ribbon::Act::Mark(_)
| ribbon::Act::FontSize(_)
| ribbon::Act::Block(_)
| ribbon::Act::ClearFormatting
| ribbon::Act::Direction(_)
Expand All @@ -2763,6 +2764,11 @@ impl NoteCraftApp {
crate::containers::ask_clipboard(ctx, *which == "cut");
return true;
}
ribbon::Act::FontSize(_) => {
self.status = crate::tl_id!("ui.select_text_before_changing_font_size").into();
self.status_is_error = false;
return true;
}
ribbon::Act::Mark(mark) => {
if !pageedit::toggle_mark(&mut ed.blocks, range, mark) {
return true;
Expand Down Expand Up @@ -2855,6 +2861,7 @@ impl NoteCraftApp {
ribbon::Act::Equation(tex) => self.insert_in_page(&format!("${tex}$")),
ribbon::Act::Tab(name) => self.ribbon_tab = name,
ribbon::Act::Mark(mark) => self.apply_mark(mark),
ribbon::Act::FontSize(size) => self.apply_font_size(size),
ribbon::Act::Block(kind) => self.apply_block_kind(kind),
ribbon::Act::Insert(what) => match what {
"space" => {
Expand Down Expand Up @@ -3621,6 +3628,33 @@ impl NoteCraftApp {
Self::mark_dirty_from_blocks(ed);
}

fn apply_font_size(&mut self, size: u8) {
if !ribbon::FONT_SIZES.contains(&size) {
log::warn!("ribbon requested unsupported font size {size} pt");
return;
}
let Some(ed) = self.editor.as_mut() else { return };
let Some(caret) = ed.caret.as_mut() else {
self.status = crate::tl_id!("ui.click_in_the_page_first_then_use_the_ribbon").into();
self.status_is_error = false;
return;
};
if caret.selection.0 == caret.selection.1 {
self.status = crate::tl_id!("ui.select_text_before_changing_font_size").into();
self.status_is_error = false;
return;
}
let open = format!("<span style=\"font-size: {size}pt\">");
let (text, selection) = pageedit::wrap_selection_with(&caret.text, caret.selection, &open, "</span>");
caret.text = text;
caret.selection = selection;
if let Some(block) = ed.blocks.get_mut(caret.block) {
pageedit::set_block_text(block, &caret.text);
}
ed.rebuild_body();
Self::mark_dirty_from_blocks(ed);
}

/// The keys Windows users expect for paragraph direction. Alt+Shift remains available
/// to Windows for switching the active input language.
fn direction_keys(&mut self, ctx: &Context) {
Expand Down
Loading
Loading