use std::any::TypeId;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::{Arc, LazyLock};
use comemo::Tracked;
use ecow::{eco_format, EcoString, EcoVec};
use hayagriva::archive::ArchivedStyle;
use hayagriva::io::BibLaTeXError;
use hayagriva::{
citationberg, BibliographyDriver, BibliographyRequest, CitationItem, CitationRequest,
Library, SpecificLocator,
};
use indexmap::IndexMap;
use smallvec::{smallvec, SmallVec};
use typst_syntax::{Span, Spanned};
use typst_utils::{Get, ManuallyHash, NonZeroExt, PicoStr};
use crate::diag::{bail, error, At, FileError, HintedStrResult, SourceResult, StrResult};
use crate::engine::Engine;
use crate::foundations::{
elem, Bytes, CastInfo, Content, Derived, FromValue, IntoValue, Label, NativeElement,
OneOrMultiple, Packed, Reflect, Scope, Show, ShowSet, Smart, StyleChain, Styles,
Synthesize, Value,
};
use crate::introspection::{Introspector, Locatable, Location};
use crate::layout::{
BlockBody, BlockElem, Em, GridCell, GridChild, GridElem, GridItem, HElem, PadElem,
Sides, Sizing, TrackSizings,
};
use crate::loading::{DataSource, Load};
use crate::model::{
CitationForm, CiteGroup, Destination, FootnoteElem, HeadingElem, LinkElem, ParElem,
Url,
};
use crate::routines::{EvalMode, Routines};
use crate::text::{
FontStyle, Lang, LocalName, Region, Smallcaps, SubElem, SuperElem, TextElem,
WeightDelta,
};
use crate::World;
#[elem(Locatable, Synthesize, Show, ShowSet, LocalName)]
pub struct BibliographyElem {
#[required]
#[parse(
let sources = args.expect("sources")?;
Bibliography::load(engine.world, sources)?
)]
pub sources: Derived<OneOrMultiple<DataSource>, Bibliography>,
pub title: Smart<Option<Content>>,
#[default(false)]
pub full: bool,
#[parse(match args.named::<Spanned<CslSource>>("style")? {
Some(source) => Some(CslStyle::load(engine.world, source)?),
None => None,
})]
#[default({
let default = ArchivedStyle::InstituteOfElectricalAndElectronicsEngineers;
Derived::new(CslSource::Named(default), CslStyle::from_archived(default))
})]
pub style: Derived<CslSource, CslStyle>,
#[internal]
#[synthesized]
pub lang: Lang,
#[internal]
#[synthesized]
pub region: Option<Region>,
}
impl BibliographyElem {
pub fn find(introspector: Tracked<Introspector>) -> StrResult<Packed<Self>> {
let query = introspector.query(&Self::elem().select());
let mut iter = query.iter();
let Some(elem) = iter.next() else {
bail!("the document does not contain a bibliography");
};
if iter.next().is_some() {
bail!("multiple bibliographies are not yet supported");
}
Ok(elem.to_packed::<Self>().unwrap().clone())
}
pub fn has(engine: &Engine, key: Label) -> bool {
engine
.introspector
.query(&Self::elem().select())
.iter()
.any(|elem| elem.to_packed::<Self>().unwrap().sources.derived.has(key))
}
pub fn keys(introspector: Tracked<Introspector>) -> Vec<(Label, Option<EcoString>)> {
let mut vec = vec![];
for elem in introspector.query(&Self::elem().select()).iter() {
let this = elem.to_packed::<Self>().unwrap();
for (key, entry) in this.sources.derived.iter() {
let detail = entry.title().map(|title| title.value.to_str().into());
vec.push((key, detail))
}
}
vec
}
}
impl Synthesize for Packed<BibliographyElem> {
fn synthesize(&mut self, _: &mut Engine, styles: StyleChain) -> SourceResult<()> {
let elem = self.as_mut();
elem.push_lang(TextElem::lang_in(styles));
elem.push_region(TextElem::region_in(styles));
Ok(())
}
}
impl Show for Packed<BibliographyElem> {
#[typst_macros::time(name = "bibliography", span = self.span())]
fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content> {
const COLUMN_GUTTER: Em = Em::new(0.65);
const INDENT: Em = Em::new(1.5);
let span = self.span();
let mut seq = vec![];
if let Some(title) = self.title(styles).unwrap_or_else(|| {
Some(TextElem::packed(Self::local_name_in(styles)).spanned(span))
}) {
seq.push(
HeadingElem::new(title)
.with_depth(NonZeroUsize::ONE)
.pack()
.spanned(span),
);
}
let works = Works::generate(engine).at(span)?;
let references = works
.references
.as_ref()
.ok_or("CSL style is not suitable for bibliographies")
.at(span)?;
if references.iter().any(|(prefix, _)| prefix.is_some()) {
let row_gutter = ParElem::spacing_in(styles);
let mut cells = vec![];
for (prefix, reference) in references {
cells.push(GridChild::Item(GridItem::Cell(
Packed::new(GridCell::new(prefix.clone().unwrap_or_default()))
.spanned(span),
)));
cells.push(GridChild::Item(GridItem::Cell(
Packed::new(GridCell::new(reference.clone())).spanned(span),
)));
}
seq.push(
GridElem::new(cells)
.with_columns(TrackSizings(smallvec![Sizing::Auto; 2]))
.with_column_gutter(TrackSizings(smallvec![COLUMN_GUTTER.into()]))
.with_row_gutter(TrackSizings(smallvec![row_gutter.into()]))
.pack()
.spanned(span),
);
} else {
for (_, reference) in references {
let realized = reference.clone();
let block = if works.hanging_indent {
let body = HElem::new((-INDENT).into()).pack() + realized;
let inset = Sides::default()
.with(TextElem::dir_in(styles).start(), Some(INDENT.into()));
BlockElem::new()
.with_body(Some(BlockBody::Content(body)))
.with_inset(inset)
} else {
BlockElem::new().with_body(Some(BlockBody::Content(realized)))
};
seq.push(block.pack().spanned(span));
}
}
Ok(Content::sequence(seq))
}
}
impl ShowSet for Packed<BibliographyElem> {
fn show_set(&self, _: StyleChain) -> Styles {
const INDENT: Em = Em::new(1.0);
let mut out = Styles::new();
out.set(HeadingElem::set_numbering(None));
out.set(PadElem::set_left(INDENT.into()));
out
}
}
impl LocalName for Packed<BibliographyElem> {
const KEY: &'static str = "bibliography";
}
#[derive(Clone, PartialEq, Hash)]
pub struct Bibliography(Arc<ManuallyHash<IndexMap<Label, hayagriva::Entry>>>);
impl Bibliography {
fn load(
world: Tracked<dyn World + '_>,
sources: Spanned<OneOrMultiple<DataSource>>,
) -> SourceResult<Derived<OneOrMultiple<DataSource>, Self>> {
let data = sources.load(world)?;
let bibliography = Self::decode(&sources.v, &data).at(sources.span)?;
Ok(Derived::new(sources.v, bibliography))
}
#[comemo::memoize]
#[typst_macros::time(name = "load bibliography")]
fn decode(
sources: &OneOrMultiple<DataSource>,
data: &[Bytes],
) -> StrResult<Bibliography> {
let mut map = IndexMap::new();
let mut duplicates = Vec::<EcoString>::new();
for (source, data) in sources.0.iter().zip(data) {
let library = decode_library(source, data)?;
for entry in library {
match map.entry(Label::new(PicoStr::intern(entry.key()))) {
indexmap::map::Entry::Vacant(vacant) => {
vacant.insert(entry);
}
indexmap::map::Entry::Occupied(_) => {
duplicates.push(entry.key().into());
}
}
}
}
if !duplicates.is_empty() {
bail!("duplicate bibliography keys: {}", duplicates.join(", "));
}
Ok(Bibliography(Arc::new(ManuallyHash::new(map, typst_utils::hash128(data)))))
}
fn has(&self, key: Label) -> bool {
self.0.contains_key(&key)
}
fn get(&self, key: Label) -> Option<&hayagriva::Entry> {
self.0.get(&key)
}
fn iter(&self) -> impl Iterator<Item = (Label, &hayagriva::Entry)> {
self.0.iter().map(|(&k, v)| (k, v))
}
}
impl Debug for Bibliography {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_set().entries(self.0.keys()).finish()
}
}
fn decode_library(source: &DataSource, data: &Bytes) -> StrResult<Library> {
let src = data.as_str().map_err(FileError::from)?;
if let DataSource::Path(path) = source {
let ext = Path::new(path.as_str())
.extension()
.and_then(OsStr::to_str)
.unwrap_or_default();
match ext.to_lowercase().as_str() {
"yml" | "yaml" => hayagriva::io::from_yaml_str(src)
.map_err(|err| eco_format!("failed to parse YAML ({err})")),
"bib" => hayagriva::io::from_biblatex_str(src)
.map_err(|errors| format_biblatex_error(src, Some(path), errors)),
_ => bail!("unknown bibliography format (must be .yml/.yaml or .bib)"),
}
} else {
let haya_err = match hayagriva::io::from_yaml_str(src) {
Ok(library) => return Ok(library),
Err(err) => err,
};
let bib_errs = match hayagriva::io::from_biblatex_str(src) {
Ok(library) => return Ok(library),
Err(err) => err,
};
let mut yaml = 0;
let mut biblatex = 0;
for c in src.chars() {
match c {
':' => yaml += 1,
'{' => biblatex += 1,
_ => {}
}
}
if yaml > biblatex {
bail!("failed to parse YAML ({haya_err})")
} else {
Err(format_biblatex_error(src, None, bib_errs))
}
}
}
fn format_biblatex_error(
src: &str,
path: Option<&str>,
errors: Vec<BibLaTeXError>,
) -> EcoString {
let Some(error) = errors.first() else {
return match path {
Some(path) => eco_format!("failed to parse BibLaTeX file ({path})"),
None => eco_format!("failed to parse BibLaTeX"),
};
};
let (span, msg) = match error {
BibLaTeXError::Parse(error) => (&error.span, error.kind.to_string()),
BibLaTeXError::Type(error) => (&error.span, error.kind.to_string()),
};
let line = src.get(..span.start).unwrap_or_default().lines().count();
match path {
Some(path) => eco_format!("failed to parse BibLaTeX file ({path}:{line}: {msg})"),
None => eco_format!("failed to parse BibLaTeX ({line}: {msg})"),
}
}
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct CslStyle(Arc<ManuallyHash<citationberg::IndependentStyle>>);
impl CslStyle {
pub fn load(
world: Tracked<dyn World + '_>,
Spanned { v: source, span }: Spanned<CslSource>,
) -> SourceResult<Derived<CslSource, Self>> {
let style = match &source {
CslSource::Named(style) => Self::from_archived(*style),
CslSource::Normal(source) => {
let data = Spanned::new(source, span).load(world)?;
Self::from_data(data).at(span)?
}
};
Ok(Derived::new(source, style))
}
#[comemo::memoize]
pub fn from_archived(archived: ArchivedStyle) -> CslStyle {
match archived.get() {
citationberg::Style::Independent(style) => Self(Arc::new(ManuallyHash::new(
style,
typst_utils::hash128(&(TypeId::of::<ArchivedStyle>(), archived)),
))),
_ => unreachable!("archive should not contain dependant styles"),
}
}
#[comemo::memoize]
pub fn from_data(data: Bytes) -> StrResult<CslStyle> {
let text = data.as_str().map_err(FileError::from)?;
citationberg::IndependentStyle::from_xml(text)
.map(|style| {
Self(Arc::new(ManuallyHash::new(
style,
typst_utils::hash128(&(TypeId::of::<Bytes>(), data)),
)))
})
.map_err(|err| eco_format!("failed to load CSL style ({err})"))
}
pub fn get(&self) -> &citationberg::IndependentStyle {
self.0.as_ref()
}
}
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum CslSource {
Named(ArchivedStyle),
Normal(DataSource),
}
impl Reflect for CslSource {
#[comemo::memoize]
fn input() -> CastInfo {
let source = std::iter::once(DataSource::input());
let names = ArchivedStyle::all().iter().map(|name| {
CastInfo::Value(name.names()[0].into_value(), name.display_name())
});
CastInfo::Union(source.into_iter().chain(names).collect())
}
fn output() -> CastInfo {
DataSource::output()
}
fn castable(value: &Value) -> bool {
DataSource::castable(value)
}
}
impl FromValue for CslSource {
fn from_value(value: Value) -> HintedStrResult<Self> {
if EcoString::castable(&value) {
let string = EcoString::from_value(value.clone())?;
if Path::new(string.as_str()).extension().is_none() {
let style = ArchivedStyle::by_name(&string)
.ok_or_else(|| eco_format!("unknown style: {}", string))?;
return Ok(CslSource::Named(style));
}
}
DataSource::from_value(value).map(CslSource::Normal)
}
}
impl IntoValue for CslSource {
fn into_value(self) -> Value {
match self {
Self::Named(v) => v.names().last().unwrap().into_value(),
Self::Normal(v) => v.into_value(),
}
}
}
pub(super) struct Works {
pub citations: HashMap<Location, SourceResult<Content>>,
pub references: Option<Vec<(Option<Content>, Content)>>,
pub hanging_indent: bool,
}
impl Works {
pub fn generate(engine: &Engine) -> StrResult<Arc<Works>> {
Self::generate_impl(engine.routines, engine.world, engine.introspector)
}
#[comemo::memoize]
fn generate_impl(
routines: &Routines,
world: Tracked<dyn World + '_>,
introspector: Tracked<Introspector>,
) -> StrResult<Arc<Works>> {
let mut generator = Generator::new(routines, world, introspector)?;
let rendered = generator.drive();
let works = generator.display(&rendered)?;
Ok(Arc::new(works))
}
}
struct Generator<'a> {
routines: &'a Routines,
world: Tracked<'a, dyn World + 'a>,
bibliography: Packed<BibliographyElem>,
groups: EcoVec<Content>,
infos: Vec<GroupInfo>,
failures: HashMap<Location, SourceResult<Content>>,
}
struct GroupInfo {
location: Location,
span: Span,
footnote: bool,
subinfos: SmallVec<[CiteInfo; 1]>,
}
struct CiteInfo {
key: Label,
supplement: Option<Content>,
hidden: bool,
}
impl<'a> Generator<'a> {
fn new(
routines: &'a Routines,
world: Tracked<'a, dyn World + 'a>,
introspector: Tracked<Introspector>,
) -> StrResult<Self> {
let bibliography = BibliographyElem::find(introspector)?;
let groups = introspector.query(&CiteGroup::elem().select());
let infos = Vec::with_capacity(groups.len());
Ok(Self {
routines,
world,
bibliography,
groups,
infos,
failures: HashMap::new(),
})
}
fn drive(&mut self) -> hayagriva::Rendered {
static LOCALES: LazyLock<Vec<citationberg::Locale>> =
LazyLock::new(hayagriva::archive::locales);
let database = &self.bibliography.sources.derived;
let bibliography_style = &self.bibliography.style(StyleChain::default()).derived;
let mut driver = BibliographyDriver::new();
for elem in &self.groups {
let group = elem.to_packed::<CiteGroup>().unwrap();
let location = elem.location().unwrap();
let children = &group.children;
let Some(first) = children.first() else { continue };
let mut subinfos = SmallVec::with_capacity(children.len());
let mut items = Vec::with_capacity(children.len());
let mut errors = EcoVec::new();
let mut normal = true;
for child in children {
let Some(entry) = database.get(child.key) else {
errors.push(error!(
child.span(),
"key `{}` does not exist in the bibliography",
child.key.resolve()
));
continue;
};
let supplement = child.supplement(StyleChain::default());
let locator = supplement.as_ref().map(|_| {
SpecificLocator(
citationberg::taxonomy::Locator::Custom,
hayagriva::LocatorPayload::Transparent,
)
});
let mut hidden = false;
let special_form = match child.form(StyleChain::default()) {
None => {
hidden = true;
None
}
Some(CitationForm::Normal) => None,
Some(CitationForm::Prose) => Some(hayagriva::CitePurpose::Prose),
Some(CitationForm::Full) => Some(hayagriva::CitePurpose::Full),
Some(CitationForm::Author) => Some(hayagriva::CitePurpose::Author),
Some(CitationForm::Year) => Some(hayagriva::CitePurpose::Year),
};
normal &= special_form.is_none();
subinfos.push(CiteInfo { key: child.key, supplement, hidden });
items.push(CitationItem::new(entry, locator, None, hidden, special_form));
}
if !errors.is_empty() {
self.failures.insert(location, Err(errors));
continue;
}
let style = match first.style(StyleChain::default()) {
Smart::Auto => bibliography_style.get(),
Smart::Custom(style) => style.derived.get(),
};
self.infos.push(GroupInfo {
location,
subinfos,
span: first.span(),
footnote: normal
&& style.settings.class == citationberg::StyleClass::Note,
});
driver.citation(CitationRequest::new(
items,
style,
Some(locale(
first.lang().copied().unwrap_or(Lang::ENGLISH),
first.region().copied().flatten(),
)),
&LOCALES,
None,
));
}
let locale = locale(
self.bibliography.lang().copied().unwrap_or(Lang::ENGLISH),
self.bibliography.region().copied().flatten(),
);
if self.bibliography.full(StyleChain::default()) {
for (_, entry) in database.iter() {
driver.citation(CitationRequest::new(
vec![CitationItem::new(entry, None, None, true, None)],
bibliography_style.get(),
Some(locale.clone()),
&LOCALES,
None,
));
}
}
driver.finish(BibliographyRequest {
style: bibliography_style.get(),
locale: Some(locale),
locale_files: &LOCALES,
})
}
fn display(&mut self, rendered: &hayagriva::Rendered) -> StrResult<Works> {
let citations = self.display_citations(rendered)?;
let references = self.display_references(rendered)?;
let hanging_indent =
rendered.bibliography.as_ref().is_some_and(|b| b.hanging_indent);
Ok(Works { citations, references, hanging_indent })
}
fn display_citations(
&mut self,
rendered: &hayagriva::Rendered,
) -> StrResult<HashMap<Location, SourceResult<Content>>> {
let mut links = HashMap::new();
if let Some(bibliography) = &rendered.bibliography {
let location = self.bibliography.location().unwrap();
for (k, item) in bibliography.items.iter().enumerate() {
links.insert(item.key.as_str(), location.variant(k + 1));
}
}
let mut output = std::mem::take(&mut self.failures);
for (info, citation) in self.infos.iter().zip(&rendered.citations) {
let supplement = |i: usize| info.subinfos.get(i)?.supplement.clone();
let link = |i: usize| {
links.get(info.subinfos.get(i)?.key.resolve().as_str()).copied()
};
let renderer = ElemRenderer {
routines: self.routines,
world: self.world,
span: info.span,
supplement: &supplement,
link: &link,
};
let content = if info.subinfos.iter().all(|sub| sub.hidden) {
Content::empty()
} else {
let mut content = renderer.display_elem_children(
&citation.citation,
&mut None,
true,
)?;
if info.footnote {
content = FootnoteElem::with_content(content).pack();
}
content
};
output.insert(info.location, Ok(content));
}
Ok(output)
}
#[allow(clippy::type_complexity)]
fn display_references(
&self,
rendered: &hayagriva::Rendered,
) -> StrResult<Option<Vec<(Option<Content>, Content)>>> {
let Some(rendered) = &rendered.bibliography else { return Ok(None) };
let mut first_occurrences = HashMap::new();
for info in &self.infos {
for subinfo in &info.subinfos {
let key = subinfo.key.resolve();
first_occurrences.entry(key).or_insert(info.location);
}
}
let location = self.bibliography.location().unwrap();
let mut output = vec![];
for (k, item) in rendered.items.iter().enumerate() {
let renderer = ElemRenderer {
routines: self.routines,
world: self.world,
span: self.bibliography.span(),
supplement: &|_| None,
link: &|_| None,
};
let backlink = location.variant(k + 1);
let mut prefix = item
.first_field
.as_ref()
.map(|elem| {
let mut content =
renderer.display_elem_child(elem, &mut None, false)?;
if let Some(location) = first_occurrences.get(item.key.as_str()) {
let dest = Destination::Location(*location);
content = content.linked(dest);
}
StrResult::Ok(content)
})
.transpose()?;
let mut reference =
renderer.display_elem_children(&item.content, &mut prefix, false)?;
prefix.as_mut().unwrap_or(&mut reference).set_location(backlink);
output.push((prefix, reference));
}
Ok(Some(output))
}
}
struct ElemRenderer<'a> {
routines: &'a Routines,
world: Tracked<'a, dyn World + 'a>,
span: Span,
supplement: &'a dyn Fn(usize) -> Option<Content>,
link: &'a dyn Fn(usize) -> Option<Location>,
}
impl ElemRenderer<'_> {
fn display_elem_children(
&self,
elems: &hayagriva::ElemChildren,
prefix: &mut Option<Content>,
is_citation: bool,
) -> StrResult<Content> {
Ok(Content::sequence(
elems
.0
.iter()
.enumerate()
.map(|(i, elem)| {
self.display_elem_child(elem, prefix, is_citation && i == 0)
})
.collect::<StrResult<Vec<_>>>()?,
))
}
fn display_elem_child(
&self,
elem: &hayagriva::ElemChild,
prefix: &mut Option<Content>,
trim_start: bool,
) -> StrResult<Content> {
Ok(match elem {
hayagriva::ElemChild::Text(formatted) => {
self.display_formatted(formatted, trim_start)
}
hayagriva::ElemChild::Elem(elem) => self.display_elem(elem, prefix)?,
hayagriva::ElemChild::Markup(markup) => self.display_math(markup),
hayagriva::ElemChild::Link { text, url } => self.display_link(text, url)?,
hayagriva::ElemChild::Transparent { cite_idx, format } => {
self.display_transparent(*cite_idx, format)
}
})
}
fn display_elem(
&self,
elem: &hayagriva::Elem,
prefix: &mut Option<Content>,
) -> StrResult<Content> {
use citationberg::Display;
let block_level = matches!(elem.display, Some(Display::Block | Display::Indent));
let mut suf_prefix = None;
let mut content = self.display_elem_children(
&elem.children,
if block_level { &mut suf_prefix } else { prefix },
false,
)?;
if let Some(prefix) = suf_prefix {
const COLUMN_GUTTER: Em = Em::new(0.65);
content = GridElem::new(vec![
GridChild::Item(GridItem::Cell(
Packed::new(GridCell::new(prefix)).spanned(self.span),
)),
GridChild::Item(GridItem::Cell(
Packed::new(GridCell::new(content)).spanned(self.span),
)),
])
.with_columns(TrackSizings(smallvec![Sizing::Auto; 2]))
.with_column_gutter(TrackSizings(smallvec![COLUMN_GUTTER.into()]))
.pack()
.spanned(self.span);
}
match elem.display {
Some(Display::Block) => {
content = BlockElem::new()
.with_body(Some(BlockBody::Content(content)))
.pack()
.spanned(self.span);
}
Some(Display::Indent) => {
content = PadElem::new(content).pack().spanned(self.span);
}
Some(Display::LeftMargin) => {
*prefix.get_or_insert_with(Default::default) += content;
return Ok(Content::empty());
}
_ => {}
}
if let Some(hayagriva::ElemMeta::Entry(i)) = elem.meta {
if let Some(location) = (self.link)(i) {
let dest = Destination::Location(location);
content = content.linked(dest);
}
}
Ok(content)
}
fn display_math(&self, math: &str) -> Content {
(self.routines.eval_string)(
self.routines,
self.world,
math,
self.span,
EvalMode::Math,
Scope::new(),
)
.map(Value::display)
.unwrap_or_else(|_| TextElem::packed(math).spanned(self.span))
}
fn display_link(&self, text: &hayagriva::Formatted, url: &str) -> StrResult<Content> {
let dest = Destination::Url(Url::new(url)?);
Ok(LinkElem::new(dest.into(), self.display_formatted(text, false))
.pack()
.spanned(self.span))
}
fn display_transparent(&self, i: usize, format: &hayagriva::Formatting) -> Content {
let content = (self.supplement)(i).unwrap_or_default();
apply_formatting(content, format)
}
fn display_formatted(
&self,
formatted: &hayagriva::Formatted,
trim_start: bool,
) -> Content {
let formatted_text = if trim_start {
formatted.text.trim_start()
} else {
formatted.text.as_str()
};
let content = TextElem::packed(formatted_text).spanned(self.span);
apply_formatting(content, &formatted.formatting)
}
}
fn apply_formatting(mut content: Content, format: &hayagriva::Formatting) -> Content {
match format.font_style {
citationberg::FontStyle::Normal => {}
citationberg::FontStyle::Italic => {
content = content.styled(TextElem::set_style(FontStyle::Italic));
}
}
match format.font_variant {
citationberg::FontVariant::Normal => {}
citationberg::FontVariant::SmallCaps => {
content =
content.styled(TextElem::set_smallcaps(Some(Smallcaps::Minuscules)));
}
}
match format.font_weight {
citationberg::FontWeight::Normal => {}
citationberg::FontWeight::Bold => {
content = content.styled(TextElem::set_delta(WeightDelta(300)));
}
citationberg::FontWeight::Light => {
content = content.styled(TextElem::set_delta(WeightDelta(-100)));
}
}
match format.text_decoration {
citationberg::TextDecoration::None => {}
citationberg::TextDecoration::Underline => {
content = content.underlined();
}
}
let span = content.span();
match format.vertical_align {
citationberg::VerticalAlign::None => {}
citationberg::VerticalAlign::Baseline => {}
citationberg::VerticalAlign::Sup => {
content = HElem::hole().pack() + SuperElem::new(content).pack().spanned(span);
}
citationberg::VerticalAlign::Sub => {
content = HElem::hole().pack() + SubElem::new(content).pack().spanned(span);
}
}
content
}
fn locale(lang: Lang, region: Option<Region>) -> citationberg::LocaleCode {
let mut value = String::with_capacity(5);
value.push_str(lang.as_str());
if let Some(region) = region {
value.push('-');
value.push_str(region.as_str())
}
citationberg::LocaleCode(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bibliography_load_builtin_styles() {
for &archived in ArchivedStyle::all() {
let _ = CslStyle::from_archived(archived);
}
}
}