Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReferences/StyleFormatter.swift3// Description: Reference-list formatting for the built-in styles (APA 7, Chicago 17 author-date, MLA 9, IEEE, generic numeric, Vancouver),4// the in-text author labels and the sort keys. Hand-written from the published rules; this is not a CSL processor.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011enum StyleKind: String, Sendable { case apa, chicago = "chicago-author-date", mla, ieee, numeric, vancouver }1213struct StyleFormatter {14 let style: StyleKind15 let t: Terms1617 private static let ieeeMonths = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]18 private static let nlmMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]1920 func entry(_ e: BibEntry, suffix: String?) -> Rich {21 let r = Ref(e, terms: t)22 switch style {23 case .apa: return apa(r, suffix)24 case .chicago: return chicago(r, suffix)25 case .mla: return mla(r)26 case .ieee, .numeric: return ieee(r)27 case .vancouver: return vancouver(r)28 }29 }3031 // MARK: Shared pieces3233 private func quoted(_ title: String, closing: String) -> Rich {34 // A title inside quotation marks: its own double quotation marks become single ones.35 let inner = title.replacingOccurrences(of: "“", with: "‘").replacingOccurrences(of: "”", with: "’")36 var x = Rich("“")37 x.title(inner)38 if let l = x.last, l == "?" || l == "!" { x.add("”") } else { x.add(closing + "”") }39 return x40 }4142 private func sameAsAuthor(_ r: Ref, _ name: String?) -> Bool {43 guard let name, r.authors.count == 1, r.authors[0].isLiteral else { return false }44 return TextFold.fold(r.authors[0].literal!) == TextFold.fold(name)45 }4647 private func placeAndPublisher(_ r: Ref) -> String? {48 switch (r.f("publisher-place"), r.f("publisher")) {49 case let (p?, pub?): return p + ": " + pub50 case let (nil, pub?): return pub51 case let (p?, nil): return p52 default: return nil53 }54 }5556 private func pageLabel(_ r: Ref, pages: String) -> String { (r.pagesAreRange ? t.pages : t.page) + " " + pages }5758 private func season(_ r: Ref) -> String? { r.f("season") ?? r.e.month.flatMap { (1...12).contains($0) ? t.months[$0 - 1] : nil } }5960 // MARK: APA 76162 private func apaNames(_ names: [PersonName], truncated: Bool) -> String {63 let items = names.map(Names.invertedInitials)64 if items.count > 20 { return items.prefix(19).joined(separator: ", ") + ", . . . " + items.last! }65 if truncated { return items.joined(separator: ", ") + ", " + t.etAl }66 return Names.join(items, and: t.ampersand, t: t, commaForTwo: true)67 }6869 private func apaDate(_ r: Ref, _ suffix: String?) -> String {70 guard var s = r.yearText(suffix: suffix) else { return t.noDate + (suffix.map { "-" + $0 } ?? "") }71 if r.e.year != nil, let m = r.e.month, (1...12).contains(m), [.webpage, .periodical, .conference].contains(r.kind) {72 s += t.french ? ", " + (r.e.day.map { "\($0 == 1 ? "1er" : String($0)) " } ?? "") + t.months[m - 1]73 : ", " + t.months[m - 1] + (r.e.day.map { " \($0)" } ?? "")74 }75 return s76 }7778 private func apaGenre(_ r: Ref) -> String? {79 guard let g = r.f("genre") else { return nil }80 guard r.kind == .thesis, r.genreIsDefault else { return g }81 switch r.degree {82 case .doctoral: return t.french ? "Thèse de doctorat" : "Doctoral dissertation"83 case .masters: return t.french ? "Mémoire de maîtrise" : "Master’s thesis"84 case .other: return g85 }86 }8788 private func apa(_ r: Ref, _ suffix: String?) -> Rich {89 var author = Rich()90 if !r.authors.isEmpty { author.add(apaNames(r.authors, truncated: r.authorsTruncated)) }91 else if !r.editors.isEmpty, !r.isPart { author.add(apaNames(r.editors, truncated: false) + " (" + (r.editors.count == 1 ? t.ed : t.eds) + ")") }9293 // Title element94 var title = Rich()95 let genre = apaGenre(r)96 let unpublishedThesis = r.kind == .thesis && (genre.map { let g = TextFold.fold($0); return g.hasPrefix("unpublished") || g.contains("non publie") } ?? true)97 if let text = r.title {98 if r.isPart {99 title.title(text)100 } else {101 title.title(text, italic: true)102 var paren: [String] = [], bracket: String?103 if let ed = r.f("edition") { paren.append(t.edition(ed)) }104 switch r.kind {105 case .report:106 if let n = r.f("number") { paren.append((genre.map { $0 + " " } ?? "") + t.numberCap + " " + n) } else { bracket = genre }107 case .thesis:108 if let n = r.f("number") { paren.append("Publication " + t.numberCap + " " + n) }109 if let genre { bracket = unpublishedThesis ? genre : [genre, r.f("publisher")].compactMap { $0 }.joined(separator: ", ") }110 case .book:111 if let v = r.f("volume") { paren.append(t.volumeCap + " " + v) }112 default:113 bracket = genre114 }115 if !paren.isEmpty { title.add(" (" + paren.joined(separator: ", ") + ")") }116 if let bracket { title.add(" [" + bracket + "]") }117 }118 if t.french { title.period() } else { title.periodInsideQuote() }119 }120121 var out = Rich()122 let date = "(" + apaDate(r, suffix) + ")."123 if author.isEmpty {124 out.add(title)125 out.add((title.isEmpty ? "" : " ") + date)126 } else {127 author.period()128 out.add(author)129 out.add(" " + date)130 if !title.isEmpty { out.add(" "); out.add(title) }131 }132133 // Source element134 var s = Rich()135 switch r.kind {136 case .article, .periodical:137 if let c = r.container {138 s.title(c, italic: true)139 let issue = r.f("issue") ?? r.f("number")140 if let v = r.f("volume") {141 s.add(", "); s.italic(v)142 if let issue { s.add("(\(issue))") }143 } else if let issue { s.add(", (\(issue))") }144 if let p = r.pages() { s.add(", " + p) } else if let a = r.f(ReferenceField.articleNumber) { s.add(", \(t.article) \(a)") }145 s.period()146 }147 case .chapter:148 s.add(t.inWord + " ")149 if !r.editors.isEmpty {150 s.add(Names.join(r.editors.map(Names.initialsFirst), and: t.ampersand, t: t) + " (" + (r.editors.count == 1 ? t.ed : t.eds) + "), ")151 }152 s.title(r.container ?? "", italic: true)153 var paren: [String] = []154 if let ed = r.f("edition") { paren.append(t.edition(ed)) }155 if let v = r.f("volume") { paren.append(t.volumeCap + " " + v) }156 if let p = r.pages() { paren.append(pageLabel(r, pages: p)) }157 if !paren.isEmpty { s.add(" (" + paren.joined(separator: ", ") + ")") }158 s.period()159 if let pub = r.f("publisher") { s.add(" " + pub); s.period() }160 case .thesis:161 if let src = unpublishedThesis ? r.f("publisher") : r.f("archive") { s.add(src); s.period() }162 case .webpage:163 if let site = r.container ?? r.f("publisher"), !sameAsAuthor(r, site) { s.add(site); s.period() }164 case .conference:165 let parts = [r.f("event-title"), r.f("event-place") ?? r.f("publisher-place")].compactMap { $0 }166 if !parts.isEmpty { s.add(parts.joined(separator: ", ")); s.period() }167 default:168 if let pub = r.f("publisher"), !sameAsAuthor(r, pub) { s.add(pub); s.period() }169 }170 if !s.isEmpty { out.add(" "); out.add(s) }171172 if let d = r.doiURL { out.add(" "); out.link(d, to: d) }173 else if let u = r.url {174 out.add(" ")175 if r.kind == .webpage, r.e.year == nil, let a = r.accessed, let y = a.year {176 out.add("\(t.retrieved) \(t.longDate(y, a.month, a.day)), \(t.from) ")177 }178 out.link(u, to: u)179 }180 return out181 }182183 // MARK: Chicago 17 (author-date)184185 private func chicagoNames(_ names: [PersonName], truncated: Bool) -> String {186 let items = names.enumerated().map { $0.offset == 0 ? Names.invertedFull($0.element) : Names.full($0.element) }187 if items.count > 10 { return items.prefix(7).joined(separator: ", ") + ", " + t.etAl }188 if truncated { return items.joined(separator: ", ") + ", " + t.etAl }189 return Names.join(items, and: t.and, t: t, commaForTwo: true)190 }191192 private func capitalised(_ s: String) -> String { s.prefix(1).uppercased() + s.dropFirst() }193194 private func chicago(_ r: Ref, _ suffix: String?) -> Rich {195 var out = Rich()196 if !r.authors.isEmpty { out.add(chicagoNames(r.authors, truncated: r.authorsTruncated)) }197 else if !r.editors.isEmpty, !r.isPart { out.add(chicagoNames(r.editors, truncated: false) + ", " + (r.editors.count == 1 ? "ed." : "eds.")) }198 let editorsUsed = r.authors.isEmpty && !r.isPart199 let year = r.yearText(suffix: suffix) ?? (t.noDate + (suffix.map { "-" + $0 } ?? ""))200201 var title = Rich()202 if let text = r.title {203 if r.isPart || r.kind == .thesis || r.kind == .webpage || r.kind == .conference { title = quoted(text, closing: ".") }204 else { title.title(text, italic: true); title.period() }205 }206 if out.isEmpty {207 out.add(title); out.add((title.isEmpty ? "" : " ") + year); out.period()208 } else {209 out.period(); out.add(" " + year); out.period()210 if !title.isEmpty { out.add(" "); out.add(title) }211 }212 func sentence(_ s: String?) { if let s, !s.isEmpty { out.add(" " + s); out.period() } }213214 switch r.kind {215 case .article:216 if let c = r.container {217 out.add(" "); out.title(c, italic: true)218 let issue = r.f("issue") ?? r.f("number"), when = season(r)219 var numbered = false220 if let v = r.f("volume") {221 out.add(" " + v); numbered = true222 if let issue { out.add(when != nil ? ", \(t.numberAbbrev) \(issue) (\(when!))" : " (\(issue))") }223 else if let when { out.add(" (\(when))") }224 } else if let issue {225 out.add(", \(t.numberAbbrev) \(issue)" + (when.map { " (\($0))" } ?? "")); numbered = true226 }227 if let p = r.pages() ?? r.f(ReferenceField.articleNumber) { out.add((numbered ? ": " : ", ") + p) }228 out.period()229 }230 case .periodical:231 if let c = r.container {232 out.add(" "); out.title(c, italic: true)233 if let y = r.e.year, r.e.month != nil { out.add(", " + t.longDate(y, r.e.month, r.e.day)) }234 out.period()235 }236 case .chapter:237 out.add(" " + t.inWord + " "); out.title(r.container ?? "", italic: true)238 if let ed = r.f("edition") { out.add(", " + t.edition(ed)) }239 if !r.editors.isEmpty { out.add(", \(t.editedBy) " + Names.join(r.editors.map(Names.full), and: t.and, t: t)) }240 if let v = r.f("volume") { out.add(", \(t.volumeAbbrev) " + v) }241 if let p = r.pages() { out.add(", " + p) }242 out.period()243 sentence(placeAndPublisher(r))244 case .thesis:245 var g = r.f("genre")246 if r.genreIsDefault { g = r.degree == .doctoral ? (t.french ? "Thèse de doctorat" : "PhD diss.") : (t.french ? "Mémoire de maîtrise" : "Master’s thesis") }247 sentence([g, r.f("publisher")].compactMap { $0 }.joined(separator: ", "))248 case .webpage:249 if let site = r.container ?? r.f("publisher"), !sameAsAuthor(r, site) { sentence(site) }250 if r.e.year == nil, let a = r.accessed, let y = a.year { sentence("\(t.accessed) \(t.longDate(y, a.month, a.day))") }251 case .conference:252 sentence([r.f("event-title"), r.f("event-place") ?? r.f("publisher-place")].compactMap { $0 }.joined(separator: ", "))253 default:254 if let ed = r.f("edition") { sentence(t.edition(ed)) }255 if r.kind == .book, let v = r.f("volume") { sentence(t.volumeCap + " " + v) }256 if !editorsUsed, !r.editors.isEmpty { sentence(capitalised(t.editedBy) + " " + Names.join(r.editors.map(Names.full), and: t.and, t: t)) }257 let translators = r.names("translator")258 if !translators.isEmpty { sentence(capitalised(t.translatedBy) + " " + Names.join(translators.map(Names.full), and: t.and, t: t)) }259 if r.kind == .report {260 if let n = r.f("number") { sentence((r.f("genre").map { $0 + " " + t.numberAbbrev + " " } ?? t.numberCap + " ") + n) } else { sentence(r.f("genre")) }261 }262 let pub = placeAndPublisher(r)263 if !sameAsAuthor(r, r.f("publisher")) || r.f("publisher-place") != nil { sentence(pub) }264 }265 if let link = r.doiURL ?? r.url { out.add(" "); out.link(link, to: link); out.add(".") }266 else if let archive = r.f("archive") { sentence(archive) }267 return out268 }269270 // MARK: MLA 9271272 private func mlaNames(_ names: [PersonName], truncated: Bool) -> String {273 guard let first = names.first else { return "" }274 if names.count >= 3 || truncated { return Names.invertedFull(first) + ", " + t.etAl }275 if names.count == 2 { return Names.invertedFull(first) + (t.french ? " " : ", ") + t.and + " " + Names.full(names[1]) }276 return Names.invertedFull(first)277 }278279 private func mlaDate(_ r: Ref, full: Bool) -> String? {280 guard let y = r.e.year else { return r.literalDate }281 guard full else { return String(y) }282 if let m = r.e.month, (1...12).contains(m) { return (r.e.day.map { "\($0) " } ?? "") + t.shortMonths[m - 1] + " \(y)" }283 if let s = r.f("season") { return s + " \(y)" }284 return String(y)285 }286287 private func mla(_ r: Ref) -> Rich {288 var out = Rich()289 let translators = r.names("translator")290 var editorsUsed = false291 if !r.authors.isEmpty { out.add(mlaNames(r.authors, truncated: r.authorsTruncated)) }292 else if !r.editors.isEmpty, !r.isPart, translators.isEmpty {293 out.add(mlaNames(r.editors, truncated: false) + ", " + (r.editors.count == 1 ? t.editor : t.editors)); editorsUsed = true294 }295 if !out.isEmpty { out.period() }296 if let text = r.title {297 if !out.isEmpty { out.add(" ") }298 if r.isPart || r.kind == .webpage { out.add(quoted(text, closing: ".")) } else { out.title(text, italic: true); out.period() }299 }300 let link = r.doiURL ?? r.url301 let archive = r.f("archive")302303 if r.kind == .thesis {304 if let y = mlaDate(r, full: false) { out.add(" " + y); out.period() }305 var g = r.f("genre")306 if r.genreIsDefault { g = r.degree == .doctoral ? "PhD dissertation" : "Master’s thesis" }307 let tail = [r.f("publisher"), g].compactMap { $0 }.joined(separator: ", ")308 if !tail.isEmpty { out.add(" " + tail); out.period() }309 if let link { out.add(" "); out.link(link, to: link); out.add(".") }310 return out311 }312313 var elements: [Rich] = []314 func el(_ s: String?) { if let s, !s.isEmpty { elements.append(Rich(s)) } }315 if r.isPart || r.kind == .webpage, let c = r.container { var x = Rich(); x.title(c, italic: true); elements.append(x) }316 if !translators.isEmpty { el(t.translatedBy + " " + Names.join(translators.map(Names.full), and: t.and, t: t)) }317 if !editorsUsed, !r.editors.isEmpty { el(t.editedBy + " " + Names.join(r.editors.map(Names.full), and: t.and, t: t)) }318 if let ed = r.f("edition") { el(t.edition(ed)) }319 if let v = r.f("volume") { el(t.volumeAbbrev + " " + v) }320 if r.kind == .article || r.kind == .periodical, let i = r.f("issue") ?? r.f("number") { el(t.numberAbbrev + " " + i) }321 if r.kind != .article, r.kind != .periodical, let pub = r.f("publisher"), pub != r.container, !sameAsAuthor(r, pub) { el(pub) }322 el(mlaDate(r, full: r.kind == .article || r.kind == .periodical || r.kind == .webpage))323 if r.isPart, let p = r.pages(enDash: false) { el(pageLabel(r, pages: p)) }324 if archive == nil, let link { var x = Rich(); x.link(link, to: link); elements.append(x) }325326 if !elements.isEmpty {327 out.add(" ")328 for (n, e) in elements.enumerated() {329 if n > 0 { out.add(", ") }330 if n == 0, e.segs.first?.props == CharProps.none, let first = e.plain.first, first.isLowercase { out.add(capitalised(e.plain)) } else { out.add(e) }331 }332 out.period()333 }334 if let archive {335 out.add(" "); out.italic(archive)336 if let link { out.add(", "); out.link(link, to: link) }337 out.period()338 }339 if r.kind == .webpage, r.e.year == nil, let a = r.accessed, let y = a.year {340 let d = (a.day.map { "\($0) " } ?? "") + (a.month.map { t.shortMonths[$0 - 1] + " " } ?? "") + String(y)341 out.add(" \(t.accessed) \(d).")342 }343 return out344 }345346 // MARK: IEEE (also the body of the generic numeric style)347348 private func ieeeNames(_ names: [PersonName], truncated: Bool) -> String {349 let items = names.map(Names.initialsFirst)350 if items.count > 6 { return items[0] + " " + t.etAl }351 if truncated { return items.joined(separator: ", ") + " " + t.etAl }352 return Names.join(items, and: t.and, t: t)353 }354355 private func ieeeDate(_ r: Ref, day: Bool = false) -> String? {356 guard let y = r.e.year else { return r.literalDate }357 guard let m = r.e.month, (1...12).contains(m) else { return String(y) }358 let month = t.french ? t.shortMonths[m - 1] : StyleFormatter.ieeeMonths[m - 1]359 if day, let d = r.e.day { return "\(month) \(d), \(y)" }360 return "\(month) \(y)"361 }362363 private func ieee(_ r: Ref) -> Rich {364 var out = Rich()365 if !r.authors.isEmpty { out.add(ieeeNames(r.authors, truncated: r.authorsTruncated)) }366 else if !r.editors.isEmpty, !r.isPart { out.add(ieeeNames(r.editors, truncated: false) + ", " + (r.editors.count == 1 ? "Ed." : "Eds.")) }367 let journal = style == .ieee ? (r.f("container-title-short") ?? r.container) : r.container368369 if r.kind == .webpage {370 // First Name Initial(s) Last Name. “Page Title.” Website Title. Accessed: Date. [Online.] Available: URL371 if !out.isEmpty { out.period(); out.add(" ") }372 if let text = r.title { out.add(quoted(text, closing: ".")) }373 if let site = r.container ?? r.f("publisher"), !sameAsAuthor(r, site) { out.add(" " + site); out.period() }374 if let a = r.accessed, let y = a.year {375 let d = a.month.map { StyleFormatter.ieeeMonths[$0 - 1] + (a.day.map { " \($0)," } ?? "") + " \(y)" } ?? String(y)376 out.add(" Accessed: \(d).")377 }378 if let u = r.url { out.add(" [Online.] Available: "); out.link(u, to: u) }379 return out380 }381382 if !out.isEmpty { out.add(", ") }383 var rest: [Rich] = []384 func el(_ s: String?) { if let s, !s.isEmpty { rest.append(Rich(s)) } }385 let quotedKind = r.isPart || r.kind == .thesis || r.kind == .report || r.kind == .conference386387 if quotedKind {388 if let text = r.title { out.add(quoted(text, closing: ",")); out.add(" ") }389 switch r.kind {390 case .article, .periodical:391 if let journal { var x = Rich(); x.title(journal, italic: true); rest.append(x) }392 if let v = r.f("volume") { el("vol. " + v) }393 if let i = r.f("issue") ?? r.f("number") { el("no. " + i) }394 if let p = r.pages() { el(pageLabel(r, pages: p)) } else if let a = r.f(ReferenceField.articleNumber) { el("Art. no. " + a) }395 el(ieeeDate(r, day: r.kind == .periodical))396 case .chapter where r.isConferencePaper:397 var x = Rich("in "); x.title(r.container ?? "", italic: true); rest.append(x)398 el(r.f("event-place") ?? r.f("publisher-place"))399 el(ieeeDate(r)?.components(separatedBy: " ").last)400 if let p = r.pages() { el(pageLabel(r, pages: p)) }401 case .chapter:402 var x = Rich("in "); x.title(r.container ?? "", italic: true)403 if let v = r.f("volume") { x.add(", vol. " + v) }404 var endsWithEd = false405 if !r.editors.isEmpty { x.add(", " + ieeeNames(r.editors, truncated: false) + ", " + (r.editors.count == 1 ? "Ed." : "Eds.")); endsWithEd = true }406 if let ed = r.f("edition") { x.add(", " + t.edition(ed)); endsWithEd = false }407 // "…, J. S. Brake, Ed., New York…" but "…, 2nd ed. New York…" and "in Title. New York…"408 let imprint = [placeAndPublisher(r), r.e.year.map(String.init) ?? r.literalDate, r.pages().map { pageLabel(r, pages: $0) }].compactMap { $0 }409 if let first = imprint.first, r.f("publisher") != nil || r.f("publisher-place") != nil {410 x.add((endsWithEd ? ", " : (x.last == "." ? " " : ". ")) + first)411 rest.append(x)412 imprint.dropFirst().forEach { el($0) }413 } else {414 rest.append(x)415 imprint.forEach { el($0) }416 }417 case .thesis:418 var g = r.f("genre")419 if r.genreIsDefault { g = r.degree == .doctoral ? "Ph.D. dissertation" : "M.S. thesis" }420 el(g); el(r.f("publisher")); el(r.f("publisher-place")); el(r.e.year.map(String.init) ?? r.literalDate)421 case .report:422 el(r.f("publisher")); el(r.f("publisher-place"))423 var g = r.f("genre")424 if let known = g, TextFold.fold(known) == "technical report" { g = "Tech. Rep." }425 if let n = r.f("number") { el((g ?? "Rep.") + " " + n) } else { el(g) }426 el(ieeeDate(r))427 default: // conference paper without proceedings428 if let ev = r.f("event-title") { el("presented at the " + ev) }429 el(r.f("event-place") ?? r.f("publisher-place"))430 el(ieeeDate(r))431 }432 } else {433 var x = Rich()434 if let text = r.title { x.title(text, italic: true) }435 if let ed = r.f("edition") { x.add((x.isEmpty ? "" : ", ") + t.edition(ed)) }436 if let pp = placeAndPublisher(r), !(sameAsAuthor(r, r.f("publisher")) && r.f("publisher-place") == nil) {437 if !x.isEmpty { x.add(x.last == "." ? " " : ". ") }438 x.add(pp)439 }440 if !x.isEmpty { rest.append(x) }441 el(r.e.year.map(String.init) ?? r.literalDate)442 }443 if let d = r.doi { var x = Rich("doi: "); x.link(d, to: "https://doi.org/" + d); rest.append(x) }444 for (n, e) in rest.enumerated() { if n > 0 { out.add(", ") }; out.add(e) }445 out.period()446 if r.doi == nil, let u = r.url { out.add(" [Online]. Available: "); out.link(u, to: u) }447 return out448 }449450 // MARK: Vancouver (ICMJE / NLM)451452 private func vancouverNames(_ names: [PersonName], truncated: Bool) -> String {453 let items = names.map(Names.vancouver)454 if items.count > 6 { return items.prefix(6).joined(separator: ", ") + ", " + t.etAl }455 return items.joined(separator: ", ") + (truncated ? ", " + t.etAl : "")456 }457458 private func nlmDate(_ p: RefDate.Parts) -> String {459 guard let y = p.year else { return "" }460 return String(y) + (p.month.map { " " + StyleFormatter.nlmMonths[$0 - 1] + (p.day.map { " \($0)" } ?? "") } ?? "")461 }462463 private func vancouver(_ r: Ref) -> Rich {464 var out = Rich()465 func sentence(_ s: String?) { if let s, !s.isEmpty { out.add((out.isEmpty ? "" : " ") + s); out.period() } }466 let plainTitle = r.title.map(TextFold.stripMarkup)467 let pages = r.pages(enDash: false)?.replacingOccurrences(of: "–", with: "-")468 let year = r.e.year.map(String.init) ?? r.literalDate469 func imprint(_ date: String?) -> String? {470 let pp = placeAndPublisher(r)471 switch (pp, date) {472 case let (a?, b?): return a + "; " + b473 case let (a?, nil): return a474 case let (nil, b?): return b475 default: return nil476 }477 }478 if !r.authors.isEmpty { sentence(vancouverNames(r.authors, truncated: r.authorsTruncated)) }479 else if !r.editors.isEmpty, !r.isPart { sentence(vancouverNames(r.editors, truncated: false) + ", " + (r.editors.count == 1 ? t.editor : t.editors)) }480481 switch r.kind {482 case .article, .periodical:483 sentence(plainTitle)484 if let j = r.f("container-title-short") ?? r.container { sentence(j.hasSuffix(".") ? String(j.dropLast()) : j) }485 var s = nlmDate(RefDate.Parts(year: r.e.year, month: r.e.month, day: r.e.day))486 if s.isEmpty { s = year ?? "" }487 let issue = r.f("issue") ?? r.f("number")488 if r.f("volume") != nil || issue != nil { s += ";" + (r.f("volume") ?? "") + (issue.map { "(\($0))" } ?? "") }489 if let p = pages ?? r.f(ReferenceField.articleNumber) { s += ":" + p }490 sentence(s)491 if let d = r.doi { out.add(" doi: "); out.link(d, to: "https://doi.org/" + d); out.period() }492 case .chapter:493 sentence(plainTitle)494 var s = t.inWord + ":"495 if !r.editors.isEmpty { s += " " + vancouverNames(r.editors, truncated: false) + ", " + (r.editors.count == 1 ? t.editor : t.editors) + "." }496 sentence(s + " " + TextFold.stripMarkup(r.container ?? ""))497 if let ed = r.f("edition") { sentence(t.edition(ed)) }498 sentence(imprint(year))499 if let p = pages { sentence("p. " + p) }500 case .thesis:501 var g = r.f("genre")502 if r.genreIsDefault { g = r.degree == .doctoral ? "dissertation" : "master’s thesis" }503 sentence((plainTitle ?? "") + (g.map { " [\($0)]" } ?? ""))504 sentence(imprint(year))505 case .webpage:506 sentence((plainTitle ?? "") + " [Internet]")507 var date = year508 if let a = r.accessed, a.year != nil { date = (date.map { $0 + " " } ?? "") + "[cited \(nlmDate(a))]" }509 sentence(imprint(date))510 default:511 sentence(plainTitle)512 if let ed = r.f("edition") { sentence(t.edition(ed)) }513 sentence(imprint(year))514 if r.kind == .report, let n = r.f("number") { sentence("Report No.: " + n) }515 }516 if let u = r.url, !((r.kind == .article || r.kind == .periodical) && r.doi != nil) {517 out.add(" Available from: "); out.link(u, to: u)518 if u.hasSuffix("/") { out.add(".") } // NLM: a full stop follows a URL only when it ends with a slash519 }520 return out521 }522523 // MARK: In-text labels and sorting524525 /// The author part of an in-text citation ("Grady et al.", "Grazer and Fishman"), or the title when the work has no author.526 func label(_ e: BibEntry) -> String {527 let r = Ref(e, terms: t)528 let people = !r.authors.isEmpty ? r.authors : (r.isPart ? [] : r.editors)529 let truncated = !r.authors.isEmpty && r.authorsTruncated530 guard let first = people.first else {531 guard let title = (r.f("title-short") ?? r.title).map(TextFold.stripMarkup) else { return "?" }532 return r.isPart || r.kind == .webpage && style != .apa ? "“\(title)”" : title533 }534 let names = people.map(Names.display)535 let etAl = Names.display(first) + " " + t.etAl536 if truncated { return etAl }537 switch style {538 case .apa:539 return names.count == 1 ? names[0] : names.count == 2 ? names[0] + " " + t.ampersand + " " + names[1] : etAl540 case .chicago:541 return names.count <= 3 ? Names.join(names, and: t.and, t: t) : etAl542 default:543 return names.count <= 2 ? Names.join(names, and: t.and, t: t) : etAl544 }545 }546547 /// Short title used by MLA when several works share an author label.548 func shortTitle(_ e: BibEntry) -> String {549 let r = Ref(e, terms: t)550 let title = TextFold.stripMarkup(r.f("title-short") ?? r.title ?? "")551 return r.isPart || r.kind == .webpage ? "“\(title)”" : title552 }553554 struct SortKey: Comparable {555 var names: [String]556 var year: Int557 var title: String558 var key: String559 static func < (a: SortKey, b: SortKey) -> Bool {560 for (x, y) in zip(a.names, b.names) where x != y { return x < y }561 if a.names.count != b.names.count { return a.names.count < b.names.count }562 if a.year != b.year { return a.year < b.year }563 if a.title != b.title { return a.title < b.title }564 return a.key < b.key565 }566 }567568 private static let leadingArticles = ["a ", "an ", "the ", "le ", "la ", "les ", "l'", "l’", "un ", "une ", "des "]569 static func titleSortText(_ title: String) -> String {570 var s = TextFold.fold(TextFold.stripMarkup(title))571 for a in leadingArticles where s.hasPrefix(a) { s = String(s.dropFirst(a.count)); break }572 return String(s.filter { $0.isLetter || $0.isNumber || $0 == " " })573 }574575 /// Alphabetical order of the reference list: authors letter by letter ("nothing precedes something"), then year576 /// (undated works first, "in press" last; ignored by MLA), then title without its leading article.577 func sortKey(_ e: BibEntry) -> SortKey {578 let r = Ref(e, terms: t)579 let people = !r.authors.isEmpty ? r.authors : (r.isPart ? [] : r.editors)580 func name(_ n: PersonName) -> String {581 if n.isLiteral { return StyleFormatter.titleSortText(n.literal!) }582 let family = TextFold.fold(n.family).filter { $0.isLetter || $0.isNumber }583 return family + " " + TextFold.fold(Names.initials(n.givenAndSuffix.given, compact: true))584 }585 let title = StyleFormatter.titleSortText(r.title ?? "")586 let names = people.isEmpty ? [title] : people.map(name)587 let year = style == .mla ? 0 : (e.year ?? (r.literalDate != nil ? Int.max : Int.min))588 return SortKey(names: names, year: year, title: title, key: e.key)589 }590}591