Sources/OrgCore/Links/Bibliography.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgCore/Links/Bibliography.swift

217 lines · 10260 bytes

12 symbols in this file
  1import Foundation
  2
  3/// An entry of a bibliography file, as Insert Citation… offers it and following a citation
  4/// shows it.
  5public struct BibEntry: Sendable, Equatable {
  6    public var key: String
  7    /// Field names in lower case; values as `org-cite-basic` reads them, braces kept.
  8    public var fields: [String: String]
  9    /// The bibliography file the entry is in.
 10    public var file: String
 11
 12    public init(key: String, fields: [String: String], file: String) {
 13        self.key = key
 14        self.fields = fields
 15        self.file = file
 16    }
 17
 18    public var author: String? { field("author") ?? field("editor") }
 19    public var title: String? { field("title") }
 20
 21    /// The `year` field, else the year of `date`, as `org-cite-basic--get-year` reads them.
 22    public var year: String? {
 23        if let year = field("year") { return year }
 24        return fields["date"].flatMap { $0.firstMatch(of: /^([0-9]{4})(?:[^0-9]|$)/) }.map { String($0.1) }
 25    }
 26
 27    /// A field without braces and with blanks collapsed; nil when missing or empty.
 28    public func field(_ name: String) -> String? {
 29        fields[name].flatMap(Self.clean)
 30    }
 31
 32    static func clean(_ value: String) -> String? {
 33        let clean = value.replacingOccurrences(of: "[{}]", with: "", options: .regularExpression)
 34            .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression).trimmingCharacters(in: .whitespaces)
 35        return clean.isEmpty ? nil : clean
 36    }
 37
 38    /// The line a chooser shows: the key, then the authors (`;` between them), the year and
 39    /// the title, as `org-cite-basic`'s completion table has them.
 40    public var label: String {
 41        [key, authors, year, title].compactMap { $0 }.joined(separator: "  ")
 42    }
 43
 44    /// The authors (else the editors) separated by `;`: split at each `and` outside braces.
 45    public var authors: String? {
 46        guard let raw = fields["author"] ?? fields["editor"] else { return nil }
 47        var names: [String] = []
 48        var current = ""
 49        var depth = 0
 50        var rest = Substring(raw)
 51        while let c = rest.first {
 52            if depth == 0, rest.hasPrefix(" and ") {
 53                names.append(current)
 54                current = ""
 55                rest = rest.dropFirst(5)
 56                continue
 57            }
 58            if c == "{" { depth += 1 } else if c == "}" { depth = max(0, depth - 1) }
 59            current.append(c)
 60            rest = rest.dropFirst()
 61        }
 62        names.append(current)
 63        let clean = names.compactMap(Self.clean)
 64        return clean.isEmpty ? nil : clean.joined(separator: "; ")
 65    }
 66
 67    /// Authors, year, title and where it was published, for showing the entry.
 68    public var summary: String {
 69        var parts: [String] = []
 70        let who = [author, year.map { "(\($0))" }].compactMap { $0 }.joined(separator: " ")
 71        if !who.isEmpty { parts.append(who) }
 72        if let title { parts.append(title) }
 73        if let from = field("journal") ?? field("journaltitle") ?? field("booktitle") ?? field("container-title") ?? field("publisher")
 74            ?? field("institution") ?? field("school") {
 75            parts.append(from)
 76        }
 77        return parts.map { $0.hasSuffix(".") ? $0 : $0 + "." }.joined(separator: " ")
 78    }
 79
 80    /// The `file` field's files: separated by `;`, each a path or JabRef's and Zotero's
 81    /// `description:path:type`, relative to the bibliography's folder unless absolute.
 82    public var files: [String] {
 83        guard let value = fields["file"] else { return [] }
 84        let folder = (file as NSString).deletingLastPathComponent
 85        return value.components(separatedBy: ";").compactMap { part in
 86            var path = part.trimmingCharacters(in: .whitespaces)
 87            if !FileManager.default.fileExists(atPath: OrgPaths.expandingTilde(path)), let m = path.firstMatch(of: /^[^:]*:(.+):[^:]*$/) {
 88                path = String(m.1)
 89            }
 90            path = path.replacingOccurrences(of: "\\:", with: ":")
 91            guard !path.isEmpty else { return nil }
 92            let expanded = OrgPaths.expandingTilde(path)
 93            return expanded.hasPrefix("/") ? expanded : ((folder as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
 94        }
 95    }
 96
 97    /// The DOI without a resolver in front.
 98    public var doi: String? {
 99        field("doi").map { $0.replacingOccurrences(of: "^(?:https?://(?:dx\\.)?doi\\.org/|doi:)", with: "", options: [.regularExpression, .caseInsensitive]) }
100    }
101
102    public var url: String? { field("url") }
103}
104
105/// Bibliography files (BibTeX, BibLaTeX and CSL-JSON) read for Insert Citation…, key
106/// completion and following citations.
107public enum Bibliography {
108    /// The files a buffer's `#+bibliography:` lines name, one each, quotes removed and
109    /// relative to `directory`, then the global ones, each once, as
110    /// `org-cite-list-bibliography-files` lists them.
111    public static func files(in text: String, directory: String?, global: [String] = []) -> [String] {
112        var files: [String] = []
113        if text.containsIgnoringASCIICase("#+bibliography") {
114            for m in text.matches(of: #/(?mi)^[ \t]*#\+bibliography:[ \t]*(.*?)[ \t]*$/#) {
115                var name = String(m.1)
116                if name.count > 1, name.hasPrefix("\""), name.hasSuffix("\"") { name = String(name.dropFirst().dropLast()) }
117                guard !name.isEmpty else { continue }
118                let path = OrgPaths.expandingTilde(name)
119                files.append(path.hasPrefix("/") ? path : ((directory ?? "/") as NSString).appendingPathComponent(path))
120            }
121        }
122        var seen = Set<String>()
123        return (files + global.map { OrgPaths.expandingTilde($0) }).filter { seen.insert($0).inserted }
124    }
125
126    /// The entries of a file: CSL-JSON for `.json`, BibTeX otherwise, with `@string`s expanded
127    /// and `crossref` fields filled in, sorted by key.
128    public static func entries(_ data: Data, path: String) -> [BibEntry] {
129        if (path as NSString).pathExtension.lowercased() == "json" {
130            return CiteProcessor.parseJSON(data).map { key, fields in
131                BibEntry(key: key, fields: Dictionary(fields.map { ($0.key.lowercased(), $0.value) }) { a, _ in a }, file: path)
132            }.sorted { $0.key < $1.key }
133        }
134        let parsed = resolvingCrossrefs(CiteProcessor.parseBibTeX(String(decoding: data, as: UTF8.self)))
135        return parsed.map { BibEntry(key: $0.key, fields: $0.value, file: path) }.sorted { $0.key < $1.key }
136    }
137
138    /// BibTeX's `crossref`: fields an entry lacks come from the entry it names; that entry's
139    /// `title` becomes `booktitle`, as BibLaTeX maps it.
140    static func resolvingCrossrefs(_ entries: [String: CiteProcessor.Entry]) -> [String: CiteProcessor.Entry] {
141        var result = entries
142        let lowered = Dictionary(entries.map { ($0.key.lowercased(), $0.value) }) { a, _ in a }
143        for (key, entry) in entries {
144            guard let target = entry["crossref"]?.trimmingCharacters(in: CharacterSet(charactersIn: "{} ")), let parent = lowered[target.lowercased()] else { continue }
145            var filled = entry
146            for (field, value) in parent where !["id", "type", "crossref"].contains(field) {
147                if field == "title" {
148                    if filled["booktitle"] == nil { filled["booktitle"] = value }
149                    if filled["title"] == nil { filled["title"] = value }
150                } else if filled[field] == nil {
151                    filled[field] = value
152                }
153            }
154            result[key] = filled
155        }
156        return result
157    }
158
159    /// The line (from 1) an entry starts on in a BibTeX file's text, or `"id"`'s object in a
160    /// CSL-JSON file, as `org-cite-basic-goto` finds it.
161    public static func line(of key: String, in text: String, json: Bool) -> Int? {
162        let quoted = NSRegularExpression.escapedPattern(for: key)
163        let pattern = json ? "\"id\":[ \\t]*\"\(quoted)\"" : "@[A-Za-z]+[ \\t\\n]*[{(][ \\t\\n]*\(quoted)[ \\t\\n]*,"
164        guard let range = text.range(of: pattern, options: .regularExpression) else { return nil }
165        return text[..<range.lowerBound].reduce(1) { $1 == "\n" ? $0 + 1 : $0 }
166    }
167}
168
169/// Parsed bibliography files kept by modification date, so a file is read again only when it
170/// changes.
171public final class BibliographyCache: @unchecked Sendable {
172    public static let shared = BibliographyCache()
173
174    private let lock = NSLock()
175    private var files: [String: (modified: Date, entries: [BibEntry])] = [:]
176    private let modified: (String) -> Date?
177    private let read: (String) -> Data?
178
179    public init(
180        modified: @escaping (String) -> Date? = { try? FileManager.default.attributesOfItem(atPath: $0)[.modificationDate] as? Date },
181        read: @escaping (String) -> Data? = { FileManager.default.contents(atPath: $0) }
182    ) {
183        self.modified = modified
184        self.read = read
185    }
186
187    /// The entries of `paths`, the first file's entry winning for a key in several. Files that
188    /// can't be read are left out. Reads files, so callers run it off the main thread.
189    public func entries(_ paths: [String]) -> [BibEntry] {
190        var seen = Set<String>()
191        var all: [BibEntry] = []
192        for path in paths {
193            for entry in entries(of: (path as NSString).resolvingSymlinksInPath, as: path) where seen.insert(entry.key).inserted { all.append(entry) }
194        }
195        return all
196    }
197
198    /// `entries` on another thread.
199    @concurrent
200    public func load(_ paths: [String]) async -> [BibEntry] {
201        entries(paths)
202    }
203
204    private func entries(of real: String, as path: String) -> [BibEntry] {
205        guard let date = modified(real) else { return [] }
206        lock.lock()
207        let cached = files[real]
208        lock.unlock()
209        if let cached, cached.modified == date { return cached.entries.map { var e = $0; e.file = path; return e } }
210        guard let data = read(real) else { return [] }
211        let parsed = Bibliography.entries(data, path: real)
212        lock.lock()
213        files[real] = (date, parsed)
214        lock.unlock()
215        return parsed.map { var e = $0; e.file = path; return e }
216    }
217}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form