336 lines · 18.8 KB · SwiftRaw
// One setter for Markdown columns. Parse the stored text before cutting it:// a page may start inside emphasis, a link or a fenced code block. Pieces// retain their source range, so the core's cuts still name the stored words.import CoreTextimport CottonPaper#if canImport(UIKit)import UIKit#elseimport AppKit#endifimport Foundationimport SwiftUIpublic enum FaceMarkdown { static let bullet = "• " public static func set(_ text: String, theme: Theme) -> AttributedString { Document(text, theme: theme).text } static func line(_ text: String, theme: Theme) -> AttributedString { set(text, theme: theme) } public static func inline(_ text: String, theme: Theme) -> AttributedString { Document(text, theme: theme, blocks: false).text } /// Extract words without choosing a look. Callers drawing runs must pass /// their worn theme to `set` or `inline` instead. public static func plain(_ text: String, blocks: Bool = true) -> String { String(Document(text, theme: nil, blocks: blocks).text.characters) } /// Give marked runs their host's weight and slant explicitly: a custom /// regular face does not infer them from presentation intents alone. public static func print(_ value: AttributedString, size: CGFloat, font: Font) -> AttributedString { var value = value for run in Array(value.runs) { let intent = run.inlinePresentationIntent ?? [] guard !intent.isEmpty else { continue } var face = intent.contains(.code) ? CottonFonts.type(size) : font if intent.contains(.stronglyEmphasized) { face = face.bold() } if intent.contains(.emphasized) { face = face.italic() } value[run.range].font = face } return value } /// The same set runs for CoreText's torn page and UIKit's reader. Font /// traits are applied before measurement as well as before drawing. public static func native(_ value: AttributedString, font: CTFont, ink: CGColor? = nil) -> NSAttributedString { let out = NSMutableAttributedString(string: "") for run in value.runs { let intent = run.inlinePresentationIntent ?? [] var face = font if intent.contains(.code) { _ = CottonFonts.type(CTFontGetSize(font)) face = CTFontCreateWithName(CottonFonts.typeFace as CFString, CTFontGetSize(font), nil) } // Some hosts bundle only their regular face (Caslon in the // reader). CoreText cannot find a sibling there: preserve the // emphasis with the same face's stroke and slant instead. var stroke: Double? if intent.contains(.stronglyEmphasized) { if let bold = CTFontCreateCopyWithSymbolicTraits(face, 0, nil, .traitBold, .traitBold), CTFontGetSymbolicTraits(bold).contains(.traitBold) { face = bold } else { stroke = -2 } } if intent.contains(.emphasized) { if let italic = CTFontCreateCopyWithSymbolicTraits(face, 0, nil, .traitItalic, .traitItalic), CTFontGetSymbolicTraits(italic).contains(.traitItalic) { face = italic } else { var slant = CTFontGetMatrix(face) slant.c += 0.2 face = CTFontCreateCopyWithAttributes(face, 0, &slant, nil) } } var attributes: [NSAttributedString.Key: Any] = [.init(kCTFontAttributeName as String): face] if let stroke { attributes[.strokeWidth] = stroke } if let ink { attributes[.init(kCTForegroundColorAttributeName as String)] = ink } #if canImport(UIKit) if let color = run.foregroundColor { attributes[.foregroundColor] = UIColor(color) } if let color = run.backgroundColor { attributes[.backgroundColor] = UIColor(color) } #else if let color = run.foregroundColor { attributes[.foregroundColor] = NSColor(color) } if let color = run.backgroundColor { attributes[.backgroundColor] = NSColor(color) } #endif if run.strikethroughStyle != nil { attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue } out.append(NSAttributedString(string: String(value[run.range].characters), attributes: attributes)) } return out } /// Draw the native runs in a face's canvas using the same text engine /// as the reader, including background, strike, stroke and font matrix. static func draw(_ value: AttributedString, font: CTFont, ink: Color, in context: CGContext, at point: CGPoint) { #if canImport(UIKit) let words = native(value, font: font, ink: UIColor(ink).cgColor) UIGraphicsPushContext(context) words.draw(at: point) UIGraphicsPopContext() #else let words = native(value, font: font, ink: NSColor(ink).cgColor) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true) words.draw(at: point) NSGraphicsContext.restoreGraphicsState() #endif } public struct Document { struct Piece { let source: Range<String.Index> var words: AttributedString } let source: String var pieces: [Piece] = [] public var text: AttributedString { pieces.reduce(into: AttributedString()) { $0 += $1.words } } public init(_ source: String, theme: Theme) { self.init(source, theme: theme, blocks: true) } init(_ source: String, theme: Theme?, blocks: Bool) { self.source = source if !blocks { pieces = Self.inline(source, range: source.startIndex..<source.endIndex, theme: theme) return } var fence: String? var start = source.startIndex while start < source.endIndex { let end = source[start...].firstIndex(of: "\n") ?? source.endIndex let range = start..<end let raw = String(source[range]) let trimmed = raw.trimmingCharacters(in: .whitespaces) let fenceMark = Self.match(#"^\s*(`{3,}|~{3,})"#, in: source, range: range) let delimiter = fenceMark.map { String(source[$0]).trimmingCharacters(in: .whitespaces) } if let open = fence { if let delimiter, delimiter.first == open.first, delimiter.count >= open.count, let fenceMark, source[fenceMark.upperBound..<end].trimmingCharacters(in: .whitespaces).isEmpty { fence = nil } else { var code = AttributedString(raw) code.inlinePresentationIntent = .code pieces.append(Piece(source: range, words: code)) if end < source.endIndex { appendNewline(at: end) } } } else if let delimiter { fence = delimiter // Fence and language take no printed line. } else { // A soft line break does not close inline emphasis. Set // an ordinary paragraph together, before any page cuts. let block = #"^\s*(?:#{1,6}\s|[-*+]\s|>|`{3,}|~{3,}|(?:-{3,}|\*{3,}|_{3,})$)"# if !trimmed.isEmpty, Self.match(block, in: source, range: range) == nil { var paragraphEnd = end while paragraphEnd < source.endIndex { let nextStart = source.index(after: paragraphEnd) let nextEnd = source[nextStart...].firstIndex(of: "\n") ?? source.endIndex let nextRange = nextStart..<nextEnd if source[nextRange].trimmingCharacters(in: .whitespaces).isEmpty || Self.match(block, in: source, range: nextRange) != nil { break } paragraphEnd = nextEnd } pieces += Self.inline(source, range: start..<paragraphEnd, theme: theme) if paragraphEnd < source.endIndex { appendNewline(at: paragraphEnd) } start = paragraphEnd < source.endIndex ? source.index(after: paragraphEnd) : paragraphEnd continue } var body = range var prefix = "" var intent: InlinePresentationIntent = [] if trimmed.range(of: #"^(-{3,}|\*{3,}|_{3,})$"#, options: .regularExpression) != nil { body = end..<end } else if let mark = Self.match(#"^\s*#{1,6}\s+"#, in: source, range: range) { body = mark.upperBound..<end intent = .stronglyEmphasized } else if let mark = Self.match(#"^\s*[-*+]\s+(?:\[[ xX]\]\s*)?"#, in: source, range: range) { let marker = String(source[mark]) prefix = String(raw.prefix(while: { $0 == " " || $0 == "\t" })) prefix += marker.contains("[ ]") ? "☐ " : marker.lowercased().contains("[x]") ? "☑ " : FaceMarkdown.bullet body = mark.upperBound..<end } else if let mark = Self.match(#"^\s*>\s?"#, in: source, range: range) { body = mark.upperBound..<end intent = .emphasized } if !prefix.isEmpty { pieces.append(Piece(source: (source[range].firstIndex(where: { !$0.isWhitespace }) ?? start)..<body.lowerBound, words: AttributedString(prefix))) } var words = Self.inline(source, range: body, theme: theme) if !intent.isEmpty { for i in words.indices { for run in Array(words[i].words.runs) { words[i].words[run.range].inlinePresentationIntent = (run.inlinePresentationIntent ?? []).union(intent) } } } pieces += words if end < source.endIndex { appendNewline(at: end) } } start = end < source.endIndex ? source.index(after: end) : end } } mutating func appendNewline(at index: String.Index) { pieces.append(Piece(source: index..<source.index(after: index), words: AttributedString("\n"))) } /// Project the cutter's pages onto the already set document. The /// Loom cutter inserts wrapping whitespace; the core returns exact /// source slices. Match characters in order, ignoring that whitespace. public func pages(_ cuts: [String]) -> [AttributedString] { var cursor = source.startIndex return cuts.map { cut in var first: String.Index? var last = cursor for character in cut where !character.isWhitespace { while cursor < source.endIndex && source[cursor].isWhitespace { cursor = source.index(after: cursor) } guard cursor < source.endIndex, source[cursor] == character else { continue } if first == nil { first = cursor } cursor = source.index(after: cursor) last = cursor } guard let first else { return AttributedString() } var shown = pieces.filter { $0.source.overlaps(first..<last) }.reduce(into: AttributedString()) { out, piece in if source[piece.source].count == piece.words.characters.count { let lower = max(first, piece.source.lowerBound) let upper = min(last, piece.source.upperBound) let from = piece.words.characters.index(piece.words.startIndex, offsetBy: source[piece.source.lowerBound..<lower].count) let to = piece.words.characters.index(from, offsetBy: source[lower..<upper].count) out += AttributedString(piece.words[from..<to]) } else if piece.source.lowerBound >= first { out += piece.words } } while shown.characters.first == "\n" { shown.removeSubrange(shown.startIndex..<shown.characters.index(after: shown.startIndex)) } while shown.characters.last == "\n" { shown.removeSubrange(shown.characters.index(before: shown.endIndex)..<shown.endIndex) } return shown } } static func match(_ pattern: String, in text: String, range: Range<String.Index>) -> Range<String.Index>? { text.range(of: pattern, options: .regularExpression, range: range) } static func inline(_ text: String, range: Range<String.Index>, theme: Theme?) -> [Piece] { var result: [Piece] = [] var at = range.lowerBound func literal(_ range: Range<String.Index>) { for index in text[range].indices { let next = text.index(after: index) result.append(Piece(source: index..<next, words: AttributedString(String(text[index])))) } } // Delimiters are read only outside code; links keep their label, // never a URL or a fetch. Recursion keeps nested emphasis intact. let delimiters: [(String, InlinePresentationIntent)] = [ ("***", [.stronglyEmphasized, .emphasized]), ("___", [.stronglyEmphasized, .emphasized]), ("**", .stronglyEmphasized), ("__", .stronglyEmphasized), ("*", .emphasized), ("_", .emphasized), ("~~", []), ("~", []), ("::", []), ("`", .code), ] while at < range.upperBound { let next = text.index(after: at) if text[at] == "\\", next < range.upperBound { let end = text.index(after: next) result.append(Piece(source: at..<end, words: AttributedString(String(text[next])))) at = end; continue } if let token = match(#"^!?\[([^\]\n]*)\]\((?:[^()\n]|\([^()\n]*\))*\)"#, in: text, range: at..<range.upperBound) { let image = text[at] == "!" let labelStart = text.index(at, offsetBy: image ? 2 : 1) let labelEnd = text[labelStart..<token.upperBound].firstIndex(of: "]")! if image { let alt = String(text[labelStart..<labelEnd]) var words = AttributedString(alt.isEmpty ? "picture" : alt) words.foregroundColor = theme?.colors.inkSecondary.color result.append(Piece(source: token, words: words)) } else { result += inline(text, range: labelStart..<labelEnd, theme: theme) } at = token.upperBound; continue } if text[at..<range.upperBound].hasPrefix("[["), let end = text.range(of: "]]", range: text.index(at, offsetBy: 2)..<range.upperBound) { result += inline(text, range: text.index(at, offsetBy: 2)..<end.lowerBound, theme: theme) at = end.upperBound; continue } var matched = false for (delimiter, intent) in delimiters { guard text[at..<range.upperBound].hasPrefix(delimiter) else { continue } // An underscore inside a word is a letter separator. if delimiter.contains("_"), at > range.lowerBound, text[text.index(before: at)].isLetter { continue } let start = text.index(at, offsetBy: delimiter.count) guard start < range.upperBound, !text[start].isWhitespace else { continue } var search = start var closing: Range<String.Index>? while let found = text.range(of: delimiter, range: search..<range.upperBound) { var end = found.upperBound if delimiter.first == "*" || delimiter.first == "_" { while end < range.upperBound && text[end] == delimiter.first { end = text.index(after: end) } } let count = text.distance(from: found.lowerBound, to: end) let escaped = found.lowerBound > start && text[text.index(before: found.lowerBound)] == "\\" if !escaped && !(delimiter.count == 1 && count == 2) { let lower = text.index(end, offsetBy: -delimiter.count) if lower > start && !text[text.index(before: lower)].isWhitespace { closing = lower..<end; break } } search = end } guard let close = closing else { continue } var held: [Piece] if intent == .code { held = [Piece(source: start..<close.lowerBound, words: AttributedString(String(text[start..<close.lowerBound])))] } else { held = inline(text, range: start..<close.lowerBound, theme: theme) } for i in held.indices { for run in Array(held[i].words.runs) { if !intent.isEmpty { held[i].words[run.range].inlinePresentationIntent = (run.inlinePresentationIntent ?? []).union(intent) } if delimiter.contains("~") { held[i].words[run.range].strikethroughStyle = .single } if delimiter == "::" { held[i].words[run.range].backgroundColor = theme?.colors.highlight.color.opacity(0.35) } } } result += held at = close.upperBound; matched = true; break } if matched { continue } if text[at] == "#", (at == range.lowerBound || text[text.index(before: at)].isWhitespace), let tag = match(#"^#[\p{L}\p{N}_]+(?:/[\p{L}\p{N}_]+)*"#, in: text, range: at..<range.upperBound) { for index in text[next..<tag.upperBound].indices { var words = AttributedString(String(text[index])) words.foregroundColor = theme?.colors.inkSecondary.color result.append(Piece(source: index..<text.index(after: index), words: words)) } at = tag.upperBound; continue } literal(at..<next) at = next } return result } }}