// 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 CoreText import CottonPaper #if canImport(UIKit) import UIKit #else import AppKit #endif import Foundation import SwiftUI public 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 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..= open.count, let fenceMark, source[fenceMark.upperBound..|`{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..\s?"#, in: source, range: range) { body = mark.upperBound.. [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..= first { out += piece.words } } while shown.characters.first == "\n" { shown.removeSubrange(shown.startIndex..) -> Range? { text.range(of: pattern, options: .regularExpression, range: range) } static func inline(_ text: String, range: Range, theme: Theme?) -> [Piece] { var result: [Piece] = [] var at = range.lowerBound func literal(_ range: Range) { for index in text[range].indices { let next = text.index(after: index) result.append(Piece(source: index.. 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? while let found = text.range(of: delimiter, range: search.. 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..