import Foundation import OrgCore import Testing @testable import OrgApp struct ImageYankTests { /// An ID per file, ending in its name's letter. static let id = "6a1b2c3d-0000-4000-8000-00000000000" static let notes = """ #+title: Notes Free text. * Task Body. """ static var noon: Date { DateComponents(calendar: Calendar.current, year: 2024, month: 1, day: 1, hour: 12).date! } static func folder() throws -> URL { let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-yank-\(UUID().uuidString)").resolvingSymlinksInPath() try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) return folder } @Test func fileNameIsOrgsAutogeneratedName() { #expect(ImageYank.fileName(ext: "png", date: Self.noon) == "clipboard-20240101T120000.png") #expect(ImageYank.fileName(ext: "jpg", date: Self.noon, prefix: "photo") == "photo-20240101T120000.jpg") } /// The text and files `org--image-yank-media-handler` leaves, without the link it inserts: /// in an entry, before the first heading (a file-level ID), and into a folder. @Test func savingMatchesEmacs() throws { let folder = try Self.folder() defer { try? FileManager.default.removeItem(at: folder) } let dir = folder.path for name in ["a", "b", "c"] { try Self.notes.write(toFile: "\(dir)/\(name).org", atomically: true, encoding: .utf8) } let form = #""" (progn (require 'org) (require 'org-attach) (require 'json) (let ((out nil) (org-yank-image-file-name-function (lambda () "clipboard-20240101T120000.000000"))) (cl-letf (((symbol-function 'org-id-new) (lambda (&rest _) (concat "\#(Self.id)" (file-name-base (buffer-file-name)))))) (cl-flet ((yank (file where method) (with-current-buffer (find-file-noselect (concat "\#(dir)/" file)) (goto-char (point-min)) (search-forward where) (let ((org-yank-image-save-method method) (start (copy-marker (point)))) (org--image-yank-media-handler 'image/png "PNG") (push (buffer-substring-no-properties start (point)) out) (delete-region start (point))) (push (buffer-substring-no-properties (point-min) (point-max)) out)))) (yank "a.org" "Body." 'attach) (yank "b.org" "Free text." 'attach) (yank "c.org" "Body." "img/"))) (with-temp-file "\#(dir)/out.json" (insert (json-encode (vconcat (nreverse out))))))) """# let process = Process() process.executableURL = URL(fileURLWithPath: "/usr/bin/env") process.arguments = [ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs", "-Q", "--batch", "--eval", form] process.currentDirectoryURL = folder let pipe = Pipe() process.standardOutput = pipe process.standardError = pipe try process.run() let log = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) process.waitUntilExit() try #require(FileManager.default.fileExists(atPath: folder.appendingPathComponent("out.json").path), "\(log)") let emacs = try JSONDecoder().decode([String].self, from: Data(contentsOf: folder.appendingPathComponent("out.json"))) try FileManager.default.removeItem(at: folder.appendingPathComponent("out.json")) let emacsFiles = AttachmentsTests.listing(folder).filter { !$0.hasSuffix(".org") } for name in ["data", "img"] { try? FileManager.default.removeItem(atPath: "\(dir)/\(name)") } var ours: [String] = [] for (file, at, method) in [("a.org", "Body.", ImageYank.SaveMethod.attach), ("b.org", "Free text.", .attach), ("c.org", "Body.", .directory("img/"))] { let ns = Self.notes as NSString var entry = Attachments.Entry(text: Self.notes, offset: NSMaxRange(ns.range(of: at)), path: "\(dir)/\(file)", idDir: "data/") if method == .attach { _ = try Attachments.directoryCreating(&entry, newID: { Self.id + (file as NSString).deletingPathExtension }) } ours.append(try ImageYank.save(Data("PNG".utf8), ext: "png", method: method, in: &entry, date: Self.noon)) ours.append(entry.text) } #expect(emacs.count == 6, "\(log)") // Org's links carry the file name as their description; ours have none. #expect(ours[0] == "[[attachment:clipboard-20240101T120000.png]]") #expect(emacs[0] == "[[attachment:clipboard-20240101T120000.png][clipboard-20240101T120000.png]]") #expect(ours[2] == "[[attachment:clipboard-20240101T120000.png]]") #expect(ours[4] == emacs[4]) for index in [1, 3, 5] { #expect(ours[index] == emacs[index], "step \(index)") } #expect(AttachmentsTests.listing(folder).filter { !$0.hasSuffix(".org") } == emacsFiles) // The link before the first heading shows as an image: the file-level ID's folder. let (text, caret) = ImageYank.inserting([ours[2]], into: ours[3], at: NSMaxRange((ours[3] as NSString).range(of: "Free text."))) #expect(DocumentSession.attachmentPath("clipboard-20240101T120000.png", at: caret, tree: OrgParser.parse(text), path: "\(dir)/b.org") == "\(dir)/data/6a/1b2c3d-0000-4000-8000-00000000000b/clipboard-20240101T120000.png") let line = (text as NSString).lineRange(for: NSRange(location: caret - 1, length: 0)) #expect(InlineImages.links(OrgParser.parse(text), in: line.location..\n:PROPERTIES:\n:ID: x\n:END:\n* Next\n", at: 0).text == "* Task\nSCHEDULED: <2026-11-21 Sat>\n:PROPERTIES:\n:ID: x\n:END:\n\(link)\n* Next\n") let folder = try Self.folder() defer { try? FileManager.default.removeItem(at: folder) } let path = folder.appendingPathComponent("n.org").path let original = "Free text.\n* Task\nBody.\n" var entry = Attachments.Entry(text: original, offset: 11, path: path, idDir: "data/") let saved = try ImageYank.save(Data("PDF".utf8), ext: "pdf", method: .attach, in: &entry, date: Self.noon, prefix: "scan") let (text, caret) = ImageYank.inserting([saved], into: entry.text, at: ImageYank.map(entry.offset, from: original, to: entry.text)) let file = try #require(DocumentSession.attachmentPath("scan-20240101T120000.pdf", at: caret, tree: OrgParser.parse(text), path: path)) #expect(FileManager.default.fileExists(atPath: file)) } @Test func caretFollowsTheChangeAboveIt() { let old = "* Task\nBody." let new = "* Task\n:PROPERTIES:\n:ID: x\n:END:\nBody." #expect(ImageYank.map(12, from: old, to: new) == (new as NSString).length) #expect(ImageYank.map(3, from: old, to: new) == 3) #expect(ImageYank.map(7, from: old, to: new) == 7 + 26) let drawer = ":PROPERTIES:\n:ID: x\n:END:\n" #expect(ImageYank.map(0, from: "#+title: a\n", to: drawer + "#+title: a\n") == (drawer as NSString).length) } @Test func settings() { #expect(ImageYank.SaveMethod("attach") == .attach) #expect(ImageYank.SaveMethod("") == .attach) #expect(ImageYank.SaveMethod("~/img/") == .directory("~/img/")) } }