Sources/OrgCore/Commands/InlineImages.swift
53 lines · 2858 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/// `file:` or `attachment:` link to an image, without a description, and the width
5/// `#+ATTR_ORG: :width` asks for.
6public enum InlineImages {
7 public struct Image: Sendable, Equatable {
8 public let path: String
9 public let width: Int?
10 }
11
12 static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif"
13 static let pattern = try! NSRegularExpression(pattern: "^[ \\t]*\\[\\[(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))\\]\\][ \\t]*$", options: .caseInsensitive)
14
15 /// The image on the line at `lineStart`, if the line is an image link; with `remote`,
16 /// http and https links too (`org-display-remote-inline-images` other than `skip`).
17 /// `attachment` gives an `attachment:` link's file from its name and offset, as
18 /// `org-attach-expand` does; without it those links don't show.
19 public static func image(atLine lineStart: Int, in text: NSString, remote: Bool = false, attachment: ((String, Int) -> String?)? = nil) -> Image? {
20 let line = text.lineRange(for: NSRange(location: lineStart, length: 0))
21 let content = text.substring(with: line).trimmingCharacters(in: .newlines)
22 guard let m = pattern.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) else { return nil }
23 var path = (content as NSString).substring(with: m.range(at: 1))
24 if path.hasPrefix("attachment:") {
25 guard let file = attachment?(String(path.dropFirst("attachment:".count)), line.location) else { return nil }
26 path = file
27 }
28 if path.contains("://") {
29 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
30 }
31 // `#+ATTR_ORG: :width N` in the affiliated keywords above.
32 var width: Int?
33 var at = line.location
34 while at > 0 {
35 let previous = text.lineRange(for: NSRange(location: at - 1, length: 0))
36 let keyword = text.substring(with: previous)
37 guard keyword.range(of: "^[ \\t]*#\\+[A-Za-z_]+:", options: .regularExpression) != nil else { break }
38 if width == nil, let w = keyword.firstMatch(of: /(?i)^[ \t]*#\+ATTR_ORG:.*:width[ \t]+([0-9]+)/) { width = Int(w.1) }
39 at = previous.location
40 }
41 return Image(path: path, width: width)
42 }
43
44 /// `#+STARTUP: inlineimages` or `noinlineimages`, if the file says.
45 public static func startup(_ tree: OrgTree) -> Bool? {
46 var shown: Bool?
47 for word in tree.settings.startup {
48 if word.lowercased() == "inlineimages" { shown = true }
49 if word.lowercased() == "noinlineimages" { shown = false }
50 }
51 return shown
52 }
53}