use std::ops::RangeInclusive;
use super::field_code;
use super::{Block, Content, ParagraphId, all_paragraphs};
use crate::params::BODY_TEXT_OUTLINE_LEVEL;
const ALL_LEVELS: RangeInclusive<u8> = 0..=BODY_TEXT_OUTLINE_LEVEL - 1;
const ANY_ENTRY_FIELDS: EntryFields = EntryFields {
identifier: None,
levels: ALL_LEVELS,
};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct TableOfContents {
pub(crate) entries: Vec<StoredEntry>,
pub(crate) switches: Switches,
pub(crate) entry_fields: Vec<EntryField>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StoredEntry {
pub(crate) style: Option<String>,
pub(crate) bookmark: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Switches {
pub(crate) outline_levels: Option<RangeInclusive<u8>>,
pub(crate) styles: Vec<(String, u8)>,
pub(crate) entry_fields: Option<EntryFields>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EntryFields {
pub(crate) identifier: Option<String>,
pub(crate) levels: RangeInclusive<u8>,
}
impl EntryFields {
pub(crate) fn lists(&self, field: &EntryField) -> bool {
let identifier = field.identifier.as_deref().unwrap_or("C");
let wanted = self.identifier.as_deref().unwrap_or("C");
identifier.eq_ignore_ascii_case(wanted) && self.levels.contains(&field.level)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EntryField {
pub(crate) paragraph: ParagraphId,
pub(crate) level: u8,
pub(crate) identifier: Option<String>,
}
#[derive(Default)]
struct Open {
code: String,
result: bool,
}
#[derive(Default)]
struct Reading {
open: Vec<Open>,
found: Option<TableOfContents>,
toc_at: Option<usize>,
entry_fields: Vec<EntryField>,
}
impl Reading {
fn read(&mut self, content: &Content, paragraph: ParagraphId) -> Option<String> {
match content {
Content::FieldBegin => self.open.push(Open::default()),
Content::FieldCode(text) => {
if let Some(field) = self.open.last_mut().filter(|field| !field.result) {
field.code.push_str(text);
}
}
Content::FieldSeparate => {
if self.open.last().is_some_and(|field| !field.result) {
let linked = self.code_ends(paragraph, true);
if let Some(field) = self.open.last_mut() {
field.result = true;
}
return linked;
}
}
Content::FieldEnd => {
let without_result = self.open.last().is_some_and(|field| !field.result);
let linked = if without_result {
self.code_ends(paragraph, false)
} else {
None
};
self.open.pop();
if self.toc_at == Some(self.open.len()) {
self.toc_at = None;
}
return linked;
}
_ => {}
}
None
}
fn code_ends(&mut self, paragraph: ParagraphId, separated: bool) -> Option<String> {
let at = self.open.len().checked_sub(1)?;
let code = self.open.get(at).map(|field| field.code.clone())?;
let kind = field_code::kind(&code)?;
if kind.eq_ignore_ascii_case("TOC") && self.found.is_none() && !lists_figures(&code) {
self.found = Some(TableOfContents {
switches: switches(&code),
..TableOfContents::default()
});
self.toc_at = separated.then_some(at);
None
} else if kind.eq_ignore_ascii_case("TC") {
self.entry_fields.push(entry_field(&code, paragraph));
None
} else if self.toc_at.is_some_and(|toc| toc < at) {
linked_bookmark(&code)
} else {
None
}
}
}
fn lists_figures(code: &str) -> bool {
field_code::words_after_kind(code).any(|word| word == "\\c" || word == "\\a")
}
fn switches(code: &str) -> Switches {
let mut out = Switches::default();
let mut own_levels = false;
let mut fields: Option<EntryFields> = None;
let mut rest = field_code::after_kind(code);
loop {
let word = field_code::quoted_argument(rest);
if word.text.is_empty() && word.rest.trim().is_empty() {
break;
}
rest = word.rest;
let next = field_code::quoted_argument(rest);
let argument = (!next.text.is_empty() && !next.text.starts_with('\\')).then_some(next);
let mut take = || {
argument.map(|argument| {
rest = argument.rest;
argument.text
})
};
match word.text {
"\\o" => out.outline_levels = Some(take().and_then(levels).unwrap_or(ALL_LEVELS)),
"\\u" => own_levels = true,
"\\t" => out.styles = take().map_or_default(style_levels),
"\\f" => {
let identifier = take().map(str::to_owned);
fields.get_or_insert(ANY_ENTRY_FIELDS).identifier = identifier;
}
"\\l" => {
let range = take().and_then(levels).unwrap_or(ALL_LEVELS);
fields.get_or_insert(ANY_ENTRY_FIELDS).levels = range;
}
_ => {}
}
}
if own_levels {
out.outline_levels.get_or_insert(ALL_LEVELS);
}
out.entry_fields = fields;
if out.outline_levels.is_none() && out.styles.is_empty() && out.entry_fields.is_none() {
out.outline_levels = Some(ALL_LEVELS);
}
out
}
fn levels(range: &str) -> Option<RangeInclusive<u8>> {
let (first, last) = range.split_once('-').unwrap_or((range, range));
let level = |text: &str| {
text.trim()
.parse::<u8>()
.ok()
.filter(|level| (1..=BODY_TEXT_OUTLINE_LEVEL).contains(level))
};
let (first, last) = (level(first)?, level(last)?);
(first <= last).then(|| first - 1..=last - 1)
}
fn style_levels(argument: &str) -> Vec<(String, u8)> {
let mut parts = argument.split([',', ';']).map(str::trim);
let mut out = Vec::new();
while let Some(name) = parts.next() {
if name.is_empty() {
continue;
}
let level = parts
.next()
.and_then(levels)
.map_or(0, |range| *range.start());
out.push((name.to_owned(), level));
}
out
}
fn entry_field(code: &str, paragraph: ParagraphId) -> EntryField {
let mut field = EntryField {
paragraph,
level: 0,
identifier: None,
};
let mut words = field_code::words_after_kind(code);
while let Some(word) = words.next() {
if word == "\\l" {
if let Some(range) = words
.next()
.and_then(|level| levels(field_code::word_argument(level)))
{
field.level = *range.start();
}
} else if word == "\\f" {
field.identifier = words
.next()
.map(field_code::word_argument)
.filter(|identifier| !identifier.starts_with('\\'))
.map(str::to_owned);
}
}
field
}
fn linked_bookmark(code: &str) -> Option<String> {
let kind = field_code::kind(code)?;
let mut words = field_code::words_after_kind(code);
let name = if kind.eq_ignore_ascii_case("PAGEREF") {
words.next()
} else if kind.eq_ignore_ascii_case("HYPERLINK") {
words.skip_while(|word| *word != "\\l").nth(1)
} else {
None
}?;
let name = field_code::word_argument(name);
(!name.is_empty() && !name.starts_with('\\')).then(|| name.to_owned())
}
pub(crate) fn read(blocks: &[Block]) -> Option<TableOfContents> {
let mut reading = Reading::default();
let mut entries = Vec::new();
for paragraph in all_paragraphs(blocks) {
let mut linked = None;
let mut in_result = reading.toc_at.is_some();
for content in paragraph.runs.iter().flat_map(|run| &run.content) {
let bookmark = reading.read(content, paragraph.id);
if linked.is_none() {
linked = bookmark;
}
in_result |= reading.toc_at.is_some();
}
if let Some(bookmark) = linked.filter(|_| in_result) {
entries.push(StoredEntry {
style: paragraph.props.style.clone(),
bookmark,
});
}
}
let mut found = reading.found?;
found.entries = entries;
found.entry_fields = reading.entry_fields;
Some(found)
}
#[cfg(test)]
mod tests;