use std::hash::{Hash, Hasher};
use crate::core::settings::named::{self, NamedEntry};
use crate::lang::mint::ArgLayout;
use crate::model::names::Name;
use crate::stdlib::features::lists::holds_placeholder;
use crate::stdlib::features::numbering::{NumberTemplate, PluralWords, PrefixWords, Within};
use crate::stdlib::features::refs::CAPITAL_VARIANT;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum XnotePlacement {
#[default]
List,
InPlace,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(transform = xnote_kind_schema)]
pub struct XnoteKind {
#[schemars(skip)]
pub name: Name,
pub commands: Vec<String>,
pub words: PrefixWords,
pub label_type: String,
pub numbered: bool,
pub number_format: NumberTemplate,
pub within: Option<Within>,
pub mark: NumberTemplate,
pub placement: XnotePlacement,
pub layout: ArgLayout,
pub title: Option<String>,
pub title_level: u8,
pub backlink: String,
pub latex_command: String,
}
fn xnote_kind_schema(schema: &mut schemars::Schema) {
crate::core::settings::named::require_only(schema, &["words"]);
}
impl XnoteKind {
pub fn numbered(name: impl Into<Name>, words: PrefixWords) -> XnoteKind {
let name = name.into();
XnoteKind {
label_type: name.as_str().to_string(),
name,
commands: Vec::new(),
title: Some(plural_title(&words)),
words,
numbered: true,
number_format: NumberTemplate::formats("#{arabic}"),
within: None,
mark: NumberTemplate::formats("#{arabic}"),
placement: XnotePlacement::List,
layout: ArgLayout::InlineOrBlocks,
title_level: 2,
backlink: String::from("\u{21a9}"),
latex_command: String::from("footnote"),
}
}
pub fn unnumbered(name: impl Into<Name>, words: PrefixWords) -> XnoteKind {
XnoteKind { numbered: false, mark: NumberTemplate::formats(""), ..XnoteKind::numbered(name, words) }
}
pub fn footnote() -> XnoteKind {
let words = PrefixWords::new("Footnote~", "Footnotes~")
.with_variant(CAPITAL_VARIANT, PluralWords::new("Footnote~", "Footnotes~"));
XnoteKind::numbered("footnote", words).commands(["footnote"]).label_type("fn")
}
pub fn commands(mut self, commands: impl IntoIterator<Item = impl Into<String>>) -> XnoteKind {
self.commands = commands.into_iter().map(Into::into).collect();
self
}
pub fn label_type(mut self, label_type: impl Into<String>) -> XnoteKind {
self.label_type = label_type.into();
self
}
pub fn number_format(mut self, number_format: NumberTemplate) -> XnoteKind {
self.number_format = number_format;
self
}
pub fn within(mut self, within: Within) -> XnoteKind {
self.within = Some(within);
self
}
pub fn mark(mut self, mark: NumberTemplate) -> XnoteKind {
self.mark = mark;
self
}
pub fn placement(mut self, placement: XnotePlacement) -> XnoteKind {
self.placement = placement;
self
}
pub fn layout(mut self, layout: ArgLayout) -> XnoteKind {
self.layout = layout;
self
}
pub fn title(mut self, title: impl Into<String>) -> XnoteKind {
self.title = Some(title.into());
self
}
pub fn without_title(mut self) -> XnoteKind {
self.title = None;
self
}
pub fn title_level(mut self, level: u8) -> XnoteKind {
self.title_level = level;
self
}
pub fn backlink(mut self, backlink: impl Into<String>) -> XnoteKind {
self.backlink = backlink.into();
self
}
pub fn latex_command(mut self, command: impl Into<String>) -> XnoteKind {
self.latex_command = command.into();
self
}
pub fn validate(&self) -> Result<(), String> {
let name = self.name.as_str();
if name.is_empty() || !name.chars().all(|ch| ch.is_ascii_alphabetic()) {
return Err(format!(
"the xnote kind name `{name}` must consist of ASCII letters only"
));
}
let label_type = self.label_type.as_str();
if label_type.is_empty() || !label_type.chars().all(|ch| ch.is_ascii_alphabetic()) {
return Err(format!(
"the label type `{label_type}` of the xnote kind `{name}` must consist of ASCII \
letters only"
));
}
let latex_command = self.latex_command.as_str();
if latex_command.is_empty() || !latex_command.chars().all(|ch| ch.is_ascii_alphabetic()) {
return Err(format!(
"the LaTeX command `{latex_command}` of the xnote kind `{name}` must consist of \
ASCII letters only, written without the backslash"
));
}
if !self.numbered && names_number(&self.mark) {
return Err(format!(
"the mark `{}` of the unnumbered xnote kind `{name}` must not write a number, \
since the kind is not numbered",
self.mark.text()
));
}
Ok(())
}
pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
let XnoteKind {
name,
commands,
words,
label_type,
numbered,
number_format,
within,
mark,
placement,
layout,
title,
title_level,
backlink,
latex_command,
} = self;
push_text(out, name.as_str());
push_len(out, commands.len());
for command in commands {
push_text(out, command);
}
push_plural(out, &words.base);
push_len(out, words.variants.len());
for (variant, plural) in &words.variants {
push_text(out, variant);
push_plural(out, plural);
}
push_text(out, label_type);
out.push(u8::from(*numbered));
push_template(out, number_format);
match within {
Some(within) => {
out.push(1);
within.digest_into(out);
}
None => out.push(0),
}
push_template(out, mark);
out.push(match placement {
XnotePlacement::List => 0,
XnotePlacement::InPlace => 1,
});
out.push(match layout {
ArgLayout::Inline => 0,
ArgLayout::Blocks => 1,
ArgLayout::InlineOrBlocks => 2,
});
match title {
Some(title) => {
out.push(1);
push_text(out, title);
}
None => out.push(0),
}
out.push(*title_level);
push_text(out, backlink);
push_text(out, latex_command);
}
}
fn names_number(mark: &NumberTemplate) -> bool {
match mark {
NumberTemplate::Formats(text) => holds_placeholder(text),
NumberTemplate::Initial(text) => text.chars().any(|ch| matches!(ch, 'a' | 'A' | 'i' | 'I' | '1')),
}
}
fn plural_title(words: &PrefixWords) -> String {
let plural = words.variants.get(CAPITAL_VARIANT).unwrap_or(&words.base);
let word = plural.other.trim_end_matches(|ch: char| ch == '~' || ch.is_whitespace());
let mut chars = word.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct XnotesConfig {
#[serde(deserialize_with = "crate::core::settings::named::deserialize")]
#[schemars(
transform = crate::core::settings::named::map_schema,
with = "std::collections::BTreeMap<String, XnoteKind>"
)]
pub kinds: Vec<XnoteKind>,
}
impl Default for XnotesConfig {
fn default() -> XnotesConfig {
XnotesConfig::new()
}
}
impl XnotesConfig {
pub fn new() -> XnotesConfig {
XnotesConfig { kinds: vec![XnoteKind::footnote()] }
}
pub fn empty() -> XnotesConfig {
XnotesConfig { kinds: Vec::new() }
}
pub fn kind(mut self, kind: XnoteKind) -> XnotesConfig {
self.kinds.push(kind);
self
}
pub fn kind_named(&self, name: &str) -> Option<&XnoteKind> {
self.kinds.iter().find(|kind| kind.name.as_str() == name)
}
pub fn validate(&self) -> Result<(), String> {
for (at, kind) in self.kinds.iter().enumerate() {
kind.validate()?;
for earlier in &self.kinds[..at] {
if earlier.name == kind.name {
return Err(format!(
"two xnote kinds have the name `{}`; each xnote kind needs a name of its \
own",
kind.name
));
}
if let Some(command) = kind.commands.iter().find(|c| earlier.commands.contains(c)) {
return Err(format!(
"the xnote kinds `{}` and `{}` are both written `\\{command}`; each xnote \
kind needs commands of its own",
earlier.name, kind.name
));
}
if earlier.label_type == kind.label_type {
return Err(format!(
"the xnote kinds `{}` and `{}` both accept the label type `{}`; each \
xnote kind needs a label type of its own",
earlier.name, kind.name, kind.label_type
));
}
}
}
Ok(())
}
pub fn digest_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
push_len(&mut out, self.kinds.len());
for kind in &self.kinds {
kind.digest_into(&mut out);
}
out
}
}
impl Hash for XnotesConfig {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.digest_bytes());
}
}
fn push_len(out: &mut Vec<u8>, len: usize) {
out.extend_from_slice(&(len as u64).to_le_bytes());
}
fn push_text(out: &mut Vec<u8>, text: &str) {
push_len(out, text.len());
out.extend_from_slice(text.as_bytes());
}
fn push_plural(out: &mut Vec<u8>, plural: &PluralWords) {
push_text(out, &plural.one);
push_text(out, &plural.other);
}
fn push_template(out: &mut Vec<u8>, template: &NumberTemplate) {
out.push(match template {
NumberTemplate::Formats(_) => 0,
NumberTemplate::Initial(_) => 1,
});
push_text(out, template.text());
}
impl NamedEntry for XnoteKind {
fn read_entry(name: &str, data: serde_json::Value) -> Result<XnoteKind, String> {
let words: PrefixWords = named::required(name, &data, "words")?;
named::read_over(&XnoteKind::numbered(name, words), "name", name, data)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_kind_is_the_footnote() {
let config = XnotesConfig::new();
assert_eq!(config.kinds.len(), 1);
let kind = &config.kinds[0];
assert_eq!(kind.name.as_str(), "footnote");
assert_eq!(kind.commands, ["footnote"]);
assert_eq!(kind.words.base, PluralWords::new("Footnote~", "Footnotes~"));
assert_eq!(kind.words.variants.get(CAPITAL_VARIANT), Some(&kind.words.base));
assert_eq!(kind.label_type, "fn");
assert!(kind.numbered);
assert_eq!(kind.number_format, NumberTemplate::formats("#{arabic}"));
assert_eq!(kind.mark, NumberTemplate::formats("#{arabic}"));
assert!(kind.within.is_none());
assert_eq!(kind.placement, XnotePlacement::List);
assert_eq!(kind.layout, ArgLayout::InlineOrBlocks);
assert_eq!(kind.title.as_deref(), Some("Footnotes"));
assert_eq!(kind.title_level, 2);
assert_eq!(kind.backlink, "\u{21a9}");
assert_eq!(kind.latex_command, "footnote");
assert_eq!(config.validate(), Ok(()));
}
#[test]
fn the_default_title_is_the_plural_word_capitalized() {
let kind = XnoteKind::numbered("endnote", PrefixWords::new("endnote~", "endnotes~"));
assert_eq!(kind.title.as_deref(), Some("Endnotes"));
let words = PrefixWords::new("n.~", "nn.~").with_variant(CAPITAL_VARIANT, PluralWords::new("Note~", "Notes~"));
assert_eq!(XnoteKind::unnumbered("aside", words).title.as_deref(), Some("Notes"));
assert_eq!(XnoteKind::numbered("x", PrefixWords::default()).title.as_deref(), Some(""));
}
#[test]
fn the_refusals_refuse_what_is_wrong() {
let refused = |config: XnotesConfig| config.validate().is_err();
let words = || PrefixWords::new("Note~", "Notes~");
assert!(refused(XnotesConfig::empty().kind(XnoteKind::numbered("side-note", words()))));
assert!(refused(XnotesConfig::empty().kind(XnoteKind::numbered("", words()))));
for label_type in ["", "fn:x", "side-note", "n1"] {
let kind = XnoteKind::numbered("other", words()).label_type(label_type);
assert!(refused(XnotesConfig::empty().kind(kind)), "{label_type:?}");
}
assert!(refused(XnotesConfig::new().kind(XnoteKind::footnote().label_type("x"))));
assert!(refused(
XnotesConfig::new().kind(XnoteKind::numbered("other", words()).commands(["footnote"]))
));
assert!(refused(XnotesConfig::new().kind(XnoteKind::numbered("other", words()).label_type("fn"))));
let level_zero = XnoteKind::numbered("other", words()).title_level(0);
assert_eq!(level_zero.validate(), Ok(()), "a title level of 0 is accepted");
let marked = XnoteKind::unnumbered("aside", words()).mark(NumberTemplate::formats("(#{alph})"));
assert!(refused(XnotesConfig::empty().kind(marked)));
let marked = XnoteKind::unnumbered("aside", words()).mark(NumberTemplate::initial("(a)"));
assert!(refused(XnotesConfig::empty().kind(marked)));
}
#[test]
fn what_is_accepted() {
let words = || PrefixWords::new("Note~", "Notes~");
let config = XnotesConfig::new()
.kind(XnoteKind::numbered("addendum", words()).label_type("add"))
.kind(XnoteKind::unnumbered("aside", words()).mark(NumberTemplate::formats("\u{2020}")))
.kind(XnoteKind::unnumbered("star", words()).mark(NumberTemplate::formats("\\#")))
.kind(
XnoteKind::unnumbered("plain", words())
.label_type("pl")
.number_format(NumberTemplate::formats("#{nosuchformat}")),
);
let config = config.kind(XnoteKind::numbered("other", words()));
assert_eq!(config.validate(), Ok(()), "{config:?}");
}
#[test]
fn the_digest_bytes_change_with_every_field() {
let base = XnotesConfig::new();
let kind = XnoteKind::footnote;
let one = |kind: XnoteKind| XnotesConfig { kinds: vec![kind] };
let changed = [
one(kind().commands(["fn", "footnote"])),
one(XnoteKind { words: PrefixWords::new("Note~", "Notes~"), ..kind() }),
one(kind().label_type("note")),
one(XnoteKind { numbered: false, ..kind() }),
one(kind().number_format(NumberTemplate::formats("#{roman}"))),
one(kind().number_format(NumberTemplate::initial("#{arabic}"))),
one(kind().within(Within::parent("flm.headings.section"))),
one(kind().mark(NumberTemplate::formats("[#{arabic}]"))),
one(kind().placement(XnotePlacement::InPlace)),
one(kind().layout(ArgLayout::Blocks)),
one(kind().title("Notes")),
one(kind().without_title()),
one(kind().title_level(3)),
one(kind().backlink("back")),
one(kind().latex_command("endnote")),
XnotesConfig::empty(),
base.clone().kind(XnoteKind::numbered("endnote", PrefixWords::new("E~", "Es~"))),
];
for other in &changed {
assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
}
assert_eq!(XnotesConfig::new().digest_bytes(), base.digest_bytes());
}
}