//! References: citations and bibliography (APA, MLA, Chicago, IEEE, Harvard, ISO 690, Turabian, //! GB/T 7714, GOST, SIST02), source manager, index, table of figures, cross-references, table //! of authorities, footnote options. use serde_json::{Value, json}; use wordcraft_doc::collate::{SortKey, heading_letter, sort_key}; use wordcraft_doc::para::InlineObject; use wordcraft_doc::props::{CharProps, TabAlign, TabLeader, TabStop}; use wordcraft_doc::{Block, Document, Paragraph, Path, Pos, Source, StoryRef}; use super::references::FieldCode; use super::{delete_selection, sel_result}; use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p}; /// How a style orders its bibliography (and, for numbered styles, numbers its citations). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Order { /// Alphabetical by the first author's surname (the title when there is no author). Author, /// Alphabetical by title. Title, /// In order of first citation in the document. Cited, } /// How one author's name is written in a bibliography entry. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Name { /// Rivera, Alex LastFirst, /// Alex Rivera FirstLast, /// Rivera, A. LastInitials, /// A. Rivera InitialsLast, /// Rivera A. LastSpaceInitials, /// RIVERA, Alex UpperLastFirst, /// RIVERA A UpperLastBareInitials, } /// The author list of a bibliography entry. #[derive(Clone, Copy, Debug)] pub struct Names { /// The first author's form, and every later author's. pub first: Name, pub rest: Name, /// Between names; between exactly two; before the last of three or more. pub sep: &'static str, pub two: &'static str, pub last: &'static str, /// List at most this many authors, then `et_al` (0: list them all). pub max: usize, pub et_al: &'static str, } /// The in-text citation. #[derive(Clone, Copy, Debug)] pub enum Cite { /// `(WhoYearPages)`. AuthorDate { year_sep: &'static str, pages_sep: &'static str }, /// `(Who Pages)`. AuthorPage, /// `n`; pages follow `pages_sep` inside the brackets (left out when `None`). Number { open: &'static str, close: &'static str, pages_sep: Option<&'static str> }, } /// A citation and bibliography style, as data. Entry templates fill `{n}`, `{names}`, `{year}`, /// `{title}`, `{city}`, `{publisher}`, `{pub}` (city: publisher), `{journal}`, `{volume}`, /// `{pages}`, `{url}` and `{type}` (GB/T 7714 document type code); text between `⟦` and `⟧` is /// left out when a field in it is empty, and a full stop never doubles up. #[derive(Debug)] pub struct CiteStyle { /// The name shown in the style picker and stored in the session. pub name: &'static str, /// Lowercase letter/digit prefixes of Word's style names and style-sheet file names that mean /// this style (`gostname` matches "GOST - Name Sort"); the longest match wins. pub aliases: &'static [&'static str], pub cite: Cite, /// Joins two authors in a citation ("&" or "and"). pub and: &'static str, /// Cite this many authors or more as "First et al.". pub et_al_from: usize, pub order: Order, pub names: Names, /// Entry template for a book (or anything without a journal), and for a journal article. pub book: &'static str, pub article: &'static str, /// Default title of the bibliography. pub bib_title: &'static str, } impl CiteStyle { /// Numbered styles cite `[1]`/`(1)` and list entries without a hanging indent. pub fn numbered(&self) -> bool { matches!(self.cite, Cite::Number { .. }) } } const fn names(first: Name, rest: Name, sep: &'static str, two: &'static str, last: &'static str) -> Names { Names { first, rest, sep, two, last, max: 0, et_al: "" } } const AUTHOR_DATE: Cite = Cite::AuthorDate { year_sep: " ", pages_sep: ", p. " }; /// Every style, in picker order (alphabetical). Formats follow the published style guides' /// rules for the source types WordCraft records, written in our own words. pub static STYLES: [CiteStyle; 12] = [ CiteStyle { name: "APA", aliases: &["apa"], cite: Cite::AuthorDate { year_sep: ", ", pages_sep: ", p. " }, and: "&", et_al_from: 3, order: Order::Author, names: names(Name::LastInitials, Name::LastInitials, ", ", ", & ", ", & "), book: "⟦{names} ⟧({year}). {title}.⟦ {publisher}.⟧⟦ {url}⟧", article: "⟦{names} ⟧({year}). {title}. {journal}⟦, {volume}⟧⟦, {pages}⟧.⟦ {url}⟧", bib_title: "References", }, CiteStyle { name: "Chicago", aliases: &["chicago"], cite: Cite::AuthorDate { year_sep: " ", pages_sep: ", " }, and: "and", et_al_from: 3, order: Order::Author, names: names(Name::LastFirst, Name::FirstLast, ", ", ", and ", ", and "), book: "⟦{names}. ⟧{year}. {title}.⟦ {pub}.⟧⟦ {url}⟧", article: "⟦{names}. ⟧{year}. {title}. {journal}⟦, {volume}⟧⟦, {pages}⟧.⟦ {url}⟧", bib_title: "References", }, // GB/T 7714 sequence-coding: numbered by first citation, surnames in capitals with bare // initials, at most three authors, a document type code after the title. CiteStyle { name: "GB/T 7714", aliases: &["gb"], cite: Cite::Number { open: "[", close: "]", pages_sep: Some(", ") }, and: "and", et_al_from: 3, order: Order::Cited, names: Names { max: 3, et_al: ", et al.", ..names(Name::UpperLastBareInitials, Name::UpperLastBareInitials, ", ", ", ", ", ") }, book: "[{n}] ⟦{names}. ⟧{title}[{type}].⟦ {pub},⟧ {year}.⟦ {url}.⟧", article: "[{n}] ⟦{names}. ⟧{title}[{type}]. {journal}, {year}⟦, {volume}⟧⟦: {pages}⟧.⟦ {url}.⟧", bib_title: "References", }, // GOST 7.1: a numbered list in alphabetical order (by author or by title); areas separated // by " – ", the container after "//". CiteStyle { name: "GOST (name sort)", aliases: &["gost", "gostname"], cite: Cite::Number { open: "[", close: "]", pages_sep: Some(", p. ") }, and: "and", et_al_from: 3, order: Order::Author, names: names(Name::LastSpaceInitials, Name::LastSpaceInitials, ", ", ", ", ", "), book: GOST_BOOK, article: GOST_ARTICLE, bib_title: "References", }, CiteStyle { name: "GOST (title sort)", aliases: &["gosttitle"], cite: Cite::Number { open: "[", close: "]", pages_sep: Some(", p. ") }, and: "and", et_al_from: 3, order: Order::Title, names: names(Name::LastSpaceInitials, Name::LastSpaceInitials, ", ", ", ", ", "), book: GOST_BOOK, article: GOST_ARTICLE, bib_title: "References", }, // Harvard as taught by Anglia Ruskin: "Surname, I., Year. Title. Place: Publisher." CiteStyle { name: "Harvard (Anglia)", aliases: &["harvard"], cite: Cite::AuthorDate { year_sep: ", ", pages_sep: ", p. " }, and: "and", et_al_from: 4, order: Order::Author, names: names(Name::LastInitials, Name::LastInitials, ", ", " and ", " and "), book: "⟦{names}, ⟧{year}. {title}.⟦ {pub}.⟧⟦ Available at: <{url}>.⟧", article: "⟦{names}, ⟧{year}. {title}. {journal}⟦, {volume}⟧⟦, pp. {pages}⟧.⟦ Available at: <{url}>.⟧", bib_title: "References", }, CiteStyle { name: "IEEE", aliases: &["ieee"], cite: Cite::Number { open: "[", close: "]", pages_sep: None }, and: "and", et_al_from: 3, order: Order::Cited, names: names(Name::InitialsLast, Name::InitialsLast, ", ", ", ", ", "), book: "[{n}] ⟦{names}, ⟧“{title},”⟦ {pub},⟧ {year}.⟦ {url}⟧", article: "[{n}] ⟦{names}, ⟧“{title},” {journal}⟦, {volume}⟧⟦, {pages}⟧, {year}.⟦ {url}⟧", bib_title: "References", }, // ISO 690 first element and date: surnames in capitals, the year after the names. CiteStyle { name: "ISO 690 (author-date)", aliases: &["iso690"], cite: AUTHOR_DATE, and: "and", et_al_from: 4, order: Order::Author, names: names(Name::UpperLastFirst, Name::UpperLastFirst, ", ", " and ", " and "), book: "⟦{names}, ⟧{year}. {title}.⟦ {pub}.⟧⟦ Available from: {url}⟧", article: "⟦{names}, ⟧{year}. {title}. {journal}⟦, {volume}⟧⟦, {pages}⟧.⟦ Available from: {url}⟧", bib_title: "References", }, // ISO 690 numeric reference: numbered by first citation, the year with the imprint. CiteStyle { name: "ISO 690 (numerical)", aliases: &["iso690num", "iso690nmerical"], cite: Cite::Number { open: "(", close: ")", pages_sep: Some(", p. ") }, and: "and", et_al_from: 4, order: Order::Cited, names: names(Name::UpperLastFirst, Name::UpperLastFirst, ", ", " and ", " and "), book: "{n}. ⟦{names}. ⟧{title}.⟦ {pub},⟧ {year}.⟦ Available from: {url}⟧", article: "{n}. ⟦{names}. ⟧{title}. {journal}. {year}⟦, {volume}⟧⟦, {pages}⟧.⟦ Available from: {url}⟧", bib_title: "References", }, CiteStyle { name: "MLA", aliases: &["mla"], cite: Cite::AuthorPage, and: "and", et_al_from: 3, order: Order::Author, names: Names { max: 1, et_al: ", et al.", ..names(Name::LastFirst, Name::LastFirst, ", ", ", ", ", ") }, book: "⟦{names}. ⟧“{title}.”⟦ {publisher},⟧ {year}.⟦ {url}⟧", article: "⟦{names}. ⟧“{title}.” {journal}⟦, {volume}⟧⟦, {pages}⟧, {year}.⟦ {url}⟧", bib_title: "Works Cited", }, // SIST 02: numbered by first citation, full names separated by semicolons. CiteStyle { name: "SIST02", aliases: &["sist"], cite: Cite::Number { open: "(", close: ")", pages_sep: Some(", p. ") }, and: "and", et_al_from: 3, order: Order::Cited, names: names(Name::LastFirst, Name::LastFirst, "; ", "; ", "; "), book: "{n}) ⟦{names}. ⟧{title}.⟦ {city},⟧⟦ {publisher},⟧ {year}.⟦ {url}⟧", article: "{n}) ⟦{names}. ⟧{title}. {journal}. {year}⟦, vol. {volume}⟧⟦, p. {pages}⟧.⟦ {url}⟧", bib_title: "References", }, // Turabian: author-date citations, a bibliography with the year in the imprint. CiteStyle { name: "Turabian", aliases: &["turabian"], cite: Cite::AuthorDate { year_sep: " ", pages_sep: ", " }, and: "and", et_al_from: 4, order: Order::Author, names: names(Name::LastFirst, Name::FirstLast, ", ", ", and ", ", and "), book: "⟦{names}. ⟧{title}.⟦ {pub},⟧ {year}.⟦ {url}.⟧", article: "⟦{names}. ⟧“{title}.” {journal}⟦ {volume}⟧ ({year})⟦: {pages}⟧.⟦ {url}.⟧", bib_title: "Bibliography", }, ]; const GOST_BOOK: &str = "{n}. ⟦{names} ⟧{title}. –⟦ {city} :⟧⟦ {publisher},⟧ {year}.⟦ – URL: {url}.⟧"; const GOST_ARTICLE: &str = "{n}. ⟦{names} ⟧{title} // {journal}. – {year}.⟦ – Vol. {volume}.⟧⟦ – P. {pages}.⟧⟦ – URL: {url}.⟧"; /// The style called `name`: one of ours (any case), or Word's style name or style-sheet file /// name (`Harvard - Anglia`, `\GostTitle.XSL`). pub fn find_style(name: &str) -> Option<&'static CiteStyle> { if let Some(st) = STYLES.iter().find(|x| x.name.eq_ignore_ascii_case(name.trim())) { return Some(st); } let key: String = name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect(); let key = key.strip_suffix("xsl").unwrap_or(&key); STYLES .iter() .flat_map(|st| st.aliases.iter().map(move |a| (st, *a))) .filter(|(_, a)| key.starts_with(a)) .max_by_key(|(_, a)| a.len()) .map(|(st, _)| st) } /// The session's style; APA when the name is unknown. pub fn style(name: &str) -> &'static CiteStyle { find_style(name).unwrap_or(&STYLES[0]) } pub fn specs() -> Vec { vec![ CommandSpec::new("references.sources", "Manage Sources", "References › Citations & Bibliography", sources) .params(r#"{"add"?: Source, "remove"?: tag, "import"?: path (a Word bibliography file, `b:Sources` / `Sources.xml`)} → list"#), CommandSpec::new("references.citation", "Insert Citation", "References › Citations & Bibliography", citation).params(r#"{"tag"?: string, "source"?: Source (added if new), "pages"?: string}"#), CommandSpec::new("references.citationStyle", "Style", "References › Citations & Bibliography", |s, v| { let st = p::str(v, "style").unwrap_or("APA"); let st = find_style(st).ok_or_else(|| { CmdError::Params(format!("style must be one of {:?}", STYLES.iter().map(|x| x.name).collect::>())) })?; s.bib_style = st.name.to_string(); // Recorded in the document too, so a save keeps it. s.doc.settings.bib_style = Some(st.name.to_string()); update_citations(s)?; Ok(json!({"style": s.bib_style})) }) .params( r#"{"style": "APA|Chicago|GB/T 7714|GOST (name sort)|GOST (title sort)|Harvard (Anglia)|IEEE|ISO 690 (author-date)|ISO 690 (numerical)|MLA|SIST02|Turabian" (Word's style names work too)}"#, ), CommandSpec::new("references.bibliography", "Bibliography", "References › Citations & Bibliography", |s, v| { let title = p::str(v, "title").unwrap_or(style(&s.bib_style).bib_title).to_string(); generated_list(s, "BIBLIOGRAPHY", &title)?; sel_result(s) }) .params(r#"{"title"?: string}"#), CommandSpec::new("references.tableOfFigures", "Insert Table of Figures", "References › Captions", table_of_figures).params( r#"{"label"?: "Figure|Table|Equation" or a caption label of your own, "includeLabel"?: bool, "pageNumbers"?: bool, "rightAlign"?: bool, "tabLeader"?: "dot|hyphen|underscore|none"}"#, ), CommandSpec::new("references.updateFigures", "Update Table", "References › Captions", |s, _| { update_generated(s)?; sel_result(s) }), CommandSpec::new("references.markCitation", "Mark Citation", "References › Table of Authorities", |s, v| { let entry = p::str(v, "entry").map(str::to_string).unwrap_or_else(|| s.selected_text().trim().to_string()); if entry.is_empty() { return Err(CmdError::Params("select a citation or give `entry`".into())); } let (_, b) = s.sel.ordered(); s.doc.insert_object(&b, InlineObject::Field { instr: format!("TA \\l \"{}\"", entry.replace('"', "")), result: String::new(), locked: false, dirty: false, code: false, form: String::new() }, &CharProps { hidden: Some(true), ..Default::default() })?; Ok(json!({"entry": entry})) }) .params(r#"{"entry"?: string}"#) .key(super::non_mac("Alt+Shift+I")), CommandSpec::new("references.tableOfAuthorities", "Insert Table of Authorities", "References › Table of Authorities", |s, _| { generated_list(s, "TOA", "Table of Authorities")?; sel_result(s) }), CommandSpec::new("references.updateAuthorities", "Update Table", "References › Table of Authorities", |s, _| { update_generated(s)?; sel_result(s) }), CommandSpec::new("insert.crossReference", "Cross-reference", "Insert › Links", cross_ref) .params(r#"{"to": "heading|bookmark|figure|table|equation|label: (a caption label of your own)", "target": string (text / name / number), "show"?: "text|page|number|aboveBelow"} or {} to list targets"#), CommandSpec::new("references.noteOptions", "Footnote and Endnote", "References › Footnotes", super::references::note_options).params( r#"{"kind"?: "footnote|endnote", "pos"?: "pageBottom|beneathText" (footnotes) | "sectEnd|docEnd" (endnotes), "numFmt"?: "decimal|lowerRoman|upperRoman|lowerLetter|upperLetter|…", "numStart"?: 1-32767, "numRestart"?: "continuous|eachSect|eachPage" (each page: footnotes only), "scope"?: "document|section", "footnoteFormat"?: …, "endnoteFormat"?: …} — no settings: the options in effect at the caret"#, ), CommandSpec::new("references.researcher", "Researcher", "References › Research", |s, _| { s.status = "Researcher needs an online service; WordCraft keeps your documents offline.".into(); Ok(json!({"available": false})) }) .pure(), ] } fn authors(a: &str) -> Vec<(String, String)> { a.split(';') .map(str::trim) .filter(|x| !x.is_empty()) .map(|x| match x.split_once(',') { Some((last, first)) => (last.trim().to_string(), first.trim().to_string()), None => match x.rsplit_once(' ') { Some((first, last)) => (last.trim().to_string(), first.trim().to_string()), None => (x.to_string(), String::new()), }, }) .collect() } /// "Alex Mei" → "A. M." (`dots`), or "A M" without them. fn initials(first: &str, dots: bool) -> String { let sep = if dots { ". " } else { " " }; let mut out = first.split_whitespace().filter_map(|w| w.chars().next()).map(String::from).collect::>().join(sep); if dots && !out.is_empty() { out.push('.'); } out } fn name(form: Name, last: &str, first: &str) -> String { let join = |a: String, sep: &str, b: String| if a.is_empty() || b.is_empty() { format!("{a}{b}") } else { format!("{a}{sep}{b}") }; match form { Name::LastFirst => join(last.to_string(), ", ", first.to_string()), Name::FirstLast => join(first.to_string(), " ", last.to_string()), Name::LastInitials => join(last.to_string(), ", ", initials(first, true)), Name::InitialsLast => join(initials(first, true), " ", last.to_string()), Name::LastSpaceInitials => join(last.to_string(), " ", initials(first, true)), Name::UpperLastFirst => join(last.to_uppercase(), ", ", first.to_string()), Name::UpperLastBareInitials => join(last.to_uppercase(), " ", initials(first, false)), } } fn name_list(au: &[(String, String)], form: &Names) -> String { let shown = if form.max > 0 { au.get(..form.max).unwrap_or(au) } else { au }; let parts: Vec = shown.iter().enumerate().map(|(i, (l, f))| name(if i == 0 { form.first } else { form.rest }, l, f)).collect(); let mut out = match parts.as_slice() { [] => String::new(), [one] => one.clone(), [a, b] => format!("{a}{}{b}", form.two), [init @ .., z] => format!("{}{}{z}", init.join(form.sep), form.last), }; if shown.len() < au.len() { out.push_str(form.et_al); } out } /// Append `s`, dropping its leading full stop when `out` already ends with one ("M." + ". "). fn push_text(out: &mut String, s: &str) { match s.strip_prefix('.') { Some(rest) if out.ends_with('.') => out.push_str(rest), _ => out.push_str(s), } } /// Fill one template segment; `None` when `optional` and a field in it is empty. fn fill_segment(seg: &str, field: &dyn Fn(&str) -> String, optional: bool) -> Option { let mut out = String::new(); let mut rest = seg; while let Some((before, after)) = rest.split_once('{') { push_text(&mut out, before); let Some((key, after)) = after.split_once('}') else { push_text(&mut out, after); return Some(out); }; let value = field(key); if value.is_empty() && optional { return None; } push_text(&mut out, &value); rest = after; } push_text(&mut out, rest); Some(out) } /// Fill an entry template (see [`CiteStyle`]). fn render(template: &str, field: &dyn Fn(&str) -> String) -> String { let mut out = String::new(); let mut rest = template; while !rest.is_empty() { let (seg, optional, after) = match rest.strip_prefix('⟦') { Some(group) => match group.split_once('⟧') { Some((g, after)) => (g, true, after), None => (group, true, ""), }, None => match rest.split_once('⟦') { Some((plain, _)) => (plain, false, rest.get(plain.len()..).unwrap_or("")), None => (rest, false, ""), }, }; if let Some(text) = fill_segment(seg, field, optional) { push_text(&mut out, &text); } rest = after; } out } /// In-text citation for a style; `n` is the source's number in numbered styles. pub fn cite(src: &Source, style_name: &str, n: usize, pages: &str) -> String { let st = style(style_name); let au = authors(&src.author); let lasts: Vec<&str> = au.iter().map(|a| a.0.as_str()).collect(); let who = match lasts.as_slice() { [] => src.title.clone(), [one] => one.to_string(), [first, ..] if lasts.len() >= st.et_al_from.max(2) => format!("{first} et al."), [a, b] => format!("{a} {} {b}", st.and), [init @ .., z] => format!("{} {} {z}", init.join(", "), st.and), }; match st.cite { Cite::AuthorPage if pages.is_empty() => format!("({who})"), Cite::AuthorPage => format!("({who} {pages})"), Cite::AuthorDate { year_sep, .. } if pages.is_empty() => format!("({who}{year_sep}{})", src.year), Cite::AuthorDate { year_sep, pages_sep } => format!("({who}{year_sep}{}{pages_sep}{pages})", src.year), Cite::Number { open, close, pages_sep: Some(sep) } if !pages.is_empty() => format!("{open}{n}{sep}{pages}{close}"), Cite::Number { open, close, .. } => format!("{open}{n}{close}"), } } /// GB/T 7714 document type code: M book, J journal article, R report, EB/OL web page, Z other; /// "/OL" marks a source read online. fn gb_type(src: &Source) -> String { let code = match src.kind.to_ascii_lowercase().as_str() { "website" | "web" => return "EB/OL".into(), _ if !src.journal.is_empty() => "J", "book" | "" => "M", "article" => "J", "report" => "R", _ => "Z", }; if src.url.is_empty() { code.into() } else { format!("{code}/OL") } } /// Bibliography entry for a style; `n` is the source's number in numbered styles. pub fn entry(src: &Source, style_name: &str, n: usize) -> String { let st = style(style_name); let au = authors(&src.author); let field = |key: &str| -> String { match key { "n" => n.to_string(), "names" => name_list(&au, &st.names), "year" if src.year.is_empty() => "n.d.".into(), "year" => src.year.clone(), "title" => src.title.clone(), "city" => src.city.clone(), "publisher" => src.publisher.clone(), "pub" => [src.city.as_str(), src.publisher.as_str()].into_iter().filter(|x| !x.is_empty()).collect::>().join(": "), "journal" => src.journal.clone(), "volume" => src.volume.clone(), "pages" => src.pages.clone(), "url" => src.url.clone(), "type" => gb_type(src), _ => String::new(), } }; render(if src.journal.is_empty() { st.book } else { st.article }, &field) } /// The tag a new source gets, as Word makes it: the first three letters of the first author's /// name and the last two digits of the year (`Smi20`), with `1`, `2`… added while it is taken. fn auto_tag(doc: &Document, src: &Source) -> String { let base = auto_tag_base(src); let taken = |t: &str| doc.sources.iter().any(|x| x.tag == t); if !taken(&base) { return base; } (1u32..).map(|n| format!("{base}{n}")).find(|t| !taken(t)).unwrap_or(base) } /// The author of a source for matching untagged entries: the editor when there is no author. #[cfg(not(target_arch = "wasm32"))] fn by_author(x: &Source) -> &str { if x.author.is_empty() { x.editor.as_str() } else { x.author.as_str() } } /// The stem of a new source's tag, before `1`, `2`… are added while it is taken: the first three /// alphanumerics of the first author's name (nothing of the author's, `Src`) and the last two /// digits of the year. fn auto_tag_base(src: &Source) -> String { let name: String = authors(&src.author).first().map(|x| x.0.clone()).unwrap_or_default().chars().filter(|c| c.is_alphanumeric()).take(3).collect(); let name = if name.is_empty() { "Src".to_string() } else { name }; let digits: Vec = src.year.chars().filter(char::is_ascii_digit).collect(); let year: String = digits.get(digits.len().saturating_sub(2)..).unwrap_or_default().iter().collect(); format!("{name}{year}") } /// Manage Sources: applies `add`, `remove` and `import` (in that order) and returns the /// document's sources. `import` reads a Word bibliography file (`b:Sources`, #2640). fn sources(s: &mut Session, v: &Value) -> CmdResult { if let Some(a) = v.get("add") { let mut src: Source = serde_json::from_value(a.clone()).map_err(|e| CmdError::Params(e.to_string()))?; // A new source's tag is made from its author and year; an edit keeps the tag it has. if src.tag.is_empty() { src.tag = auto_tag(&s.doc, &src); } // Edit Source keeps the source's place in the list and refreshes its citations. match s.doc.sources.iter().position(|x| x.tag == src.tag) { Some(i) => { if let Some(x) = s.doc.sources.get_mut(i) { *x = src; } update_citations(s)?; } None => s.doc.sources.push(src), } s.touch(); } if let Some(t) = p::str(v, "remove") { s.doc.sources.retain(|x| x.tag != t); } if let Some(path) = p::str(v, "import") { import_sources(s, path)?; } Ok(serde_json::to_value(&s.doc.sources).unwrap_or(Value::Null)) } /// The largest bibliography sources file imported from disk. #[cfg(not(target_arch = "wasm32"))] const MAX_SOURCES_FILE: u64 = 32 << 20; /// Import the sources of a Word bibliography file (`b:Sources`: Word's own `Sources.xml`) into /// this document (#2640). A tag already here is left alone — an import never overwrites an /// edited source; a source with no tag is matched to an existing one by title and author, and /// otherwise gets a tag the way a new source does. fn import_sources(s: &mut Session, path: &str) -> Result<(), CmdError> { #[cfg(target_arch = "wasm32")] { let _ = (s, path); return Err(CmdError::Failed("reading files by path isn't available on the web".into())); } #[cfg(not(target_arch = "wasm32"))] { // Through `io`, which keeps automation inside its read root (#769). let bytes = crate::io::read_file_capped(path, MAX_SOURCES_FILE, "sources file").map_err(CmdError::Failed)?; let file = wordcraft_docx::read_sources(&bytes).map_err(|e| CmdError::Failed(e.to_string()))?; let mut added = false; // The tags and (title, author-or-editor) keys already here, once: an import of thousands // of untagged sources must not rescan the list per source. Tags follow `auto_tag`: the // stem, then 1, 2… while taken. let mut tags: std::collections::HashSet = s.doc.sources.iter().map(|x| x.tag.clone()).collect(); let mut keys: std::collections::HashSet<(String, String)> = s.doc.sources.iter().map(|x| (x.title.clone(), by_author(x).to_string())).collect(); let mut next: std::collections::HashMap = std::collections::HashMap::new(); for mut src in file.sources { if s.doc.sources.len() >= wordcraft_docx::MAX_SOURCES { break; } if src.tag.is_empty() { // A source with no tag is matched to one already here by its title and author (or // editor), as repeated parts of a document are; otherwise it gets a tag the way a // new source does. if keys.contains(&(src.title.clone(), by_author(&src).to_string())) { continue; } let base = auto_tag_base(&src); let n = next.entry(base.clone()).or_insert(0); let mut tag = if *n == 0 { base.clone() } else { format!("{base}{}", *n) }; while tags.contains(&tag) { *n += 1; tag = format!("{base}{}", *n); } *n = n.saturating_add(1); src.tag = tag; } if !tags.insert(src.tag.clone()) { continue; } keys.insert((src.title.clone(), by_author(&src).to_string())); s.doc.sources.push(src); added = true; } if added { s.touch(); } Ok(()) } } fn citation(s: &mut Session, v: &Value) -> CmdResult { if v.get("source").is_some() { sources(s, &json!({"add": v.get("source")}))?; } let tag = match p::str(v, "tag") { Some(t) => t.to_string(), None => match v.get("source") { Some(_) => s.doc.sources.last().map(|x| x.tag.clone()).unwrap_or_default(), None => return Err(CmdError::Params("give `tag` or `source`".into())), }, }; let src = s.doc.sources.iter().find(|x| x.tag == tag).cloned().ok_or_else(|| CmdError::Params(format!("no source `{tag}`")))?; let pages = p::str(v, "pages").unwrap_or("").to_string(); let st = style(&s.bib_style); let n = number_of(&s.doc, &bib_order(&s.doc, st, super::default_lang(s)), &tag); let props = s.typing_props(); let at = delete_selection(s)?; let instr = if pages.is_empty() { format!("CITATION {tag}") } else { format!("CITATION {tag} \\p {pages}") }; let end = s.doc.insert_object( &at, InlineObject::Field { instr, result: cite(&src, st.name, n, &pages), locked: false, dirty: false, code: false, form: String::new() }, &props, )?; s.sel = Selection::caret(end); // A new citation can renumber the others (numbered styles count in order of first citation). if st.numbered() { refresh_citations(s)?; } Ok(json!({"tag": tag})) } /// The tag and `\p` pages of a CITATION field instruction. fn citation_field(instr: &str) -> Option<(&str, &str)> { let mut words = instr.split_whitespace(); if words.next()? != "CITATION" { return None; } let tag = words.next()?; let pages = instr.split("\\p").nth(1).map(str::trim).unwrap_or(""); Some((tag, pages)) } /// Tags cited in the body, in order of first citation. fn cited_tags(doc: &Document) -> Vec { let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); for path in doc.para_paths(StoryRef::Body) { let Some(p) = doc.para(StoryRef::Body, &path) else { continue }; for o in &p.objects { if let InlineObject::Field { instr, .. } = o && let Some((tag, _)) = citation_field(instr) && seen.insert(tag.to_string()) { out.push(tag.to_string()); } } } out } fn author_key(src: &Source) -> String { authors(&src.author).first().map(|a| a.0.to_lowercase()).unwrap_or_else(|| src.title.to_lowercase()) } /// Indices into `doc.sources` in bibliography order: the cited sources (every source while /// nothing is cited), sorted or in order of first citation as the style asks. fn bib_order(doc: &Document, st: &CiteStyle, lang: Option) -> Vec { let cited = cited_tags(doc); let mut idx: Vec = if cited.is_empty() { (0..doc.sources.len()).collect() } else if st.order == Order::Cited { cited.iter().filter_map(|t| doc.sources.iter().position(|x| &x.tag == t)).collect() } else { let cited: std::collections::HashSet<&str> = cited.iter().map(String::as_str).collect(); doc.sources.iter().enumerate().filter(|(_, x)| cited.contains(x.tag.as_str())).map(|(i, _)| i).collect() }; // Sorted in the document's language (Polish authors `Łukasiewicz` before `Mazur`). let key = |i: &usize, by_title: bool| { sort_key(&doc.sources.get(*i).map(|x| if by_title { x.title.clone() } else { author_key(x) }).unwrap_or_default(), lang.as_deref()) }; match st.order { Order::Author => idx.sort_by_cached_key(|i| key(i, false)), Order::Title => idx.sort_by_cached_key(|i| key(i, true)), Order::Cited => {} } idx } /// A source's number in a numbered style: its place in the bibliography order. fn number_of(doc: &Document, order: &[usize], tag: &str) -> usize { order.iter().position(|&i| doc.sources.get(i).is_some_and(|x| x.tag == tag)).unwrap_or(order.len()).saturating_add(1) } /// Refresh CITATION results and generated lists. pub fn update_citations(s: &mut Session) -> Result<(), CmdError> { refresh_citations(s)?; update_generated(s) } /// Refresh the results of the CITATION fields in the body. fn refresh_citations(s: &mut Session) -> Result<(), CmdError> { let st = style(&s.bib_style); let order = bib_order(&s.doc, st, super::default_lang(s)); for path in s.doc.para_paths(StoryRef::Body) { let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue }; let updates: Vec<(usize, String)> = p .objects .iter() .enumerate() .filter_map(|(k, o)| match o { InlineObject::Field { instr, .. } => { let (tag, pages) = citation_field(instr)?; let src = s.doc.sources.iter().find(|x| x.tag == tag)?; Some((k, cite(src, st.name, number_of(&s.doc, &order, tag), pages))) } _ => None, }) .collect(); if updates.is_empty() { continue; } let para = s.doc.para_mut(StoryRef::Body, &path)?; for (k, r) in updates { if let Some(InlineObject::Field { result, .. }) = para.objects.get_mut(k) { *result = r; } } para.touch(); } Ok(()) } /// The TOC field for `references.tableOfFigures` (ECMA-376 §17.16.5.68): `\c "