Sources/OrgPresentation/LatexPreview.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgPresentation/LatexPreview.swift history · blame · raw

139 lines · 6531 bytes

14 symbols in this file
  1import CoreGraphics
  2import Foundation
  3import OrgCore
  4import SwiftMath
  5#if os(macOS)
  6import AppKit
  7#else
  8import UIKit
  9#endif
 10
 11/// `org-latex-preview`: LaTeX fragments and environments drawn as typeset math, by SwiftMath
 12/// rather than LaTeX, so it works without TeX and on iOS.
 13public enum LatexPreview {
 14    /// A fragment or environment and what to typeset.
 15    public struct Fragment: Equatable, Sendable {
 16        public let range: Range<Int>
 17        public let latex: String
 18        /// `$$…$$`, `\[…\]` and environments: display style.
 19        public let display: Bool
 20        /// A LaTeX environment, which takes lines of its own.
 21        public let environment: Bool
 22    }
 23
 24    /// The fragments and environments that overlap `range`.
 25    public static func fragments(_ tree: OrgTree, in range: Range<Int>) -> [Fragment] {
 26        var out: [Fragment] = []
 27        func walk(_ node: SyntaxNode) {
 28            guard node.range.overlaps(range) || node.range.isEmpty && range.contains(node.range.lowerBound) else { return }
 29            switch node.kind {
 30            case .latexFragment:
 31                if let fragment = fragment(node.text, range: node.range) { out.append(fragment) }
 32            case .latexEnvironment:
 33                let text = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
 34                let leading = node.text.prefix { $0 == " " || $0 == "\t" }.utf16.count
 35                let end = node.range.lowerBound + leading + (text as NSString).length
 36                out.append(Fragment(range: (node.range.lowerBound + leading)..<end, latex: environment(text), display: true, environment: true))
 37            case .block:
 38                return
 39            default:
 40                for child in node.children { walk(child) }
 41            }
 42        }
 43        walk(tree.root)
 44        return out
 45    }
 46
 47    /// A fragment's math without its delimiters.
 48    static func fragment(_ text: String, range: Range<Int>) -> Fragment? {
 49        let pairs: [(String, String, Bool)] = [("$$", "$$", true), ("\\[", "\\]", true), ("\\(", "\\)", false), ("$", "$", false)]
 50        for (open, close, display) in pairs where text.hasPrefix(open) && text.hasSuffix(close) && text.count >= open.count + close.count {
 51            let inner = String(text.dropFirst(open.count).dropLast(close.count))
 52            guard inner.contains(where: { !$0.isWhitespace }) else { return nil }
 53            return Fragment(range: range, latex: inner, display: display, environment: false)
 54        }
 55        // `\command[…]{…}`.
 56        return Fragment(range: range, latex: text, display: false, environment: false)
 57    }
 58
 59    /// An environment as SwiftMath reads it: `equation` and `displaymath` as their body,
 60    /// `align` and `gather` as `aligned` and `gathered`.
 61    static func environment(_ text: String) -> String {
 62        guard let m = text.firstMatch(of: #/(?s)^\\begin\{([A-Za-z]+)\*?\}(.*)\\end\{\1\*?\}$/#) else { return text }
 63        let body = String(m.2).trimmingCharacters(in: .whitespacesAndNewlines)
 64        switch m.1 {
 65        case "equation", "displaymath", "math": return body
 66        case "align", "alignat", "flalign", "eqnarray": return "\\begin{aligned}" + body + "\\end{aligned}"
 67        case "gather", "multline": return "\\begin{gathered}" + body + "\\end{gathered}"
 68        default: return text
 69        }
 70    }
 71
 72    /// Typeset math: the image at the screen's scale, its size in points, and how far it
 73    /// reaches above and below the baseline.
 74    public struct Rendering: @unchecked Sendable {
 75        public let image: CGImage
 76        public let size: CGSize
 77        public let ascent: CGFloat
 78        public let descent: CGFloat
 79    }
 80
 81    #if os(macOS)
 82    public typealias Color = NSColor
 83    #else
 84    public typealias Color = UIColor
 85    #endif
 86
 87    private final class Box: NSObject {
 88        let rendering: Rendering?
 89        init(_ rendering: Rendering?) { self.rendering = rendering }
 90    }
 91
 92    nonisolated(unsafe) private static let cache = NSCache<NSString, Box>()
 93
 94    /// `latex` typeset at `fontSize` in `color`, or nil when SwiftMath can't read it.
 95    @MainActor
 96    public static func render(_ latex: String, display: Bool, fontSize: CGFloat, color: Color, scale: CGFloat) -> Rendering? {
 97        let key = "\(display)|\(fontSize)|\(scale)|\(color.description)|\(latex)" as NSString
 98        if let cached = cache.object(forKey: key) { return cached.rendering }
 99        var math = MathImage(latex: latex, fontSize: fontSize, textColor: color, labelMode: display ? .display : .text, textAlignment: .left)
100        let (error, image, layout) = math.asImage()
101        var rendering: Rendering?
102        if error == nil, let image, let layout, let cg = cgImage(image, scale: scale) {
103            rendering = Rendering(image: cg, size: image.size, ascent: layout.ascent, descent: layout.descent)
104        }
105        cache.setObject(Box(rendering), forKey: key)
106        return rendering
107    }
108
109    #if os(macOS)
110    private static func cgImage(_ image: NSImage, scale: CGFloat) -> CGImage? {
111        let width = Int((image.size.width * scale).rounded(.up)), height = Int((image.size.height * scale).rounded(.up))
112        guard width > 0, height > 0,
113              let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
114                                      space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }
115        NSGraphicsContext.saveGraphicsState()
116        NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
117        image.draw(in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)))
118        NSGraphicsContext.restoreGraphicsState()
119        return context.makeImage()
120    }
121    #else
122    private static func cgImage(_ image: UIImage, scale: CGFloat) -> CGImage? {
123        let format = UIGraphicsImageRendererFormat()
124        format.scale = scale
125        return UIGraphicsImageRenderer(size: image.size, format: format).image { _ in image.draw(at: .zero) }.cgImage
126    }
127    #endif
128}
129
130extension Presentation {
131    /// `#+STARTUP: latexpreview` and `nolatexpreview`, last one wins; nil without either.
132    public static func startupLatexPreview(_ tree: OrgTree) -> Bool? {
133        var shows: Bool?
134        for word in startupOptions(tree).map({ $0.lowercased() }) {
135            if word == "latexpreview" { shows = true } else if word == "nolatexpreview" { shows = false }
136        }
137        return shows
138    }
139}