SPB Git

Repository Public

NameParser.swift 6.7 KB 129 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReferences/NameParser.swift3// Description: BibTeX name-list parsing ("First von Last", "von Last, First", "von Last, Jr, First", "and others", braced corporate names)4//              and the inverse serialisation. Also the conventions the engine uses to fit name suffixes into `PersonName`.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011extension PersonName {12    /// Marker produced by BibTeX "and others": the list is known to be incomplete. Formatters render it as "et al.".13    public static let others = PersonName(family: "", given: "", literal: "others")14    public var isOthers: Bool { family.isEmpty && given.isEmpty && literal == "others" }15    /// True for an institutional name kept verbatim.16    public var isLiteral: Bool { !isOthers && !(literal ?? "").isEmpty }1718    /// `PersonName` has no suffix slot: a generational suffix is stored after the given name, "Martin Luther, Jr.".19    public var givenAndSuffix: (given: String, suffix: String?) {20        guard let r = given.range(of: ", ", options: .backwards) else { return (given, nil) }21        let suffix = String(given[r.upperBound...])22        return suffix.isEmpty ? (given, nil) : (String(given[..<r.lowerBound]), suffix)23    }24}2526public enum NameParser {27    /// Parses a BibTeX name list. `decode` converts one raw name part to display text (LaTeX decoding for .bib input).28    public static func parseList(_ raw: String, decode: (String) -> String = NameParser.stripBraces) -> [PersonName] {29        split(raw).compactMap { parseOne($0, decode: decode) }30    }3132    /// Serialises names in BibTeX syntax. `encode` escapes one name part (LaTeX encoding for .bib output).33    public static func string(_ names: [PersonName], encode: (String) -> String = { $0 }) -> String {34        names.map { n -> String in35            if n.isOthers { return "others" }36            if let l = n.literal, !l.isEmpty { return "{" + encode(l) + "}" }37            var family = encode(n.family)38            if n.family.contains(",") || n.family.range(of: " and ", options: .caseInsensitive) != nil { family = "{" + family + "}" }39            let (given, suffix) = n.givenAndSuffix40            if let suffix { return family + ", " + encode(suffix) + ", " + encode(given) }41            if given.isEmpty { return n.family.contains(" ") ? family + "," : family }42            return family + ", " + encode(given)43        }.joined(separator: " and ")44    }4546    public static func stripBraces(_ s: String) -> String {47        s.contains("{") || s.contains("}") ? s.replacingOccurrences(of: "{", with: "").replacingOccurrences(of: "}", with: "") : s48    }4950    /// Splits on the word "and" at brace depth 0.51    static func split(_ raw: String) -> [String] {52        let c = Array(raw)53        var parts: [String] = []54        var depth = 0, start = 0, i = 055        func isSpace(_ ch: Character) -> Bool { ch == " " || ch == "\n" || ch == "\t" || ch == "\r" || ch == "\r\n" || ch == "~" }56        while i < c.count {57            let ch = c[i]58            if ch == "{" { depth += 1 } else if ch == "}" { depth = max(0, depth - 1) }59            else if depth == 0, isSpace(ch), i + 4 < c.count, (c[i + 1] == "a" || c[i + 1] == "A"), (c[i + 2] == "n" || c[i + 2] == "N"),60                    (c[i + 3] == "d" || c[i + 3] == "D"), isSpace(c[i + 4]) {61                parts.append(String(c[start..<i]))62                i += 463                start = i + 164            }65            i += 166        }67        if start <= c.count { parts.append(String(c[min(start, c.count)...])) }68        return parts.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }69    }7071    private static func splitTopLevel(_ raw: String, isSeparator: (Character) -> Bool, keepEmpty: Bool) -> [String] {72        var parts: [String] = []73        var cur = ""74        var depth = 075        for ch in raw {76            if ch == "{" { depth += 1 } else if ch == "}" { depth = max(0, depth - 1) }77            if depth == 0, isSeparator(ch) {78                if keepEmpty || !cur.isEmpty { parts.append(cur) }79                cur = ""80            } else { cur.append(ch) }81        }82        if keepEmpty || !cur.isEmpty { parts.append(cur) }83        return parts84    }8586    private static func isFullyBraced(_ w: String) -> Bool {87        guard w.hasPrefix("{"), w.hasSuffix("}") else { return false }88        var depth = 089        var idx = w.startIndex90        while idx < w.endIndex {91            if w[idx] == "{" { depth += 1 } else if w[idx] == "}" { depth -= 1; if depth == 0, w.index(after: idx) != w.endIndex { return false } }92            idx = w.index(after: idx)93        }94        return true95    }9697    static func parseOne(_ raw: String, decode: (String) -> String) -> PersonName? {98        let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)99        guard !trimmed.isEmpty else { return nil }100        if trimmed.lowercased() == "others" { return .others }101        func clean(_ s: String) -> String {102            LaTeXText.collapse(decode(s).replacingOccurrences(of: "\u{00A0}", with: " "))103        }104        let parts = splitTopLevel(trimmed, isSeparator: { $0 == "," }, keepEmpty: true).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }105        if parts.count == 1 {106            let words = splitTopLevel(parts[0], isSeparator: { $0 == " " || $0 == "\n" || $0 == "\t" || $0 == "~" || $0 == "\r" || $0 == "\r\n" }, keepEmpty: false)107            if words.count == 1 {108                if isFullyBraced(words[0]), !words[0].hasPrefix("{\\") { return PersonName(family: "", given: "", literal: clean(String(words[0].dropFirst().dropLast()))) }109                return PersonName(family: clean(words[0]))110            }111            func isLower(_ w: String) -> Bool {112                if w.hasPrefix("{") && !w.hasPrefix("{\\") { return false }113                return clean(w).first(where: { $0.isLetter })?.isLowercase ?? false114            }115            let n = words.count116            if let k = (0..<(n - 1)).first(where: { isLower(words[$0]) }) {117                // Everything from the first lower-case word on is "von Last"; the particle stays with the family name.118                return PersonName(family: clean(words[k...].joined(separator: " ")), given: clean(words[..<k].joined(separator: " ")))119            }120            return PersonName(family: clean(words[n - 1]), given: clean(words[..<(n - 1)].joined(separator: " ")))121        }122        let family = clean(parts[0])123        if parts.count == 2 { return PersonName(family: family, given: clean(parts[1])) }124        let suffix = clean(parts[1])125        let given = clean(parts[2...].joined(separator: ", "))126        return PersonName(family: family, given: [given, suffix].filter { !$0.isEmpty }.joined(separator: ", "))127    }128}129
Files main
Menu

Theme