use crate::options::CodeBlockStyle;
pub enum CodeScan<'a> {
Fenced(FenceScan),
Indented(IndentedScan<'a>),
}
pub struct IndentedScan<'a> {
output: &'a str,
quotes: QuoteLines,
lines: Option<(usize, Vec<bool>)>,
next: (usize, usize),
first: (usize, usize),
}
impl IndentedScan<'_> {
fn advance(&mut self) -> (usize, bool) {
let (index, start) = self.next;
let rest = self.output.get(start..).unwrap_or_default();
let length = rest.find('\n').unwrap_or(rest.len());
self.next = (index + 1, start + length + 1);
let is_kept_quote_line = self.quotes == QuoteLines::Kept && rest.starts_with('>');
if is_kept_quote_line {
self.first = self.next;
self.lines = None;
}
(index, is_kept_quote_line)
}
fn is_code(&mut self) -> bool {
let start = self.next.1;
let (index, is_kept_quote_line) = self.advance();
if is_kept_quote_line {
return true;
}
let (output, quotes, first) = (self.output, self.quotes, self.first);
let (first_index, lines) = self.lines.get_or_insert_with(|| {
let rest = output.get(first.1..).unwrap_or_default();
let end = match quotes {
QuoteLines::Read => rest.len(),
QuoteLines::Kept => output
.get(start..)
.and_then(|after| after.find("\n>"))
.map_or(rest.len(), |length| start - first.1 + length),
};
(first.0, indented_code_lines(&rest[..end], quotes))
});
lines.get(index - *first_index).copied().unwrap_or(false)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum QuoteLines {
Read,
Kept,
}
impl<'a> CodeScan<'a> {
pub const fn new(style: CodeBlockStyle, output: &'a str) -> Self {
Self::with_quote_lines(style, output, QuoteLines::Read)
}
pub const fn of_quote_content(style: CodeBlockStyle, content: &'a str) -> Self {
Self::with_quote_lines(style, content, QuoteLines::Kept)
}
const fn with_quote_lines(style: CodeBlockStyle, output: &'a str, quotes: QuoteLines) -> Self {
match style {
CodeBlockStyle::Indented => Self::Indented(IndentedScan {
output,
quotes,
lines: None,
next: (0, 0),
first: (0, 0),
}),
CodeBlockStyle::Backticks => Self::Fenced(FenceScan {
fence: b'`',
quotes,
open: None,
}),
CodeBlockStyle::Tildes => Self::Fenced(FenceScan {
fence: b'~',
quotes,
open: None,
}),
}
}
pub fn is_code(&mut self, line: &str) -> bool {
match self {
Self::Fenced(fences) => fences.is_code(line),
Self::Indented(scan) => scan.is_code(),
}
}
pub fn pass(&mut self, line: &str) {
match self {
Self::Fenced(fences) => {
fences.is_code(line);
}
Self::Indented(scan) => {
scan.advance();
}
}
}
}
pub struct FenceScan {
fence: u8,
quotes: QuoteLines,
open: Option<(u8, usize)>,
}
impl FenceScan {
fn is_code(&mut self, line: &str) -> bool {
use crate::converter::utility::escaping::code_fence;
let Some((marker, length)) = self.open else {
if self.quotes == QuoteLines::Kept && line.starts_with('>') {
return false;
}
self.open = code_fence(after_container_markers(line)).filter(|(marker, _)| *marker == self.fence);
return false;
};
let rest = line.trim_start_matches([' ', '\t', '>']);
let closes = code_fence(rest).is_some_and(|(fence, run)| fence == marker && run >= length)
&& rest.trim_start_matches(char::from(marker)).trim().is_empty();
if closes {
self.open = None;
}
!closes
}
}
fn after_container_markers(mut line: &str) -> &str {
loop {
line = line.trim_start_matches([' ', '\t', '>']);
let Some(marker) = list_marker_length(line) else {
return line;
};
line = &line[marker..];
}
}
fn list_marker_length(rest: &str) -> Option<usize> {
let bytes = rest.as_bytes();
let digits = bytes.iter().take_while(|byte| byte.is_ascii_digit()).count();
let length = match bytes.first()? {
b'-' | b'*' | b'+' => 1,
_ if (1..=9).contains(&digits) && matches!(bytes.get(digits), Some(b'.' | b')')) => digits + 1,
_ => return None,
};
matches!(bytes.get(length), None | Some(b' ' | b'\t')).then_some(length)
}
enum Container {
Quote,
Item(usize),
}
struct LineCursor<'a> {
rest: &'a str,
column: usize,
spare: usize,
}
impl LineCursor<'_> {
fn indent(&self) -> usize {
let mut column = self.column;
for byte in self.rest.bytes() {
match byte {
b' ' => column += 1,
b'\t' => column += 4 - column % 4,
_ => break,
}
}
self.spare + column - self.column
}
fn skip(&mut self, mut columns: usize) {
let used = columns.min(self.spare);
self.spare -= used;
columns -= used;
while columns > 0 {
let width = match self.rest.as_bytes().first() {
Some(b' ') => 1,
Some(b'\t') => 4 - self.column % 4,
_ => return,
};
self.advance(1);
self.column += width - 1;
if width > columns {
self.spare = width - columns;
return;
}
columns -= width;
}
}
fn advance(&mut self, bytes: usize) {
self.rest = &self.rest[bytes..];
self.column += bytes;
}
fn skip_quote_marker(&mut self) {
self.advance(1);
if self.indent() > 0 {
self.skip(1);
}
}
fn is_blank(&self) -> bool {
self.rest.trim_matches([' ', '\t']).is_empty()
}
fn enter(&mut self, containers: &[Container]) -> usize {
let mut depth = 0;
for container in containers {
match *container {
Container::Quote => {
let indent = self.indent();
if indent > 3 || !self.rest.trim_start_matches([' ', '\t']).starts_with('>') {
break;
}
self.skip(indent);
self.skip_quote_marker();
}
Container::Item(content) => {
if self.indent() >= content {
self.skip(content);
} else if !self.is_blank() {
break;
}
}
}
depth += 1;
}
depth
}
}
fn indented_code_lines(output: &str, quotes: QuoteLines) -> Vec<bool> {
let mut code = Vec::new();
let mut containers: Vec<Container> = Vec::new();
let mut in_paragraph = false;
let mut last_code: Option<usize> = None;
for (index, line) in output.split('\n').enumerate() {
code.push(false);
let mut cursor = LineCursor {
rest: line,
column: 0,
spare: 0,
};
let depth = cursor.enter(&containers);
if cursor.is_blank() {
in_paragraph = false;
continue;
}
if depth < containers.len() {
containers.truncate(depth);
last_code = None;
}
let mut is_kept_quote_line = false;
let is_code = loop {
let indent = cursor.indent();
if indent >= 4 {
break !in_paragraph;
}
cursor.skip(indent);
if cursor.rest.starts_with('>') {
if quotes == QuoteLines::Kept {
is_kept_quote_line = true;
in_paragraph = false;
break false;
}
cursor.skip_quote_marker();
containers.push(Container::Quote);
} else if let Some(marker) = list_marker_length(cursor.rest) {
cursor.advance(marker);
let padding = match cursor.indent() {
spaces @ 1..=4 if !cursor.is_blank() => spaces,
_ => 1,
};
cursor.skip(padding);
containers.push(Container::Item(indent + marker + padding));
} else {
in_paragraph = true;
break false;
}
in_paragraph = false;
last_code = None;
if cursor.is_blank() {
break false;
}
};
if is_code {
code[index] = true;
if let Some(last) = last_code {
code[last + 1..index].fill(true);
}
last_code = Some(index);
} else {
last_code = None;
code[index] = is_kept_quote_line;
}
}
code
}
pub fn quote_content_range(content: &str, style: CodeBlockStyle) -> std::ops::Range<usize> {
let start = quote_content_start(content, style);
start..quote_content_end(content, style, QuoteLines::Read).max(start)
}
pub fn trimmed_quotes_content_range(content: &str, style: CodeBlockStyle) -> std::ops::Range<usize> {
let start = quote_content_start(content, style);
start..quote_content_end(content, style, QuoteLines::Kept).max(start)
}
pub fn quote_content_start(content: &str, style: CodeBlockStyle) -> usize {
let start = content.len() - content.trim_start().len();
if style != CodeBlockStyle::Indented {
return start;
}
let first_line = content[..start].rfind('\n').map_or(0, |index| index + 1);
let line_end = content[start..].find('\n').map_or(content.len(), |index| start + index);
if indented_code_lines(&content[first_line..line_end], QuoteLines::Read) == [true] {
first_line
} else {
start
}
}
fn quote_content_end(content: &str, style: CodeBlockStyle, quotes: QuoteLines) -> usize {
let end = content.trim_end().len();
if style != CodeBlockStyle::Indented || end == 0 {
return end;
}
let last_line = content[end..].find('\n').map_or(content.len(), |index| end + index);
if last_line == end {
return end;
}
let start = content.len() - content.trim_start().len();
let mut first_line = content[..start].rfind('\n').map_or(0, |index| index + 1);
if quotes == QuoteLines::Kept {
let line_start = content[..end].rfind('\n').map_or(0, |index| index + 1);
let line = &content[line_start..last_line];
if indented_code_lines(line, QuoteLines::Read) != [true] {
return end;
}
if let Some(quote) = content[..line_start].rfind("\n>") {
first_line = content[quote + 1..line_start]
.find('\n')
.map_or(line_start, |length| quote + length + 2);
}
}
if indented_code_lines(&content[first_line..last_line], quotes).last() == Some(&true) {
last_line
} else {
end
}
}
#[cfg(test)]
mod tests {
use super::*;
fn code(markdown: &str) -> String {
indented_code_lines(markdown, QuoteLines::Read)
.into_iter()
.map(|is_code| if is_code { '1' } else { '0' })
.collect()
}
#[test]
fn should_measure_indented_code_from_the_content_column_of_a_list_item() {
let cases = [
("7 x\n\n c", "001"),
("- a\n\n b", "000"),
("- \n b", "01"),
(" - a\n\n b", "000"),
("- a\n\nb\n\n c", "00001"),
];
for (markdown, expected) in cases {
assert_eq!(code(markdown), expected, "{markdown:?}");
}
}
#[test]
fn should_preserve_only_blank_lines_inside_indented_code() {
for (markdown, expected) in [
("- t\n\n<!-- -->\n\n a\n\n\n b\n", "000011110"),
("- t\n\n a\n\n\n b\n", "0000000"),
("- t\n\n a\n\n\n b\n", "0011110"),
("> a\n>\n>\n> b\n", "11110"),
("paragraph\n continuation", "00"),
] {
assert_eq!(code(markdown), expected, "{markdown:?}");
}
}
#[test]
fn should_measure_indented_code_after_the_marker_of_a_block_quote() {
let cases = [
("> a", "0"),
("> a\n>\n > b", "111"),
(">\t foo", "0"),
(">\t\tfoo", "1"),
];
for (markdown, expected) in cases {
assert_eq!(code(markdown), expected, "{markdown:?}");
}
}
#[test]
fn should_count_a_tab_to_the_next_multiple_of_four_columns() {
assert_eq!(code("1234. a\n\n \tb"), "001");
let mut cursor = LineCursor {
rest: " \t\tx",
column: 0,
spare: 0,
};
assert_eq!(cursor.indent(), 8);
cursor.skip(2);
cursor.skip(1);
assert_eq!(cursor.indent(), 5);
cursor.skip(1);
assert_eq!(cursor.indent(), 4);
}
#[test]
fn should_keep_the_white_space_of_code_at_the_edges_of_the_content_of_a_container() {
let indented = CodeBlockStyle::Indented;
assert_eq!(quote_content_range("\n a \n", indented), 1..8);
assert_eq!(quote_content_range("\n a \n", indented), 3..4);
assert_eq!(quote_content_range(" \n", indented), 3..3);
assert_eq!(quote_content_range(" a\n", CodeBlockStyle::Backticks), 4..5);
}
fn range_from_every_line(content: &str) -> std::ops::Range<usize> {
let start = content.len() - content.trim_start().len();
let end = content.trim_end().len();
if start >= end {
return start..end.max(start);
}
let first_line = content[..start].rfind('\n').map_or(0, |index| index + 1);
let last_line = content[end..].find('\n').map_or(content.len(), |index| end + index);
let code = indented_code_lines(&content[first_line..last_line], QuoteLines::Read);
let start = if code.first() == Some(&true) { first_line } else { start };
let end = if code.last() == Some(&true) { last_line } else { end };
start..end
}
#[test]
fn should_trim_the_content_of_a_container_as_a_read_of_every_line_does() {
let cases = [
("", 0..0),
(" \n\t\n", 4..4),
("\n a\n\n b \n\n", 1..15),
("\n a\n\nb \n\n", 1..9),
(" a\n\n b \n", 2..12),
(" a\n b \n", 2..9),
("- a\n\n b \t\n", 0..14),
("- a\n\n b \n", 0..10),
("> a \n> b\n", 0..13),
("> b\n>\n> a \n", 0..15),
("\n\n\ta\n\tb\t\n", 2..8),
(" a ", 0..7),
("a ", 0..1),
];
for (content, expected) in cases {
let range = quote_content_range(content, CodeBlockStyle::Indented);
assert_eq!(range, expected, "{content:?}");
assert_eq!(
trimmed_quotes_content_range(content, CodeBlockStyle::Indented),
expected,
"{content:?}"
);
assert_eq!(range, range_from_every_line(content), "{content:?}");
assert_eq!(
quote_content_start(content, CodeBlockStyle::Indented),
range.start,
"{content:?}"
);
}
assert_eq!(quote_content_range("\n a \n", CodeBlockStyle::Tildes), 5..6);
assert_eq!(quote_content_start("\n a \n", CodeBlockStyle::Backticks), 5);
}
#[test]
fn should_not_read_the_lines_of_a_quote_that_trimmed_its_own_content() {
let kept = |markdown: &str| -> String {
indented_code_lines(markdown, QuoteLines::Kept)
.into_iter()
.map(|is_kept| if is_kept { '1' } else { '0' })
.collect()
};
assert_eq!(kept("> > a\n\n b\n \n c\n> d"), "101111");
assert_eq!(kept("- a\n > b\n\n c\n\n d"), "010001");
assert_eq!(kept("> a\n \n> b"), "101");
assert_eq!(code("> a\n \n> b"), "111");
let indented = CodeBlockStyle::Indented;
assert_eq!(trimmed_quotes_content_range("a\n\n> > b \n\n", indented), 0..14);
assert_eq!(trimmed_quotes_content_range("a\n> b \n", indented), 0..5);
assert_eq!(trimmed_quotes_content_range("> a\n\n b \n", indented), 0..12);
assert_eq!(trimmed_quotes_content_range("- a\n > b\n\n c \n", indented), 0..16);
assert_eq!(trimmed_quotes_content_range("- a\n> b\n\n c \n", indented), 0..16);
let content = " a\n \n b\n> c\n\n d\n \n e\n> f\n ";
assert_eq!(kept(content), "1111011110");
let mut scan = CodeScan::of_quote_content(indented, content);
let mut answers = String::new();
for line in content.split('\n') {
if line.trim().is_empty() {
answers.push(if scan.is_code(line) { '1' } else { '0' });
} else {
scan.pass(line);
answers.push('-');
}
}
assert_eq!(answers, "-1--0-1--0");
let mut scan = CodeScan::of_quote_content(indented, content);
let every: String = content
.split('\n')
.map(|line| if scan.is_code(line) { '1' } else { '0' })
.collect();
assert_eq!(every, kept(content));
}
#[test]
fn should_answer_for_the_next_line_after_lines_that_were_passed() {
let markdown = "a\n\n b\n \n c\nd";
let mut scan = CodeScan::new(CodeBlockStyle::Indented, markdown);
let mut answers = String::new();
for (index, line) in markdown.split('\n').enumerate() {
if index < 2 || index == 4 {
scan.pass(line);
answers.push('-');
} else {
answers.push(if scan.is_code(line) { '1' } else { '0' });
}
}
assert_eq!(answers, "--11-0");
assert!(!scan.is_code(""));
let fenced = "```\n \n```\n ";
let mut scan = CodeScan::new(CodeBlockStyle::Backticks, fenced);
let mut answers = String::new();
for (index, line) in fenced.split('\n').enumerate() {
if index % 2 == 0 {
scan.pass(line);
answers.push('-');
} else {
answers.push(if scan.is_code(line) { '1' } else { '0' });
}
}
assert_eq!(answers, "-1-0");
}
#[test]
fn should_not_read_the_fences_of_a_quote_that_closed_its_own_code_blocks() {
let answers = |mut scan: CodeScan<'_>, markdown: &str| -> String {
markdown
.split('\n')
.map(|line| if scan.is_code(line) { '1' } else { '0' })
.collect()
};
for (style, fence) in [(CodeBlockStyle::Backticks, "```"), (CodeBlockStyle::Tildes, "~~~")] {
let content = format!("> {fence}\n> a\n> {fence}\n \n{fence}\n \n> b\n{fence}\n ");
assert_eq!(
answers(CodeScan::of_quote_content(style, &content), &content),
"000001100"
);
assert_eq!(answers(CodeScan::new(style, &content), &content), "010001100");
let item = format!("- a\n > {fence}\n > \n > {fence}\n ");
assert_eq!(answers(CodeScan::of_quote_content(style, &item), &item), "00100");
}
}
}