SPB Git

Repository Public

CitationEngine.swift 14.3 KB 269 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReferences/CitationEngine.swift3// Description: The citation engine: style catalogue, in-text citations (author-date, author-page, numeric with range collapsing),4//              year-suffix disambiguation, bibliography ordering and the generated bibliography paragraphs.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011public struct CitationStyleInfo: Sendable, Identifiable, Hashable {12    public enum Kind: String, Sendable, Hashable { case authorDate, numeric, authorPage }13    public var id: String14    public var name: String15    public var kind: Kind16    public var summary: String17    public init(id: String, name: String, kind: Kind, summary: String) { self.id = id; self.name = name; self.kind = kind; self.summary = summary }18}1920public struct CitationEngine: CitationFormatting {21    public static let styles: [CitationStyleInfo] = [22        CitationStyleInfo(id: "apa", name: "APA 7th edition", kind: .authorDate, summary: "(Grady et al., 2019, p. 4); reference list in alphabetical order."),23        CitationStyleInfo(id: "chicago-author-date", name: "Chicago 17th edition (author-date)", kind: .authorDate, summary: "(Grazer and Fishman 2015, 12); reference list in alphabetical order."),24        CitationStyleInfo(id: "mla", name: "MLA 9th edition", kind: .authorPage, summary: "(Baron 194); works cited in alphabetical order."),25        CitationStyleInfo(id: "ieee", name: "IEEE", kind: .numeric, summary: "[1], [3]–[5]; references numbered in order of first citation."),26        CitationStyleInfo(id: "numeric", name: "Numeric", kind: .numeric, summary: "[1, 3–5]; references numbered in order of first citation."),27        CitationStyleInfo(id: "vancouver", name: "Vancouver (ICMJE / NLM)", kind: .numeric, summary: "(1,3–5); references numbered in order of first citation."),28    ]2930    /// The style in use; an unknown identifier falls back to "apa".31    public let styleID: String32    /// Language of the connecting terms ("en", "fr-CA"…). When nil, the document's `meta.language` is used; previews default to English.33    public let language: String?34    let kind: StyleKind3536    public init(styleID: String) { self.init(styleID: styleID, language: nil) }37    public init(styleID: String, language: String?) {38        let k = StyleKind(rawValue: styleID.lowercased()) ?? .apa39        self.kind = k; self.styleID = k.rawValue; self.language = language40    }41    public init(document: DocumentModel) { self.init(styleID: document.settings.citationStyle, language: document.meta.language) }4243    public var info: CitationStyleInfo { CitationEngine.styles.first { $0.id == styleID }! }44    var isNumeric: Bool { kind == .ieee || kind == .numeric || kind == .vancouver }4546    // MARK: Context (what depends on the whole set of cited works)4748    struct Context: Sendable {49        var cited: [String: BibEntry] = [:]50        /// Keys of the cited works in reference-list order.51        var order: [String] = []52        var rank: [String: Int] = [:]53        /// 1-based reference numbers (numeric styles): order of first citation among the works that exist.54        var number: [String: Int] = [:]55        /// Year suffixes ("a", "b") of works that share an in-text author label and a year.56        var suffix: [String: String] = [:]57        var label: [String: String] = [:]58        /// MLA: works whose author label is shared with another cited work and need a title in the citation.59        var needsTitle: Set<String> = []60    }6162    private final class Cache: @unchecked Sendable {63        struct Slot { var style: StyleKind; var french: Bool; var citedKeys: [String]; var bibliography: [BibEntry]; var context: Context }64        private let lock = NSLock()65        private var slots: [Slot] = []66        func lookup(_ style: StyleKind, _ french: Bool, _ citedKeys: [String], _ bibliography: [BibEntry]) -> Context? {67            lock.lock(); defer { lock.unlock() }68            // Array == returns at once when both sides share their storage, which is the case while the document value is unchanged.69            return slots.first { $0.style == style && $0.french == french && $0.citedKeys == citedKeys && $0.bibliography == bibliography }?.context70        }71        func store(_ slot: Slot) {72            lock.lock(); defer { lock.unlock() }73            slots.insert(slot, at: 0)74            if slots.count > 4 { slots.removeLast() }75        }76    }77    private static let cache = Cache()7879    private func terms(_ document: DocumentModel) -> Terms { Terms.forLanguage(language ?? document.meta.language) }8081    static func letters(_ index: Int) -> String {82        var n = index, s = ""83        repeat { s = String(UnicodeScalar(UInt8(97 + n % 26))) + s; n = n / 26 - 1 } while n >= 084        return s85    }8687    func context(document: DocumentModel, numbering: Numbering) -> Context {88        let t = terms(document)89        if let c = CitationEngine.cache.lookup(kind, t.french, numbering.citedKeys, document.bibliography) { return c }90        var ctx = Context()91        let wanted = Set(numbering.citedKeys)92        for e in document.bibliography where wanted.contains(e.key) && ctx.cited[e.key] == nil { ctx.cited[e.key] = e }93        let present = numbering.citedKeys.filter { ctx.cited[$0] != nil }94        let f = StyleFormatter(style: kind, t: t)95        if isNumeric {96            ctx.order = present97        } else {98            let keyed = present.map { ($0, f.sortKey(ctx.cited[$0]!)) }.sorted { $0.1 < $1.1 }99            ctx.order = keyed.map(\.0)100            var groups: [String: [String]] = [:]101            for key in ctx.order {102                let e = ctx.cited[key]!103                let label = f.label(e)104                ctx.label[key] = label105                let group = kind == .mla ? label : label + "\u{1F}" + (e.year.map(String.init) ?? Ref.literalDate(e) ?? "")106                groups[group, default: []].append(key)107            }108            for members in groups.values where members.count > 1 {109                if kind == .mla { ctx.needsTitle.formUnion(members) }110                else { for (n, key) in members.enumerated() { ctx.suffix[key] = CitationEngine.letters(n) } }111            }112        }113        for (n, key) in ctx.order.enumerated() { ctx.rank[key] = n; if isNumeric { ctx.number[key] = n + 1 } }114        CitationEngine.cache.store(.init(style: kind, french: t.french, citedKeys: numbering.citedKeys, bibliography: document.bibliography, context: ctx))115        return ctx116    }117118    // MARK: Locators119120    /// "12-14" → pages "12–14"; "pp. 12-14" → the same; "ch. 3" is a labelled locator and is kept verbatim.121    static func parseLocator(_ raw: String) -> (pages: String?, verbatim: String) {122        var s = raw.trimmingCharacters(in: .whitespaces)123        let lower = s.lowercased()124        for prefix in ["pp.", "pp ", "p.", "p ", "pages ", "page "] where lower.hasPrefix(prefix) {125            s = String(s.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces)126            return (Ref.enDashRanges(s), raw)127        }128        // Bare numbers, roman numerals and ranges are pages.129        let bare = !s.isEmpty && s.allSatisfy { $0.isNumber || "ivxlcdmIVXLCDM".contains($0) || "-–, ".contains($0) }130        return bare ? (Ref.enDashRanges(s), raw) : (nil, s)131    }132133    private func locatorText(_ raw: String?, _ t: Terms) -> String? {134        guard let raw, !raw.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }135        let (pages, verbatim) = CitationEngine.parseLocator(raw)136        guard let pages else { return verbatim }137        if kind == .chicago || kind == .mla { return pages }138        let many = pages.contains("–") || pages.contains(",") || pages.contains("-")139        return (many ? t.pages : t.page) + " " + pages140    }141142    private func withAffixes(_ body: String, _ item: CitationItem) -> String {143        var s = body144        if let p = item.prefix?.trimmingCharacters(in: .whitespaces), !p.isEmpty { s = p + " " + s }145        if let x = item.suffix, !x.trimmingCharacters(in: .whitespaces).isEmpty {146            let trimmed = x.trimmingCharacters(in: .whitespaces)147            s += (trimmed.first.map { ",;:.)".contains($0) } ?? false) ? trimmed : " " + trimmed148        }149        return s150    }151152    private func hasAffix(_ i: CitationItem) -> Bool {153        !(i.prefix ?? "").trimmingCharacters(in: .whitespaces).isEmpty || !(i.suffix ?? "").trimmingCharacters(in: .whitespaces).isEmpty154    }155156    // MARK: CitationFormatting157158    public func citationText(_ citation: Citation, document: DocumentModel, numbering: Numbering) -> String {159        guard !citation.items.isEmpty else { return "" }160        let t = terms(document)161        let ctx = context(document: document, numbering: numbering)162        return isNumeric ? numericCitation(citation, ctx, t) : authorCitation(citation, ctx, t)163    }164165    private func numericCitation(_ citation: Citation, _ ctx: Context, _ t: Terms) -> String {166        let open = kind == .vancouver ? "(" : "[", close = kind == .vancouver ? ")" : "]"167        let simple = citation.items.allSatisfy { !hasAffix($0) && ($0.locator ?? "").trimmingCharacters(in: .whitespaces).isEmpty }168        if !simple {169            let parts = citation.items.map { item -> String in170                var body = ctx.number[item.key].map(String.init) ?? "?" + item.key171                if let l = locatorText(item.locator, t) { body += ", " + l }172                return withAffixes(body, item)173            }174            return kind == .ieee ? parts.map { open + $0 + close }.joined(separator: ", ") : open + parts.joined(separator: "; ") + close175        }176        var numbers: [Int] = [], missing: [String] = []177        for item in citation.items {178            if let n = ctx.number[item.key] { if !numbers.contains(n) { numbers.append(n) } } else if !missing.contains(item.key) { missing.append(item.key) }179        }180        numbers.sort()181        var runs: [(Int, Int)] = []182        for n in numbers {183            if let last = runs.last, last.1 + 1 == n { runs[runs.count - 1].1 = n } else { runs.append((n, n)) }184        }185        var parts: [String] = []186        for (a, b) in runs {187            if kind == .ieee {188                if b - a >= 2 { parts.append("[\(a)]–[\(b)]") } else { parts += (a...b).map { "[\($0)]" } }189            } else {190                if b - a >= 2 { parts.append("\(a)–\(b)") } else { parts += (a...b).map(String.init) }191            }192        }193        parts += missing.map { kind == .ieee ? "[?\($0)]" : "?\($0)" }194        if kind == .ieee { return parts.joined(separator: ", ") }195        return open + parts.joined(separator: kind == .vancouver ? "," : ", ") + close196    }197198    private func authorCitation(_ citation: Citation, _ ctx: Context, _ t: Terms) -> String {199        var items = citation.items200        if kind == .apa, items.count > 1, !items.contains(where: hasAffix) {201            // APA orders the works inside one parenthesis as in the reference list. Kept as typed when a prefix or suffix is attached.202            items = items.enumerated().sorted { a, b in203                let ra = ctx.rank[a.element.key] ?? Int.max, rb = ctx.rank[b.element.key] ?? Int.max204                return ra != rb ? ra < rb : a.offset < b.offset205            }.map(\.element)206        }207        var groups: [String] = []208        var previousLabel: String?209        var previousOpen = false       // the previous item can take another year after a comma210        for item in items {211            guard let e = ctx.cited[item.key] else {212                groups.append(withAffixes("?" + item.key, item))213                previousLabel = nil214                continue215            }216            let label = ctx.label[item.key] ?? "?"217            let locator = locatorText(item.locator, t)218            let noPrefix = (item.prefix ?? "").trimmingCharacters(in: .whitespaces).isEmpty219            let noSuffix = (item.suffix ?? "").trimmingCharacters(in: .whitespaces).isEmpty220            if kind == .mla {221                var parts: [String] = []222                if !item.suppressAuthor { parts.append(label + (ctx.needsTitle.contains(item.key) ? ", " + StyleFormatter(style: kind, t: t).shortTitle(e) : "")) }223                else if ctx.needsTitle.contains(item.key) { parts.append(StyleFormatter(style: kind, t: t).shortTitle(e)) }224                if let locator { parts.append(locator) }225                if parts.isEmpty { parts.append(label) }226                groups.append(withAffixes(parts.joined(separator: " "), item))227                continue228            }229            let suffix = ctx.suffix[item.key]230            let dated = e.year != nil || Ref.literalDate(e) != nil231            var year: String232            if let y = e.year { year = String(y) + (suffix ?? "") }233            else if let l = Ref.literalDate(e) { year = l + (suffix.map { "-" + $0 } ?? "") }234            else { year = t.noDate + (suffix.map { "-" + $0 } ?? "") }235            if let locator { year += ", " + locator }236            if !item.suppressAuthor, noPrefix, previousOpen, previousLabel == label, !groups.isEmpty {237                groups[groups.count - 1] += ", " + withAffixes(year, item)238            } else if item.suppressAuthor {239                groups.append(withAffixes(year, item))240            } else {241                groups.append(withAffixes(label + (kind == .apa || !dated ? ", " : " ") + year, item))242            }243            previousLabel = item.suppressAuthor ? nil : label244            previousOpen = locator == nil && noSuffix245        }246        return "(" + groups.joined(separator: "; ") + ")"247    }248249    public func bibliographyParagraphs(document: DocumentModel, numbering: Numbering) -> [Paragraph] {250        let t = terms(document)251        let ctx = context(document: document, numbering: numbering)252        let f = StyleFormatter(style: kind, t: t)253        return ctx.order.map { key in254            let e = ctx.cited[key]!255            return Paragraph(id: "bib-" + key, style: StyleID.bibliography, runs: numberLabel(ctx.number[key]) + f.entry(e, suffix: ctx.suffix[key]).runs)256        }257    }258259    private func numberLabel(_ n: Int?) -> [Run] {260        guard isNumeric, let n else { return [] }261        return [Run(kind == .vancouver ? "\(n).\t" : "[\(n)]\t")]262    }263264    /// One formatted entry as runs (used by the citation manager preview). `number` is shown by the numeric styles only.265    public func formattedEntry(_ entry: BibEntry, number: Int?) -> [Run] {266        numberLabel(number) + StyleFormatter(style: kind, t: Terms.forLanguage(language ?? "en")).entry(entry, suffix: nil).runs267    }268}269
Files main
Menu

Theme