const MIN_CONTENTS_HEADINGS: usize = 3;
const MAX_BLOCK_INDENT: usize = 3;
const MIN_FENCE_LENGTH: usize = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HeadingLevel {
One,
Two,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Heading {
pub(super) level: HeadingLevel,
pub(super) title: String,
pub(super) section: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct HelpSections {
sections: Vec<String>,
headings: Vec<Heading>,
}
impl HelpSections {
pub(super) fn parse(markdown: &str) -> Self {
markdown
.split_inclusive('\n')
.map(|line| (line, fence(line), atx_heading(line)))
.fold(Splitter::default(), |splitter, (line, fence, heading)| {
splitter.push(line, fence, heading)
})
.finish()
}
pub(super) fn sections(&self) -> &[String] {
&self.sections
}
pub(super) fn headings(&self) -> &[Heading] {
&self.headings
}
pub(super) fn shows_contents(&self) -> bool {
self.headings.len() >= MIN_CONTENTS_HEADINGS
}
pub(super) fn heading_for(&self, section: usize) -> Option<&Heading> {
self.headings
.iter()
.find(|heading| heading.section == section)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Fence {
marker: char,
length: usize,
bare: bool,
}
struct RawHeading<'a> {
level: HeadingLevel,
text: &'a str,
section: usize,
}
#[derive(Default)]
struct Splitter<'a> {
sections: Vec<String>,
current: String,
headings: Vec<RawHeading<'a>>,
open_fence: Option<Fence>,
}
impl<'a> Splitter<'a> {
fn push(
mut self,
line: &str,
fence: Option<Fence>,
heading: Option<(HeadingLevel, &'a str)>,
) -> Self {
match (self.open_fence, fence, heading) {
(Some(open), Some(close), _)
if close.bare && close.marker == open.marker && close.length >= open.length =>
{
self.open_fence = None;
}
(None, Some(open), _) => self.open_fence = Some(open),
(None, None, Some((level, text))) => {
if !self.current.trim().is_empty() {
self.sections.push(std::mem::take(&mut self.current));
}
self.current.clear();
self.headings.push(RawHeading {
level,
text,
section: self.sections.len(),
});
}
_ => {}
}
self.current.push_str(line);
self
}
fn finish(mut self) -> HelpSections {
if !self.current.trim().is_empty() {
self.sections.push(self.current);
}
HelpSections {
sections: self.sections,
headings: self
.headings
.into_iter()
.map(|raw| Heading {
level: raw.level,
title: plain_title(raw.text),
section: raw.section,
})
.collect(),
}
}
}
fn block_text(line: &str) -> Option<&str> {
let line = line.trim_end_matches(['\n', '\r']);
let text = line.trim_start_matches(' ');
(line.len() - text.len() <= MAX_BLOCK_INDENT).then_some(text)
}
fn fence(line: &str) -> Option<Fence> {
let text = block_text(line)?;
let marker = text.chars().next().filter(|c| matches!(c, '`' | '~'))?;
let rest = text.trim_start_matches(marker);
let length = text.len() - rest.len();
(length >= MIN_FENCE_LENGTH).then(|| Fence {
marker,
length,
bare: rest.trim().is_empty(),
})
}
fn atx_heading(line: &str) -> Option<(HeadingLevel, &str)> {
let text = block_text(line)?;
let rest = text.trim_start_matches('#');
if !(rest.is_empty() || rest.starts_with([' ', '\t'])) {
return None;
}
match text.len() - rest.len() {
1 => Some((HeadingLevel::One, rest)),
2 => Some((HeadingLevel::Two, rest)),
_ => None,
}
}
pub(super) fn plain_title(raw: &str) -> String {
let text = without_closing_sequence(raw);
let characters: Vec<char> = text.chars().collect();
let plain = (0..characters.len())
.map(|at| InlineChar {
previous: at.checked_sub(1).map(|before| characters[before]),
current: characters[at],
next: characters.get(at + 1).copied(),
})
.fold(PlainText::default(), PlainText::push);
plain.text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn without_closing_sequence(raw: &str) -> &str {
let trimmed = raw.trim();
let open = trimmed.trim_end_matches('#');
if open.is_empty() {
""
} else if open.len() < trimmed.len() && open.ends_with([' ', '\t']) {
open.trim_end()
} else {
trimmed
}
}
#[derive(Clone, Copy)]
struct InlineChar {
previous: Option<char>,
current: char,
next: Option<char>,
}
impl InlineChar {
fn is_emphasis_underscore(self) -> bool {
let word = |c: Option<char>| c.is_some_and(char::is_alphanumeric);
self.current == '_' && !(word(self.previous) && word(self.next))
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Mode {
#[default]
Text,
Escaped,
Code,
LinkTarget,
Url,
Tag,
}
#[derive(Default)]
struct PlainText {
text: String,
mode: Mode,
}
impl PlainText {
fn push(mut self, inline: InlineChar) -> Self {
let character = inline.current;
let next = inline.next.unwrap_or(' ');
let (keep, mode) = match (self.mode, character) {
(Mode::Escaped, _) => (true, Mode::Text),
(Mode::Code, '`') | (Mode::Url, ')') | (Mode::Tag, '>') => (false, Mode::Text),
(Mode::Code, _) => (true, Mode::Code),
(Mode::LinkTarget, '(') => (false, Mode::Url),
(Mode::LinkTarget, _) => (true, Mode::Text),
(Mode::Url | Mode::Tag, _) => (false, self.mode),
(Mode::Text, '\\') => (false, Mode::Escaped),
(Mode::Text, '`') => (false, Mode::Code),
(Mode::Text, ']') if next == '(' => (false, Mode::LinkTarget),
(Mode::Text, '<') if next.is_ascii_alphabetic() || next == '/' => (false, Mode::Tag),
(Mode::Text, '!') if next == '[' => (false, Mode::Text),
(Mode::Text, '[' | ']' | '*' | '~') => (false, Mode::Text),
(Mode::Text, _) => (!inline.is_emphasis_underscore(), Mode::Text),
};
if keep {
self.text.push(character);
}
self.mode = mode;
self
}
}
#[cfg(test)]
#[path = "contents_tests.rs"]
mod tests;