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
6 changes: 5 additions & 1 deletion crates/formats/src/boxes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,11 @@ fn styled_spans_in(block: &Block) -> usize {
Block::Table { head, rows } => head.iter().chain(rows.iter().flatten()).collect(),
Block::Code { .. } | Block::MathBlock(_) | Block::Rule | Block::Image { .. } => Vec::new(),
};
lines.iter().flat_map(|spans| spans.iter()).filter(|span| span.font_size.is_some() || span.font_family.is_some()).count()
lines
.iter()
.flat_map(|spans| spans.iter())
.filter(|span| span.font_size.is_some() || span.font_family.is_some() || span.colour.is_some() || span.highlight.is_some())
.count()
}

#[cfg(test)]
Expand Down
22 changes: 20 additions & 2 deletions crates/formats/src/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,15 @@ fn font_size(attrs: &str) -> Option<u8> {
})
}

/// The text colour or highlight of an HTML span, when it is a colour NoteCraft writes (#260).
fn span_colour(attrs: &str, wanted: &str) -> Option<String> {
let style = attr(attrs, "style")?;
crate::markdown::style_declarations(&style).into_iter().find_map(|declaration| {
let (property, value) = declaration.split_once(':')?;
property.trim().eq_ignore_ascii_case(wanted).then(|| crate::markdown::css_colour(value)).flatten()
})
}

fn font_family(attrs: &str) -> Option<String> {
let style = attr(attrs, "style")?;
crate::markdown::style_declarations(&style).into_iter().find_map(|declaration| {
Expand Down Expand Up @@ -603,15 +612,24 @@ impl Writer {
("span", false) => {
let size = font_size(attrs);
let family = font_family(attrs);
self.span_sizes.push(size.is_some() || family.is_some());
if size.is_some() || family.is_some() {
let colour = span_colour(attrs, "color");
let highlight = span_colour(attrs, "background-color");
let styled = size.is_some() || family.is_some() || colour.is_some() || highlight.is_some();
self.span_sizes.push(styled);
if styled {
let mut styles = Vec::new();
if let Some(family) = family {
styles.push(format!("font-family: {}", escape(&crate::markdown::font_family_css(&family))));
}
if let Some(size) = size {
styles.push(format!("font-size: {size}pt"));
}
if let Some(colour) = colour {
styles.push(format!("color: {colour}"));
}
if let Some(colour) = highlight {
styles.push(format!("background-color: {colour}"));
}
self.push(&format!("<span style=\"{}\">", styles.join("; ")));
}
if attrs.to_lowercase().contains("math") {
Expand Down
81 changes: 63 additions & 18 deletions crates/formats/src/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ pub struct Span {
/// Font size in points, carried by a NoteCraft inline `<span>`.
pub font_size: Option<u8>,
pub font_family: Option<String>,
/// Text colour, as `#rrggbb`, from a NoteCraft inline `<span style="color: ...">` (#260).
pub colour: Option<String>,
/// Highlight behind the text, as `#rrggbb`, from `background-color` (#260).
pub highlight: Option<String>,
/// 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 @@ -69,6 +73,8 @@ struct Style {
script: Option<Script>,
font_size: Option<u8>,
font_family: Option<String>,
colour: Option<String>,
highlight: Option<String>,
}

/// Parses inline Markdown into styled spans.
Expand Down Expand Up @@ -131,6 +137,8 @@ fn push_text(out: &mut Vec<Span>, buf: &mut String, st: &Style, link: &Option<St
script: st.script,
font_size: st.font_size,
font_family: st.font_family.clone(),
colour: st.colour.clone(),
highlight: st.highlight.clone(),
link: link.clone(),
..Span::default()
});
Expand Down Expand Up @@ -206,31 +214,56 @@ pub(crate) fn style_declarations(style: &str) -> Vec<&str> {
result
}

fn font_style_open(chars: &[char], start: usize) -> Option<(Option<u8>, Option<String>, usize)> {
/// What a NoteCraft inline `<span style="...">` sets. Every declaration must be one NoteCraft
/// writes, or the span is not one of ours and is left as text.
struct SpanStyle {
size: Option<u8>,
family: Option<String>,
colour: Option<String>,
highlight: Option<String>,
}

/// A colour as NoteCraft writes it, `#rrggbb` in lower case; `#rgb` is widened (#260).
pub fn css_colour(value: &str) -> Option<String> {
let hex = value.trim().strip_prefix('#')?;
if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
match hex.len() {
6 => Some(format!("#{}", hex.to_ascii_lowercase())),
3 => Some(format!("#{}", hex.chars().flat_map(|c| [c, c]).collect::<String>().to_ascii_lowercase())),
_ => None,
}
}

fn font_style_open(chars: &[char], start: usize) -> Option<(SpanStyle, 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 = crate::html::unescape(tag.get(style_start..style_end)?);
let mut size = None;
let mut family = None;
let mut found = SpanStyle { size: None, family: None, colour: None, highlight: None };
for declaration in style_declarations(&style).into_iter().filter(|part| !part.trim().is_empty()) {
let (property, value) = declaration.split_once(':')?;
let value = value.trim();
if property.trim().eq_ignore_ascii_case("font-size") {
let points = value.strip_suffix("pt")?.parse::<u8>().ok()?;
if !(8..=72).contains(&points) {
return None;
let property = property.trim().to_ascii_lowercase();
match property.as_str() {
"font-size" => {
let points = value.strip_suffix("pt")?.parse::<u8>().ok()?;
if !(8..=72).contains(&points) {
return None;
}
found.size = Some(points);
}
size = Some(points);
} else if property.trim().eq_ignore_ascii_case("font-family") {
family = Some(font_family_from_css(value)?);
} else {
return None;
"font-family" => found.family = Some(font_family_from_css(value)?),
"color" => found.colour = Some(css_colour(value)?),
"background-color" => found.highlight = Some(css_colour(value)?),
_ => return None,
}
}
(size.is_some() || family.is_some()).then_some((size, family, end))
let any = found.size.is_some() || found.family.is_some() || found.colour.is_some() || found.highlight.is_some();
any.then_some((found, end))
}

fn font_size_close(chars: &[char], start: usize) -> Option<usize> {
Expand Down Expand Up @@ -300,16 +333,22 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize, cell_br
}
if c == '<'
&& depth < MAX_DEPTH
&& let Some((font_size, font_family, content_start)) = font_style_open(chars, i)
&& let Some((found, content_start)) = font_style_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.clone();
if font_size.is_some() {
sized.font_size = font_size;
if found.size.is_some() {
sized.font_size = found.size;
}
if found.family.is_some() {
sized.font_family = found.family;
}
if found.colour.is_some() {
sized.colour = found.colour;
}
if font_family.is_some() {
sized.font_family = font_family;
if found.highlight.is_some() {
sized.highlight = found.highlight;
}
out.extend(inline(slice(chars, content_start, content_end), sized, link.clone(), depth + 1, cell_breaks));
i = content_end + "</span>".chars().count();
Expand Down Expand Up @@ -369,6 +408,8 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize, cell_br
script: st.script,
font_size: st.font_size,
font_family: st.font_family.clone(),
colour: st.colour.clone(),
highlight: st.highlight.clone(),
link: link.clone(),
..Span::default()
});
Expand Down Expand Up @@ -432,6 +473,8 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize, cell_br
math: true,
font_size: st.font_size,
font_family: st.font_family.clone(),
colour: st.colour.clone(),
highlight: st.highlight.clone(),
underline: st.underline,
script: st.script,
link: link.clone(),
Expand All @@ -454,6 +497,8 @@ fn inline(chars: &[char], st: Style, link: Option<String>, depth: usize, cell_br
image: Some(url),
font_size: st.font_size,
font_family: st.font_family.clone(),
colour: st.colour.clone(),
highlight: st.highlight.clone(),
underline: st.underline,
script: st.script,
link: link.clone(),
Expand Down
38 changes: 38 additions & 0 deletions crates/formats/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,12 @@ fn inline_style(s: &Span, text: String) -> String {
if let Some(size) = s.font_size {
styles.push(format!("font-size: {size}pt"));
}
if let Some(colour) = s.colour.as_deref().and_then(crate::markdown::css_colour) {
styles.push(format!("color: {colour}"));
}
if let Some(colour) = s.highlight.as_deref().and_then(crate::markdown::css_colour) {
styles.push(format!("background-color: {colour}"));
}
if styles.is_empty() { text } else { format!("<span style=\"{}\">{text}</span>", styles.join("; ")) }
}

Expand Down Expand Up @@ -914,6 +920,38 @@ fn b() {}"
assert_eq!(parse(&html::to_markdown(&html)), blocks, "HTML retains the size");
}

#[test]
fn text_colour_and_highlight_round_trip_through_cmgfm_and_html() {
// Issue #260: exact colours, nested with a size, and a short colour widened.
let source = "plain <span style=\"color: #C00000\">red <span style=\"background-color: #ff0\">marked</span></span> \
<span style=\"font-size: 18pt; color: #1a5fd0; background-color: #ccffcc\">all three</span>";
let blocks = parse(source);
let Block::Paragraph(spans) = &blocks[0] else { panic!("expected a paragraph") };
let span = |text: &str| spans.iter().find(|s| s.text == text).cloned().unwrap_or_default();
assert_eq!(span("red ").colour.as_deref(), Some("#c00000"));
assert_eq!(span("red ").highlight, None);
assert_eq!((span("marked").colour.as_deref(), span("marked").highlight.as_deref()), (Some("#c00000"), Some("#ffff00")));
let all = span("all three");
assert_eq!((all.font_size, all.colour.as_deref(), all.highlight.as_deref()), (Some(18), Some("#1a5fd0"), Some("#ccffcc")));
assert_eq!(blocks_to_text(&blocks), "plain red marked all three", "colours are not visible page text");

let markdown = blocks_to_markdown(&blocks);
assert_eq!(parse(&markdown), blocks, "CMGFM keeps the colours:\n{markdown}");
let html = blocks_to_html(&blocks);
assert!(html.contains("color: #c00000"), "{html}");
assert!(html.contains("background-color: #ffff00"), "{html}");
assert_eq!(parse(&html::to_markdown(&html)), blocks, "HTML keeps the colours:\n{html}");
}

#[test]
fn a_colour_that_is_not_a_plain_hex_value_is_not_taken() {
for style in ["color: red", "color: rgb(1,2,3)", "color: #12345", "background-color: url(x)"] {
let blocks = parse(&format!("<span style=\"{style}\">x</span>"));
let Block::Paragraph(spans) = &blocks[0] else { panic!("expected a paragraph") };
assert!(spans.iter().all(|s| s.colour.is_none() && s.highlight.is_none()), "{style}: {spans:?}");
}
}

#[test]
fn font_family_underline_and_scripts_round_trip_in_both_formats() {
let source = "<span style=\"font-family: DejaVu Sans; font-size: 18pt\"><u>underlined</u> H<sub>2</sub>O x<sup>2</sup></span>";
Expand Down
1 change: 1 addition & 0 deletions crates/ink/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

pub mod pick;
pub mod rack;
pub mod recognise;
pub mod ruler;
pub mod shape;
pub mod shapes;
Expand Down
Loading
Loading