Sources/OrgCore/Commands/InlineImages.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Commands/InlineImages.swift history · blame · raw

126 lines · 7210 bytes

11 symbols in this file
  1import Foundation
  2
  3/// Image links shown as images (`org-link-preview-region`, Org 9.8.7): `file:` and
  4/// `attachment:` links to an image, and the width `#+ATTR_ORG: :width` asks for.
  5public enum InlineImages {
  6    public struct Image: Sendable, Equatable {
  7        public let path: String
  8        public let width: Int?
  9    }
 10
 11    /// A link shown as an image, and the text the image stands for.
 12    public struct Link: Sendable, Equatable {
 13        public let range: Range<Int>
 14        public let image: Image
 15    }
 16
 17    static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif"
 18    static let imagePath = try! NSRegularExpression(pattern: "^(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))$", options: .caseInsensitive)
 19    static let bracketLink = try! NSRegularExpression(pattern: "\\[\\[([^\\]\\n]+)\\](?:\\[([^\\]\\n]+)\\])?\\]")
 20
 21    /// The image links overlapping `range`, in order. A link without a description shows its
 22    /// path. One with a description shows the description, and the image stands for the
 23    /// description alone, when that is a single `file:` or `attachment:` link, plain or in
 24    /// angle brackets; with `includeLinked` (`org-toggle-inline-images` with a prefix
 25    /// argument) it shows its path instead. With `remote`, http and https paths too
 26    /// (`org-display-remote-inline-images` other than `skip`). `attachment` gives an
 27    /// `attachment:` link's file from its name and offset, as `org-attach-expand` does;
 28    /// without it those links don't show.
 29    public static func links(
 30        _ tree: OrgTree, in range: Range<Int>, includeLinked: Bool = false, remote: Bool = false, attachment: ((String, Int) -> String?)? = nil
 31    ) -> [Link] {
 32        var out: [Link] = []
 33        func add(_ target: String?, _ link: Range<Int>, widthFrom line: Int?) {
 34            guard let target, let m = imagePath.firstMatch(in: target, range: NSRange(location: 0, length: (target as NSString).length)) else { return }
 35            var path = (target as NSString).substring(with: m.range(at: 1))
 36            if path.hasPrefix("attachment:") {
 37                guard let file = attachment?(String(path.dropFirst("attachment:".count)), link.lowerBound) else { return }
 38                path = file
 39            }
 40            if path.contains("://") {
 41                guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return }
 42            }
 43            out.append(Link(range: link, image: Image(path: path, width: line.flatMap { width(above: $0, in: tree.text as NSString) })))
 44        }
 45        func bracket(path: String, _ link: Range<Int>, description: String?, _ described: Range<Int>?, widthFrom line: Int?) {
 46            if let description, let described, !includeLinked {
 47                add(plainTarget(description), described, widthFrom: line)
 48            } else {
 49                add(path, link, widthFrom: line)
 50            }
 51        }
 52        // Org text the tree keeps as a line: its bracket links.
 53        func scan(_ line: SyntaxToken, widthFrom start: Int?) {
 54            let content = line.text as NSString
 55            for m in bracketLink.matches(in: line.text, range: NSRange(location: 0, length: content.length)) {
 56                let offset = line.range.lowerBound
 57                let described = m.range(at: 2).location == NSNotFound ? nil : m.range(at: 2)
 58                bracket(path: content.substring(with: m.range(at: 1)), (offset + m.range.location)..<(offset + NSMaxRange(m.range)),
 59                        description: described.map(content.substring(with:)), described.map { (offset + $0.location)..<(offset + NSMaxRange($0)) }, widthFrom: start)
 60            }
 61        }
 62        func walk(_ node: SyntaxNode, paragraph: Int?) {
 63            switch node.kind {
 64            case .link:
 65                if let path = node.linkPath {
 66                    let description = node.firstChild(.linkDescription)
 67                    bracket(path: path, node.range, description: description?.text, description?.range, widthFrom: paragraph)
 68                } else {
 69                    add(plainTarget(node.text), node.range, widthFrom: paragraph)
 70                }
 71            case .block:
 72                // Quote, center, verse and special blocks hold Org text.
 73                guard case .token(let opening)? = node.green.children.first,
 74                      opening.text.range(of: "^[ \\t]*#\\+begin_(?:src|example|export|comment)\\b", options: [.regularExpression, .caseInsensitive]) == nil else { return }
 75                let lines = node.tokens.filter { $0.kind == .text }
 76                for line in lines.dropFirst().dropLast() where line.range.overlaps(range) { scan(line, widthFrom: line.range.lowerBound) }
 77            case .affiliatedKeyword:
 78                // A caption is Org text too.
 79                for line in node.tokens where line.kind == .text && line.text.range(of: "^[ \\t]*#\\+CAPTION(?:\\[.*\\])?:", options: [.regularExpression, .caseInsensitive]) != nil {
 80                    scan(line, widthFrom: nil)
 81                }
 82            case .paragraph:
 83                // An item's first paragraph starts after the bullet and takes no affiliated keywords.
 84                let start = node.parent?.kind == .item ? nil : node.range.lowerBound
 85                for child in node.children(overlapping: range) { walk(child, paragraph: start) }
 86            default:
 87                for child in node.children(overlapping: range) { walk(child, paragraph: paragraph) }
 88            }
 89        }
 90        walk(tree.root, paragraph: nil)
 91        return out
 92    }
 93
 94    /// A plain or angle link with an explicit `file:` or `attachment:` type.
 95    static func plainTarget(_ link: String) -> String? {
 96        var target = Substring(link)
 97        if target.hasPrefix("<"), target.hasSuffix(">") { target = target.dropFirst().dropLast() }
 98        guard target.hasPrefix("file:") || target.hasPrefix("attachment:"), !target.contains(where: { $0 == "\n" || $0 == "<" || $0 == ">" }),
 99              link.hasPrefix("<") || !target.contains(where: \.isWhitespace) else { return nil }
100        return String(target)
101    }
102
103    /// `#+ATTR_ORG: :width N` in the affiliated keywords above the line at `lineStart`.
104    static func width(above lineStart: Int, in text: NSString) -> Int? {
105        var width: Int?
106        var at = lineStart
107        while at > 0 {
108            let previous = text.lineRange(for: NSRange(location: at - 1, length: 0))
109            let keyword = text.substring(with: previous)
110            guard keyword.range(of: "^[ \\t]*#\\+[A-Za-z_]+:", options: .regularExpression) != nil else { break }
111            if width == nil, let w = keyword.firstMatch(of: /(?i)^[ \t]*#\+ATTR_ORG:.*:width[ \t]+([0-9]+)/) { width = Int(w.1) }
112            at = previous.location
113        }
114        return width
115    }
116
117    /// `#+STARTUP: inlineimages` or `noinlineimages`, if the file says.
118    public static func startup(_ tree: OrgTree) -> Bool? {
119        var shown: Bool?
120        for word in tree.settings.startup {
121            if word.lowercased() == "inlineimages" { shown = true }
122            if word.lowercased() == "noinlineimages" { shown = false }
123        }
124        return shown
125    }
126}