import Foundation /// The info string of a fenced block that the page shows as one object: a code block, or a table for csv. public enum FenceKind: String, Sendable, CaseIterable { case php, json, xml, csv } /// The page file as lines, with the created date of each block; reads the text and writes it back unchanged. public struct PageFile: Sendable, Equatable { public enum Line: Sendable, Equatable { case text(String) /// An image line; the path is relative to the page file folder, as `images/`. case image(String) /// A code block or table: the whole fenced block, whose body may hold newlines and blank lines. case fenced(FenceKind, String) /// The line as it stands in the page file. public var text: String { switch self { case let .text(text): text case let .image(path): PageFile.imageLine(path) case let .fenced(kind, body): PageFile.fencedBlock(kind, body) } } public var isBlank: Bool { if case let .text(text) = self { return PageFile.isBlank(text) } return false } } public var lines: [Line] /// Created dates by the index of the first line of a block; a date on any other line is not written. public var dates: [Int: Date] public init(lines: [Line] = [], dates: [Int: Date] = [:]) { self.lines = lines self.dates = dates } /// Reads page file text; a date line directly above the first line of a block is its created date. public init(text: String, timeZone: TimeZone = .current) { var raw = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n") if raw.last == "" { raw.removeLast() } var lines: [Line] = [] var dates: [Int: Date] = [:] var index = 0 while index < raw.count { let line = raw[index] let startsBlock = !Self.isBlank(line) && (index == 0 || Self.isBlank(raw[index - 1])) // A date line with no line under it in its block stays text, so the round trip stays exact. if startsBlock, index + 1 < raw.count, !Self.isBlank(raw[index + 1]), let date = CreatedDate.date(fromLine: line, timeZone: timeZone) { dates[lines.count] = date index += 1 } let (parsed, next) = Self.line(raw, at: index, timeZone: timeZone) lines.append(parsed) index = next } self.init(lines: lines, dates: dates) } /// The lines of pasted text: image lines and fenced blocks, but no dates. public static func lines(pasted text: String) -> [Line] { let raw = text.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n") var lines: [Line] = [] var index = 0 while index < raw.count { let (parsed, next) = Self.line(raw, at: index, timeZone: .current) lines.append(parsed) index = next } return lines } /// The page file text: every line, the date line above each dated block, and a trailing newline. public func text(timeZone: TimeZone = .current) -> String { guard !lines.isEmpty else { return "" } var out: [String] = [] out.reserveCapacity(lines.count + dates.count) for (index, line) in lines.enumerated() { if let date = dates[index], startsBlock(at: index) { out.append(CreatedDate.line(for: date, timeZone: timeZone)) } out.append(line.text) } return out.joined(separator: "\n") + "\n" } /// The line ranges of the blocks, top to bottom; a run of blank lines of any length separates two blocks. public var blocks: [Range] { var blocks: [Range] = [] var start: Int? for (index, line) in lines.enumerated() { if line.isBlank { if let first = start { blocks.append(first.. Bool { !lines[index].isBlank && (index == 0 || lines[index - 1].isBlank) } public static func isBlank(_ line: S) -> Bool { line.allSatisfy(\.isWhitespace) } /// The path an image line points to, as `images/`; nil when the line is not exactly an image line. public static func imagePath(fromLine line: String) -> String? { line.wholeMatch(of: #/!\[\]\((images/[^/()\s]+)\)/#).map { String($0.1) } } public static func imageLine(_ path: String) -> String { "![](\(path))" } /// The fence line, the body and the closing fence; the fence is longer than any run of backticks that starts a body line. public static func fencedBlock(_ kind: FenceKind, _ body: String) -> String { let fence = fence(for: body) return "\(fence)\(kind.rawValue)\n\(body)\n\(fence)" } /// Every line break as LF: a CR or CRLF in a body would hide a fence line inside it. public static func unixNewlines(_ text: String) -> String { text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") } /// Split on "\n" itself: as a Character, "\r\n" is one grapheme and would not split. static func fence(for body: String) -> String { var longest = 0 for line in body.components(separatedBy: "\n") { longest = max(longest, line.prefix(while: { $0 == "`" }).count) } return String(repeating: "`", count: max(3, longest + 1)) } /// The line that starts at `raw[index]`, and the index of the line after it. private static func line(_ raw: [String], at index: Int, timeZone: TimeZone) -> (Line, next: Int) { if let fenced = fencedBlock(raw, at: index, timeZone: timeZone) { return fenced } let text = raw[index] return (imagePath(fromLine: text).map(Line.image) ?? .text(text), index + 1) } /// A fence of a known kind with a body of at least one line and a closing fence of the same length. /// /// A fence that is not the one `fencedBlock` would write stays text, so the round trip stays exact. A body /// with a date line after a blank line stays text too: a stray fence must not swallow the dated blocks below it. private static func fencedBlock(_ raw: [String], at index: Int, timeZone: TimeZone) -> (Line, next: Int)? { let open = raw[index] let ticks = open.prefix(while: { $0 == "`" }).count guard ticks >= 3, let kind = FenceKind(rawValue: String(open.dropFirst(ticks))) else { return nil } let fence = String(repeating: "`", count: ticks) var close = index + 1 while close < raw.count, raw[close] != fence { close += 1 } guard close < raw.count, close > index + 1 else { return nil } for line in (index + 2)..