Tests/OrgCoreTests/InlineImagesTests.swift

design-themes-widgets
orgstar/Tests/OrgCoreTests/InlineImagesTests.swift history · blame · raw

145 lines · 8793 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct InlineImagesTests {
  6    /// Each image link's text and the path it shows.
  7    static func shown(_ text: String, includeLinked: Bool = false, remote: Bool = false, attachment: ((String, Int) -> String?)? = nil) -> [[String]] {
  8        let tree = OrgParser.parse(text)
  9        return InlineImages.links(tree, in: 0..<(text as NSString).length, includeLinked: includeLinked, remote: remote, attachment: attachment)
 10            .map { [(text as NSString).substring(with: NSRange($0.range)), $0.image.path] }
 11    }
 12
 13    @Test func findsImageLines() {
 14        let text = "#+STARTUP: inlineimages\n* Images\n[[file:pic.png]]\n#+NAME: x\n#+ATTR_ORG: :width 60\n[[./pic.png]]\n[[pic.png][desc]]\n[[https://x.org/a.png]]\n"
 15        let tree = OrgParser.parse(text)
 16        let links = InlineImages.links(tree, in: 0..<(text as NSString).length)
 17        #expect(links.map(\.image) == [InlineImages.Image(path: "pic.png", width: nil), InlineImages.Image(path: "./pic.png", width: 60)])
 18        #expect(links.map(\.range.lowerBound) == ["[[file:pic", "[[./pic"].map { (text as NSString).range(of: $0).location })
 19        #expect(InlineImages.startup(tree) == true)
 20        #expect(InlineImages.startup(OrgParser.parse("#+STARTUP: overview noinlineimages\n")) == false)
 21        #expect(InlineImages.startup(OrgParser.parse("* x\n")) == nil)
 22        #expect(InlineImages.startup(OrgParser.parse("#+begin_src org\n#+STARTUP: inlineimages\n#+end_src\n")) == nil)
 23    }
 24
 25    @Test func attachmentLinksNeedTheResolver() {
 26        let text = "* Photo\n[[attachment:cat.jpg]]\n#+ATTR_ORG: :width 80\n[[attachment:sub/dog.png]]\n[[attachment:cat.jpg][desc]]\n"
 27        #expect(Self.shown(text).isEmpty)
 28        var asked: [(String, Int)] = []
 29        let resolve: (String, Int) -> String? = { name, offset in
 30            asked.append((name, offset))
 31            return "/notes/data/ab/cd/" + name
 32        }
 33        let links = InlineImages.links(OrgParser.parse(text), in: 0..<(text as NSString).length, attachment: resolve)
 34        #expect(links.map(\.image) == [
 35            InlineImages.Image(path: "/notes/data/ab/cd/cat.jpg", width: nil), InlineImages.Image(path: "/notes/data/ab/cd/sub/dog.png", width: 80),
 36        ])
 37        #expect(asked.map(\.0) == ["cat.jpg", "sub/dog.png"] && asked[0].1 == (text as NSString).range(of: "[[attachment:cat.jpg]]").location)
 38        #expect(Self.shown(text, attachment: { _, _ in nil }).isEmpty)
 39    }
 40
 41    /// `org-link-preview-region`: a described link shows only with INCLUDE-LINKED.
 42    @Test func describedLinksShowWithThePrefix() {
 43        let text = "See [[file:a.png][the figure]] here.\n"
 44        #expect(Self.shown(text).isEmpty)
 45        #expect(Self.shown(text, includeLinked: true) == [["[[file:a.png][the figure]]", "a.png"]])
 46        #expect(Self.shown("[[file:notes.org][the figure]]\n", includeLinked: true).isEmpty)
 47    }
 48
 49    /// A description that is one `file:` or `attachment:` link, plain or in angle brackets,
 50    /// shows without the prefix, in place of the description; with it, the path decides.
 51    @Test func descriptionThatIsAnImageLink() {
 52        #expect(Self.shown("[[https://example.com][file:thumb.png]]\n") == [["file:thumb.png", "thumb.png"]])
 53        #expect(Self.shown("[[file:big.png][<file:small thumb.png>]]\n") == [["<file:small thumb.png>", "small thumb.png"]])
 54        #expect(Self.shown("[[file:big.png][attachment:t.png]]\n", attachment: { name, _ in "/a/" + name }) == [["attachment:t.png", "/a/t.png"]])
 55        #expect(Self.shown("[[file:big.png][file:thumb.png]]\n", includeLinked: true) == [["[[file:big.png][file:thumb.png]]", "big.png"]])
 56        #expect(Self.shown("[[https://example.com][file:thumb.png]]\n", includeLinked: true).isEmpty)
 57        // Not the whole description, no explicit type, or a remote link.
 58        #expect(Self.shown("[[file:big.png][see file:thumb.png]]\n[[file:big.png][./thumb.png]]\n[[file:big.png][https://example.com/t.png]]\n", remote: true).isEmpty)
 59    }
 60
 61    @Test func imagesInALinesText() {
 62        let text = "Before [[file:a.png]] between [[./b.jpg]] and file:c.gif and <file:d e.png> after.\n"
 63        #expect(Self.shown(text) == [["[[file:a.png]]", "a.png"], ["[[./b.jpg]]", "./b.jpg"], ["file:c.gif", "c.gif"], ["<file:d e.png>", "d e.png"]])
 64        // Only the links a range overlaps.
 65        let tree = OrgParser.parse(text)
 66        let b = (text as NSString).range(of: "[[./b.jpg]]")
 67        #expect(InlineImages.links(tree, in: b.location..<(b.location + 1)).map(\.image.path) == ["./b.jpg"])
 68    }
 69
 70    @Test func imagesInHeadingsTablesAndItems() {
 71        let text = "* Head [[file:h.png]]\n- item [[file:i.png]]\n  1. [[file:n.png]]\n| a | [[file:t.png]] |\n"
 72        #expect(Self.shown(text).map { $0[1] } == ["h.png", "i.png", "n.png", "t.png"])
 73    }
 74
 75    /// Links are objects: none in verbatim text, comments, keywords and literal blocks; quote,
 76    /// center and verse blocks and captions hold Org text.
 77    @Test func onlyWhereOrgHasLinks() {
 78        let text = "=[[file:v.png]]= ~[[file:c.png]]~\n# [[file:comment.png]]\n#+begin_src org\n[[file:s.png]]\n#+end_src\n#+BEGIN_EXAMPLE\n[[file:e.png]]\n#+END_EXAMPLE\n"
 79        #expect(Self.shown(text).isEmpty)
 80        let quote = "#+begin_quote\n#+ATTR_ORG: :width 40\n[[file:q.png]]\nText [[file:r.png][desc]] end\n#+end_quote\n"
 81        #expect(Self.shown(quote) == [["[[file:q.png]]", "q.png"]])
 82        #expect(Self.shown(quote, includeLinked: true).map { $0[1] } == ["q.png", "r.png"])
 83        #expect(InlineImages.links(OrgParser.parse(quote), in: 0..<(quote as NSString).length).first?.image.width == 40)
 84        #expect(Self.shown("#+CAPTION: See [[file:k.png]]\n#+NAME: [[file:n.png]]\nText\n") == [["[[file:k.png]]", "k.png"]])
 85    }
 86
 87    /// The paragraph's `#+ATTR_ORG` sizes every image in it, as `org-display-inline-image--width`
 88    /// reads it from the link's paragraph.
 89    @Test func widthComesFromTheParagraph() {
 90        let text = "#+ATTR_ORG: :width 120\nFirst line\nthen [[file:a.png]] and [[file:b.png]]\n\n- [[file:item.png]]\n* [[file:head.png]]\n"
 91        let links = InlineImages.links(OrgParser.parse(text), in: 0..<(text as NSString).length)
 92        #expect(links.map(\.image.width) == [120, 120, nil, nil])
 93    }
 94
 95    /// The links `org-link-preview-region` hands to the `file:` preview with an image's name,
 96    /// and the text each overlay covers, with and without INCLUDE-LINKED.
 97    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable))
 98    func linksMatchEmacs() throws {
 99        let text = """
100            * Head [[file:h.png]] tail
101            #+ATTR_ORG: :width 60
102            Para [[file:a.png][desc]] and [[./b.jpg]] and file:c.gif and <file:d e.png> end
103            more =[[file:v.png]]= ~[[file:w.png]]~ [[https://example.com][file:t.png]] [[file:big.png][file:small.png]]
104            [[file:big.png][<file:angle.png>]] [[file:big.png][see file:not.png]] [[file:notes.org][notes]] [[file:n.org]]
105
106            - item [[file:i.png]]
107              1. [[file:n.png][n]]
108            | a | [[file:t1.png]] | [[file:t2.png][two]] |
109            #+begin_quote
110            [[file:q.png]]
111            Text [[file:r.png][desc]] end
112            #+end_quote
113            #+begin_src org
114            [[file:s.png]]
115            #+end_src
116            #+begin_example
117            [[file:e.png]]
118            #+end_example
119            # [[file:comment.png]]
120            #+CAPTION: [[file:k.png]]
121            [[file:z.png]]
122
123            """
124        for includeLinked in [false, true] {
125            let emacs = try EmacsOracle.evaluate(text, """
126                (let (out (org-link-preview-batch-size 1000))
127                  (advice-add 'org-link-preview-file :override
128                              (lambda (ov path _link)
129                                (when (string-match-p (image-file-name-regexp) path)
130                                  (push (format "%s -> %s" (buffer-substring-no-properties (overlay-start ov) (overlay-end ov)) path) out))
131                                nil))
132                  (org-link-preview-region \(includeLinked ? "t" : "nil") t (point-min) (point-max))
133                  (nreverse out))
134                """)
135            #expect(Self.shown(text, includeLinked: includeLinked).map { "\($0[0]) -> \($0[1])" } == emacs, "INCLUDE-LINKED \(includeLinked)")
136            #expect(emacs.count > 8)
137        }
138    }
139
140    @Test func notImagesAndRemoteLinks() {
141        let text = "[[file:notes.org]] [[file:a.png::3]] [[https://x.org/a.png]] [[ftp://x.org/b.png]] https://x.org/c.png\n"
142        #expect(Self.shown(text).isEmpty)
143        #expect(Self.shown(text, remote: true) == [["[[https://x.org/a.png]]", "https://x.org/a.png"]])
144    }
145}