Sources/OrgCore/Commands/InlineImages.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Commands/InlineImages.swift history · blame · raw

47 lines · 2500 bytes

 1import Foundation
 2
 3/// Image links shown as images (`org-display-inline-images`, Org 9.8.7): a line that is only a
 4/// link to an image file, without a description, 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    static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif"
12    static let pattern = try! NSRegularExpression(pattern: "^[ \\t]*\\[\\[(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))\\]\\][ \\t]*$", options: .caseInsensitive)
13
14    /// The image on the line at `lineStart`, if the line is an image link; with `remote`,
15    /// http and https links too (`org-display-remote-inline-images` other than `skip`).
16    public static func image(atLine lineStart: Int, in text: NSString, remote: Bool = false) -> Image? {
17        let line = text.lineRange(for: NSRange(location: lineStart, length: 0))
18        let content = text.substring(with: line).trimmingCharacters(in: .newlines)
19        guard let m = pattern.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) else { return nil }
20        let path = (content as NSString).substring(with: m.range(at: 1))
21        guard !path.hasPrefix("attachment:") else { return nil }
22        if path.contains("://") {
23            guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
24        }
25        // `#+ATTR_ORG: :width N` in the affiliated keywords above.
26        var width: Int?
27        var at = line.location
28        while at > 0 {
29            let previous = text.lineRange(for: NSRange(location: at - 1, length: 0))
30            let keyword = text.substring(with: previous)
31            guard keyword.range(of: "^[ \\t]*#\\+[A-Za-z_]+:", options: .regularExpression) != nil else { break }
32            if width == nil, let w = keyword.firstMatch(of: /(?i)^[ \t]*#\+ATTR_ORG:.*:width[ \t]+([0-9]+)/) { width = Int(w.1) }
33            at = previous.location
34        }
35        return Image(path: path, width: width)
36    }
37
38    /// `#+STARTUP: inlineimages` or `noinlineimages`, if the file says.
39    public static func startup(_ tree: OrgTree) -> Bool? {
40        var shown: Bool?
41        for word in tree.settings.startup {
42            if word.lowercased() == "inlineimages" { shown = true }
43            if word.lowercased() == "noinlineimages" { shown = false }
44        }
45        return shown
46    }
47}