Sources/OrgCore/MarkdownImport/MarkdownFrontMatter.swift

a15753a827b5ab7a0ccf3a0873890771c2979ee7
orgstar/Sources/OrgCore/MarkdownImport/MarkdownFrontMatter.swift

122 lines · 5918 bytes

  1import Foundation
  2
  3/// YAML front matter between `---` lines at the top of a Markdown file. Reads the subset notes
  4/// use: `key: value`, quoted strings, `[a, b]` and `- item` lists, and `|` and `>` blocks.
  5/// Nested maps are kept as `nested`.
  6enum MarkdownFrontMatter {
  7    enum Value: Equatable, Sendable {
  8        case scalar(String)
  9        case list([String])
 10        case nested
 11    }
 12
 13    /// The entries and the text after the front matter; no entries and the whole text when
 14    /// there is none.
 15    static func split(_ text: String) -> (entries: [(key: String, value: Value)], body: String) {
 16        guard text.hasPrefix("---") else { return ([], text) }
 17        let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map { $0.hasSuffix("\r") ? $0.dropLast() : $0 }
 18        guard lines.first?.trimmingCharacters(in: .whitespaces) == "---",
 19              let end = lines.dropFirst().firstIndex(where: { $0 == "---" || $0 == "..." }) else { return ([], text) }
 20        let body = lines[(end + 1)...].joined(separator: "\n")
 21        return (parse(lines[1..<end].map(String.init)), body)
 22    }
 23
 24    static func parse(_ lines: [String]) -> [(key: String, value: Value)] {
 25        var entries: [(key: String, value: Value)] = []
 26        var i = 0
 27        while i < lines.count {
 28            let line = lines[i]
 29            i += 1
 30            guard !line.hasPrefix(" "), !line.hasPrefix("#"), let colon = keyColon(line) else { continue }
 31            let key = unquote(String(line[..<colon]).trimmingCharacters(in: .whitespaces))
 32            let rest = stripComment(String(line[line.index(after: colon)...])).trimmingCharacters(in: .whitespaces)
 33            var nested: [String] = []
 34            while i < lines.count, lines[i].hasPrefix(" ") || lines[i].hasPrefix("-") || lines[i].trimmingCharacters(in: .whitespaces).isEmpty {
 35                nested.append(lines[i])
 36                i += 1
 37            }
 38            while nested.last?.trimmingCharacters(in: .whitespaces).isEmpty == true { nested.removeLast() }
 39            if rest == "|" || rest == ">" || rest.hasPrefix("|") || rest.hasPrefix(">") {
 40                let indent = nested.compactMap { $0.trimmingCharacters(in: .whitespaces).isEmpty ? nil : $0.prefix { $0 == " " }.count }.min() ?? 0
 41                let body = nested.map { String($0.dropFirst(min(indent, $0.prefix { $0 == " " }.count))) }
 42                entries.append((key, .scalar(body.joined(separator: rest.hasPrefix("|") ? "\n" : " "))))
 43            } else if !rest.isEmpty {
 44                if rest.hasPrefix("["), rest.hasSuffix("]") {
 45                    entries.append((key, .list(flowItems(String(rest.dropFirst().dropLast())))))
 46                } else if rest.hasPrefix("{") {
 47                    entries.append((key, .nested))
 48                } else {
 49                    entries.append((key, .scalar(unquote(rest))))
 50                }
 51            } else if nested.isEmpty {
 52                entries.append((key, .scalar("")))
 53            } else if nested.allSatisfy({ $0.trimmingCharacters(in: .whitespaces).hasPrefix("-") || $0.trimmingCharacters(in: .whitespaces).isEmpty }) {
 54                let items = nested.compactMap { line -> String? in
 55                    let item = line.trimmingCharacters(in: .whitespaces)
 56                    guard item.hasPrefix("-") else { return nil }
 57                    return unquote(stripComment(String(item.dropFirst())).trimmingCharacters(in: .whitespaces))
 58                }
 59                entries.append((key, .list(items.filter { !$0.isEmpty })))
 60            } else {
 61                entries.append((key, .nested))
 62            }
 63        }
 64        return entries
 65    }
 66
 67    /// The colon ending a key: the first one outside quotes followed by a space or the end.
 68    private static func keyColon(_ line: String) -> String.Index? {
 69        var quote: Character?
 70        var index = line.startIndex
 71        while index < line.endIndex {
 72            let char = line[index]
 73            if let open = quote {
 74                if char == open { quote = nil }
 75            } else if char == "\"" || char == "'" {
 76                quote = char
 77            } else if char == ":" {
 78                let next = line.index(after: index)
 79                if next == line.endIndex || line[next] == " " { return index }
 80            }
 81            index = line.index(after: index)
 82        }
 83        return nil
 84    }
 85
 86    private static func stripComment(_ value: String) -> String {
 87        guard !value.trimmingCharacters(in: .whitespaces).hasPrefix("\""), !value.trimmingCharacters(in: .whitespaces).hasPrefix("'"),
 88              let range = value.range(of: " #") else { return value }
 89        return String(value[..<range.lowerBound])
 90    }
 91
 92    static func unquote(_ value: String) -> String {
 93        if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first {
 94            let inner = String(value.dropFirst().dropLast())
 95            return first == "'" ? inner.replacingOccurrences(of: "''", with: "'")
 96                : inner.replacingOccurrences(of: "\\\"", with: "\"").replacingOccurrences(of: "\\\\", with: "\\")
 97        }
 98        return value
 99    }
100
101    private static func flowItems(_ text: String) -> [String] {
102        var items: [String] = []
103        var current = ""
104        var quote: Character?
105        for char in text {
106            if let open = quote {
107                current.append(char)
108                if char == open { quote = nil }
109            } else if char == "\"" || char == "'" {
110                quote = char
111                current.append(char)
112            } else if char == "," {
113                items.append(current)
114                current = ""
115            } else {
116                current.append(char)
117            }
118        }
119        items.append(current)
120        return items.map { unquote($0.trimmingCharacters(in: .whitespaces)) }.filter { !$0.isEmpty }
121    }
122}
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