use std::borrow::Cow;
use crate::converter::utility::content::ZERO_WIDTH_SPACE;
use crate::text;
#[must_use]
pub const fn is_collapsible(character: char) -> bool {
matches!(character, ' ' | '\t' | '\n' | '\r')
}
#[must_use]
pub fn with_line_feeds(decoded: Cow<'_, str>) -> Cow<'_, str> {
if decoded.contains('\r') {
Cow::Owned(decoded.replace("\r\n", "\n").replace('\r', "\n"))
} else {
decoded
}
}
#[must_use]
pub fn with_white_space_references_decoded(source: &str) -> Cow<'_, str> {
let mut buffer: Option<String> = None;
let mut copied = 0;
let mut from = 0;
while let Some(found) = source[from..].find('&') {
let amp = from + found;
from = amp + 1;
let Some((end, character, None)) = text::decode_character_reference(source, amp, text::ReferenceContext::Text)
else {
continue;
};
if !is_collapsible(character) || !source[..end].ends_with(';') {
continue;
}
let target = buffer.get_or_insert_with(|| String::with_capacity(source.len()));
target.push_str(&source[copied..amp]);
target.push(character);
copied = end;
from = end;
}
let Some(mut decoded) = buffer else {
return Cow::Borrowed(source);
};
decoded.push_str(&source[copied..]);
Cow::Owned(decoded)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Run {
pub segment_break: bool,
}
impl Run {
fn of(white_space: &str) -> Option<Self> {
(!white_space.is_empty()).then(|| Self {
segment_break: white_space.contains('\n'),
})
}
#[must_use]
pub fn writes_space(self, before: Option<char>, after: Option<char>) -> bool {
!(self.segment_break && segment_break_is_removed(before, after))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextClass<'text> {
WhiteSpaceOnly(Option<Run>),
Text {
prefix: Option<Run>,
core: &'text str,
suffix: Option<Run>,
},
}
#[must_use]
pub fn classify_text(decoded: &str) -> TextClass<'_> {
let core = decoded.trim_matches(is_collapsible);
if core.is_empty() {
return TextClass::WhiteSpaceOnly(Run::of(decoded));
}
let start = decoded.len() - decoded.trim_start_matches(is_collapsible).len();
let end = start + core.len();
TextClass::Text {
prefix: Run::of(&decoded[..start]),
core,
suffix: Run::of(&decoded[end..]),
}
}
pub const FORM_FEED: char = '\u{c}';
#[must_use]
pub const fn is_unseen(character: char) -> bool {
character.is_whitespace() && character != FORM_FEED
}
#[must_use]
pub fn is_blank(decoded: &str) -> bool {
decoded.chars().all(is_unseen)
}
#[must_use]
pub fn edges(decoded: &str) -> (&'static str, &'static str) {
let is_space = |character: char| matches!(character, ' ' | '\t') || text::is_unicode_space(character);
let before = if decoded.starts_with(is_unseen) { " " } else { "" };
let after = if decoded.ends_with("\n\n") || decoded.ends_with("\r\n\r\n") {
"\n\n"
} else if decoded.ends_with(is_space) {
" "
} else {
""
};
(before, after)
}
#[must_use]
pub fn visible(decoded: &str) -> Cow<'_, str> {
text::normalize_block_whitespace_cow(decoded.trim_matches(is_unseen))
}
#[must_use]
pub fn mark_edges(content: &str) -> (&str, &str) {
let start = content.len() - content.trim_start().len();
let end = content.trim_end().len().max(start);
(&content[..start], &content[end..])
}
#[must_use]
pub fn owed_part<'run>(written: &str, prefix: &'run str) -> &'run str {
if space_is_owed(written) {
prefix
} else {
prefix.trim_start_matches(is_collapsible)
}
}
#[must_use]
pub fn cell_text(decoded: &str) -> Cow<'_, str> {
text::normalize_cell_whitespace_cow(decoded)
}
#[must_use]
pub fn segment_break_is_removed(before: Option<char>, after: Option<char>) -> bool {
before == Some(ZERO_WIDTH_SPACE) || after == Some(ZERO_WIDTH_SPACE)
}
#[must_use]
pub fn space_is_owed(written: &str) -> bool {
!written.ends_with([' ', '\n'])
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextPlace {
AfterBreak,
ElementStart,
AfterEmptyElement,
AfterFlowElement,
AfterText,
}
#[must_use]
pub fn writes_in_text_flow(name: &str) -> bool {
name == "span"
}
#[must_use]
pub fn starts_with_unicode_space(decoded: &str) -> bool {
decoded
.chars()
.take_while(|character| character.is_whitespace())
.any(text::is_unicode_space)
}
#[must_use]
pub fn unicode_space_is_kept(written: &str, place: TextPlace) -> bool {
written.ends_with(' ') && matches!(place, TextPlace::AfterEmptyElement | TextPlace::AfterFlowElement)
}
#[must_use]
pub fn space_is_owed_in(output: &String, ctx: &crate::converter::context::Context) -> bool {
let is_block_buffer = std::ptr::from_ref::<String>(output) as usize == ctx.block_output_ptr;
space_is_owed(output) && !(output.is_empty() && is_block_buffer)
}
#[must_use]
pub fn unicode_line_indent(decoded: &str) -> String {
let mut indent = String::new();
for character in decoded.chars().take_while(|character| is_unseen(*character)) {
if is_collapsible(character) {
if !indent.is_empty() && !indent.ends_with(' ') {
indent.push(' ');
}
} else {
indent.push(character);
}
}
indent
}
#[cfg(test)]
mod tests {
use super::*;
const RUN: Option<Run> = Some(Run { segment_break: false });
const BREAK: Option<Run> = Some(Run { segment_break: true });
#[test]
fn a_text_of_unicode_white_space_is_blank() {
for blank in ["", " \t\r\n", "\u{a0}", " \u{a0}\n", "\u{2003}\u{3000}"] {
assert!(is_blank(blank), "{blank:?}");
}
for text in ["a", " a ", "\u{a0}a", "\u{200b}", "\u{feff}", "\u{c}", " \u{c}\n"] {
assert!(!is_blank(text), "{text:?}");
}
}
#[test]
fn a_form_feed_is_a_character_at_the_edge_of_a_text_and_goes_outside_the_marks() {
assert_eq!(edges("\u{c}one"), ("", ""));
assert_eq!(edges(" \u{c}one"), (" ", ""));
assert_eq!(edges("one\u{c} "), ("", " "));
assert_eq!(visible("\u{c}one\u{c}"), "\u{c}one\u{c}");
assert_eq!(visible(" \u{c}one\u{c}\n"), "\u{c}one\u{c}");
assert_eq!(mark_edges("\u{c}one "), ("\u{c}", " "));
assert_eq!(mark_edges("one"), ("", ""));
assert_eq!(mark_edges(" \u{c}"), (" \u{c}", ""));
assert_eq!(owed_part("x", " \u{c}"), " \u{c}");
assert_eq!(owed_part("x ", " \u{c}"), "\u{c}");
assert_eq!(owed_part("x ", " "), "");
}
#[test]
fn an_edge_of_a_text_is_one_space_for_white_space_of_any_kind() {
assert_eq!(edges("one"), ("", ""));
assert_eq!(edges(" one "), (" ", " "));
assert_eq!(edges("\u{a0}one\u{a0}"), (" ", " "));
assert_eq!(edges("\none\t"), (" ", " "));
assert_eq!(edges("one\n"), ("", ""));
assert_eq!(edges("one\n\n"), ("", "\n\n"));
assert_eq!(edges("one\r\n\r\n"), ("", "\n\n"));
assert_eq!(edges("one\u{c}"), ("", ""));
}
#[test]
fn the_visible_part_of_a_text_collapses_a_no_break_space_with_the_spaces_around_it() {
assert_eq!(visible(" one \u{a0} two\u{a0}"), "one two");
assert_eq!(visible("one\n two"), "one\ntwo");
assert_eq!(visible("\u{a0}\u{a0}"), "");
}
#[test]
fn a_cell_text_folds_a_line_end_to_a_space_and_keeps_its_edges() {
assert_eq!(cell_text(" one\n\u{a0}two "), " one two ");
assert_eq!(cell_text("quick \u{a0} amet"), "quick amet");
}
#[test]
fn a_reference_to_collapsible_white_space_is_written_as_the_character() {
for (source, decoded) in [
("one ", "one\n"),
("one
two", "one\ntwo"),
("
", "\n"),
("one
", "one\n"),
("one ", "one\r"),
("one two", "one\r\ntwo"),
("one 		two", "one \t\ttwo"),
("a & b ", "a & b\n"),
("é é", "é\né"),
] {
assert_eq!(with_white_space_references_decoded(source), decoded, "{source:?}");
}
}
#[test]
fn a_text_with_no_reference_to_collapsible_white_space_is_not_changed() {
for source in [
"",
"one\n",
"one &",
"one&#10;",
"one ",
"one",
"one​",
"one&NewLines;",
"one
",
] {
assert!(
matches!(with_white_space_references_decoded(source), Cow::Borrowed(same) if same == source),
"{source:?}"
);
}
}
#[test]
fn a_carriage_return_is_a_line_feed() {
assert_eq!(
with_line_feeds(Cow::Borrowed("one\r\ntwo\rthree\n")),
"one\ntwo\nthree\n"
);
assert!(matches!(
with_line_feeds(Cow::Borrowed("one\n")),
Cow::Borrowed("one\n")
));
}
#[test]
fn the_four_characters_are_collapsible() {
for character in [' ', '\t', '\n', '\r'] {
assert!(is_collapsible(character), "{character:?}");
}
}
#[test]
fn a_form_feed_a_no_break_space_and_the_other_unicode_spaces_are_characters() {
for character in [
'\u{c}', '\u{a0}', '\u{2002}', '\u{2003}', '\u{3000}', '\u{200b}', '\u{feff}', 'a',
] {
assert!(!is_collapsible(character), "{character:?}");
}
}
#[test]
fn a_text_of_the_four_characters_is_white_space_only() {
assert_eq!(classify_text(" \t\r"), TextClass::WhiteSpaceOnly(RUN));
assert_eq!(classify_text(" \n "), TextClass::WhiteSpaceOnly(BREAK));
assert_eq!(classify_text(""), TextClass::WhiteSpaceOnly(None));
}
#[test]
fn a_no_break_space_alone_is_text() {
assert_eq!(
classify_text("\u{a0}"),
TextClass::Text {
prefix: None,
core: "\u{a0}",
suffix: None
}
);
assert_eq!(
classify_text(" \u{a0} "),
TextClass::Text {
prefix: RUN,
core: "\u{a0}",
suffix: RUN
}
);
}
#[test]
fn the_edges_of_a_text_are_its_runs() {
assert_eq!(
classify_text("\r\none"),
TextClass::Text {
prefix: BREAK,
core: "one",
suffix: None
}
);
assert_eq!(
classify_text("one\u{c}\n"),
TextClass::Text {
prefix: None,
core: "one\u{c}",
suffix: BREAK
}
);
assert_eq!(
classify_text("one two\t"),
TextClass::Text {
prefix: None,
core: "one two",
suffix: RUN
}
);
}
#[test]
fn a_segment_break_beside_a_zero_width_space_is_removed_on_either_side() {
assert!(segment_break_is_removed(Some('\u{200b}'), Some('G')));
assert!(segment_break_is_removed(Some('s'), Some('\u{200b}')));
assert!(segment_break_is_removed(Some('\u{200b}'), None));
assert!(segment_break_is_removed(None, Some('\u{200b}')));
assert!(!segment_break_is_removed(Some('s'), Some('G')));
assert!(!segment_break_is_removed(None, None));
assert!(!segment_break_is_removed(Some('\u{a0}'), Some('\u{feff}')));
}
#[test]
fn a_run_writes_one_space_unless_its_segment_break_is_removed() {
let run = Run { segment_break: false };
assert!(run.writes_space(Some('\u{200b}'), Some('\u{200b}')));
let with_break = Run { segment_break: true };
assert!(with_break.writes_space(Some('s'), Some('G')));
assert!(!with_break.writes_space(Some('\u{200b}'), Some('G')));
assert!(!with_break.writes_space(Some('s'), Some('\u{200b}')));
}
#[test]
fn a_unicode_space_is_kept_after_a_space_only_after_an_element_with_no_text() {
for (text, starts) in [
("\u{a0}b", true),
(" \u{a0}b", true),
("\u{3000}b", true),
(" b", false),
("\u{c}\nb", false),
("\u{b}b", false),
("b\u{a0}", false),
("", false),
] {
assert_eq!(starts_with_unicode_space(text), starts, "{text:?}");
}
assert!(unicode_space_is_kept("a ", TextPlace::AfterEmptyElement));
assert!(unicode_space_is_kept("a x ", TextPlace::AfterFlowElement));
assert!(!unicode_space_is_kept("a x", TextPlace::AfterFlowElement));
assert!(writes_in_text_flow("span"));
assert!(!writes_in_text_flow("b"));
assert!(!unicode_space_is_kept("a ", TextPlace::AfterBreak));
assert!(!unicode_space_is_kept("a ", TextPlace::ElementStart));
assert!(!unicode_space_is_kept("a ", TextPlace::AfterText));
assert!(!unicode_space_is_kept("a", TextPlace::AfterEmptyElement));
assert!(!unicode_space_is_kept("a\n", TextPlace::AfterEmptyElement));
}
#[test]
fn a_space_is_owed_except_after_a_space_or_at_a_line_start() {
assert!(space_is_owed("one"));
assert!(space_is_owed("**one**"));
assert!(space_is_owed("one\u{a0}"));
assert!(!space_is_owed("one "));
assert!(!space_is_owed("one\n"));
}
}