Inline images for attachment: links !298

merged merged by cmc on 2026-10-11 22:55 UTC · krz/orgstar:issue-0 into main

12 files changed, +101 −12

Layout: unified · split

Sources/OrgApp/LinkFollow.swift +7 −1
@@ -83,7 +83,13 @@ extension DocumentSession {
8383 return searchCurrent(option)
8484 }
8585
86 static func isDirectory(_ path: String) -> Bool {
86 /// An `attachment:` link's file in the file at `path` with `tree`, for inline images.
87 nonisolated public static func attachmentPath(_ name: String, at offset: Int, tree: OrgTree, path: String?) -> String? {
88 Links.attachmentFile(OrgLink(type: "attachment", path: name, raw: "attachment:" + name, position: offset), tree: tree, path: path,
89 idDir: OrgPreferences.attachIDDir(), inherit: OrgPreferences.attachUseInheritance(), isDirectory: isDirectory)?.path
90 }
91
92 nonisolated static func isDirectory(_ path: String) -> Bool {
8793 var directory: ObjCBool = false
8894 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
8995 }
Sources/OrgCore/Commands/InlineImages.swift +10 −4
@@ -1,7 +1,8 @@
11import Foundation
22
33/// 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.
4/// `file:` or `attachment:` link to an image, without a description, and the width
5/// `#+ATTR_ORG: :width` asks for.
56public enum InlineImages {
67 public struct Image: Sendable, Equatable {
78 public let path: String
@@ -13,12 +14,17 @@ public enum InlineImages {
1314
1415 /// The image on the line at `lineStart`, if the line is an image link; with `remote`,
1516 /// 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 /// `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? {
1720 let line = text.lineRange(for: NSRange(location: lineStart, length: 0))
1821 let content = text.substring(with: line).trimmingCharacters(in: .newlines)
1922 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 }
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 }
2228 if path.contains("://") {
2329 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
2430 }
Sources/OrgEditorAppKit/OrgEditor+Images.swift +9 −2
@@ -17,7 +17,7 @@ extension OrgEditor {
1717 var offset = 0
1818 while offset < ns.length {
1919 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
20 if let image = InlineImages.image(atLine: line.location, in: ns, remote: remote), loadImage(image.path) != nil { count += 1 }
20 if let image = InlineImages.image(atLine: line.location, in: ns, remote: remote, attachment: attachment), loadImage(image.path) != nil { count += 1 }
2121 offset = NSMaxRange(line)
2222 }
2323 onMessage?("\(count) images displayed inline")
@@ -34,6 +34,13 @@ extension OrgEditor {
3434 redrawViews()
3535 }
3636
37 /// `attachment:` links' files, for inline images.
38 private var attachment: ((String, Int) -> String?)? {
39 guard let attachmentPath else { return nil }
40 let tree = document.tree
41 return { attachmentPath($0, $1, tree) }
42 }
43
3744 /// Whether http(s) links show, as `org-display-remote-inline-images` says.
3845 private var remote: Bool { options.remoteInlineImages != "skip" }
3946
@@ -67,7 +74,7 @@ extension OrgEditor {
6774 while location < range.upperBound, location < text.length {
6875 let line = text.lineRange(for: NSRange(location: location, length: 0))
6976 location = NSMaxRange(line)
70 guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote), let picture = loadImage(image.path) else { continue }
77 guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote, attachment: attachment), let picture = loadImage(image.path) else { continue }
7178 var width = image.width.map(CGFloat.init) ?? picture.size.width
7279 width = min(width, maxWidth)
7380 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
Sources/OrgEditorAppKit/OrgEditor.swift +3
@@ -684,6 +684,9 @@ public final class OrgEditor: NSObject {
684684 public internal(set) var showsImages = false
685685 /// `org-latex-preview`: LaTeX fragments show as typeset math.
686686 public internal(set) var showsLatex = false
687 /// An `attachment:` link's file, from its name, offset and the tree: the app's
688 /// `org-attach-expand`. Nil leaves those links as text.
689 public var attachmentPath: ((String, Int, OrgTree) -> String?)?
687690 /// The file's folder, for relative image paths.
688691 public var baseDirectory: URL? {
689692 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
Sources/Orgstar/PaneView.swift +1
@@ -91,6 +91,7 @@ struct PaneView: NSViewRepresentable {
9191 let store = commands.store
9292 editor.onChange = { [weak session] in session?.bufferChanged(path) }
9393 editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent()
94 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
9495 editor.onMessage = { [weak commands] in commands?.show($0) }
9596 editor.onKeysPending = { [weak commands] keys, next in
9697 commands?.pendingKeys = keys
Sources/OrgstarMobile/EditorScreen.swift +4 −1
@@ -384,10 +384,13 @@ struct EditorScreen: View {
384384
385385 private func makeEditor() -> MobileEditor? {
386386 guard let document = session.document(of: path) else { return nil }
387 return MobileEditor(
387 let editor = MobileEditor(
388388 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
389389 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
390390 )
391 let path = path
392 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
393 return editor
391394 }
392395
393396 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
Sources/OrgstarMobile/MobileEditor+Display.swift +9 −2
@@ -60,7 +60,7 @@ extension MobileEditor {
6060 var offset = 0
6161 while offset < ns.length {
6262 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
63 if let image = InlineImages.image(atLine: line.location, in: ns, remote: options.remoteInlineImages != "skip"),
63 if let image = InlineImages.image(atLine: line.location, in: ns, remote: options.remoteInlineImages != "skip", attachment: attachment),
6464 loadImage(image.path) != nil { count += 1 }
6565 offset = NSMaxRange(line)
6666 }
@@ -70,6 +70,13 @@ extension MobileEditor {
7070 }
7171 }
7272
73 /// `attachment:` links' files, for inline images.
74 private var attachment: ((String, Int) -> String?)? {
75 guard let attachmentPath else { return nil }
76 let tree = document.tree
77 return { attachmentPath($0, $1, tree) }
78 }
79
7380 /// An image link's image here: remote ones as `org-display-remote-inline-images` says,
7481 /// restyled when they come.
7582 func loadImage(_ path: String) -> UIImage? {
@@ -114,7 +121,7 @@ extension MobileEditor {
114121 while location < range.upperBound, location < text.length {
115122 let line = text.lineRange(for: NSRange(location: location, length: 0))
116123 location = NSMaxRange(line)
117 guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip"),
124 guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip", attachment: attachment),
118125 let picture = loadImage(image.path) else { continue }
119126 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
120127 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
Sources/OrgstarMobile/MobileEditor.swift +3
@@ -121,6 +121,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
121121 var imageWidth: CGFloat = 0
122122 /// The file's folder, for relative image paths.
123123 let baseDirectory: URL?
124 /// An `attachment:` link's file, from its name, offset and the tree; nil leaves those links
125 /// as text.
126 var attachmentPath: ((String, Int, OrgTree) -> String?)?
124127 static let imageCache = NSCache<NSString, UIImage>()
125128 var loading = false
126129 var restyleScheduled: Range<Int>?
Sources/OrgstarMobile/ReaderScreen.swift +2 −1
@@ -228,7 +228,8 @@ struct ReaderScreen: View {
228228 while location < range.upperBound {
229229 let line = ns.lineRange(for: NSRange(location: location, length: 0))
230230 location = NSMaxRange(line)
231 guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns, remote: remote != .skip),
231 guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns, remote: remote != .skip,
232 attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) }),
232233 let picture = MobileEditor.loadImage(image.path, relativeTo: base, remote: remote) else { continue }
233234 if textStart < line.location { parts.append(Part(range: textStart..<line.location)) }
234235 parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width)))
Tests/OrgAppTests/AttachmentsTests.swift +33
@@ -208,3 +208,36 @@ struct AttachmentInboxTests {
208208 #expect(inbox.batches().isEmpty)
209209 }
210210}
211
212struct AttachmentImageTests {
213 /// `attachment:` links resolve as following them does: an ID entry's folder under
214 /// `org-attach-id-dir`, a `DIR` property's folder, and the file's folder otherwise.
215 @Test func attachmentLinksResolveToTheEntrysFolder() throws {
216 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-image-\(UUID().uuidString)").resolvingSymlinksInPath()
217 defer { try? FileManager.default.removeItem(at: folder) }
218 try FileManager.default.createDirectory(at: folder.appendingPathComponent("data/202401/01T120000"), withIntermediateDirectories: true)
219 try FileManager.default.createDirectory(at: folder.appendingPathComponent("imgs"), withIntermediateDirectories: true)
220 let text = """
221 * With ID
222 :PROPERTIES:
223 :ID: 20240101T120000
224 :END:
225 [[attachment:pic.png]]
226 * With DIR
227 :PROPERTIES:
228 :DIR: imgs
229 :END:
230 [[attachment:pic.png]]
231
232 """
233 let path = folder.appendingPathComponent("notes.org").path
234 let tree = OrgParser.parse(text)
235 let ns = text as NSString
236 let first = ns.range(of: "[[attachment").location
237 let second = ns.range(of: "[[attachment", options: .backwards).location
238 #expect(DocumentSession.attachmentPath("pic.png", at: first, tree: tree, path: path) == folder.appendingPathComponent("data/202401/01T120000/pic.png").path)
239 #expect(DocumentSession.attachmentPath("pic.png", at: second, tree: tree, path: path) == folder.appendingPathComponent("imgs/pic.png").path)
240 #expect(InlineImages.image(atLine: second, in: ns, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) })?.path
241 == folder.appendingPathComponent("imgs/pic.png").path)
242 }
243}
Tests/OrgCoreTests/InlineImagesTests.swift +18
@@ -14,4 +14,22 @@ struct InlineImagesTests {
1414 #expect(InlineImages.startup(OrgParser.parse("* x\n")) == nil)
1515 #expect(InlineImages.startup(OrgParser.parse("#+begin_src org\n#+STARTUP: inlineimages\n#+end_src\n")) == nil)
1616 }
17
18 @Test func attachmentLinksNeedTheResolver() {
19 let text = "* Photo\n[[attachment:cat.jpg]]\n#+ATTR_ORG: :width 80\n[[attachment:sub/dog.png]]\n[[attachment:cat.jpg][desc]]\n" as NSString
20 func at(_ s: String, _ resolve: ((String, Int) -> String?)?) -> InlineImages.Image? {
21 InlineImages.image(atLine: text.range(of: s).location, in: text, attachment: resolve)
22 }
23 #expect(at("[[attachment:cat.jpg]]", nil) == nil)
24 var asked: [(String, Int)] = []
25 let resolve: (String, Int) -> String? = { name, offset in
26 asked.append((name, offset))
27 return "/notes/data/ab/cd/" + name
28 }
29 #expect(at("[[attachment:cat.jpg]]", resolve) == InlineImages.Image(path: "/notes/data/ab/cd/cat.jpg", width: nil))
30 #expect(at("[[attachment:sub", resolve) == InlineImages.Image(path: "/notes/data/ab/cd/sub/dog.png", width: 80))
31 #expect(at("[[attachment:cat.jpg][", resolve) == nil)
32 #expect(asked.map(\.0) == ["cat.jpg", "sub/dog.png"] && asked[0].1 == text.range(of: "[[attachment:cat.jpg]]").location)
33 #expect(at("[[attachment:cat.jpg]]", { _, _ in nil }) == nil)
34 }
1735}
docs/manual/guide/02-the-editor.org +2 −1
@@ -58,7 +58,7 @@ Entities are left as typed on the caret's line, in comment lines and inside bloc
5858
5959Org ▸ Show or Hide Inline Images (=C-c C-x C-v= in the Emacs and Doom presets), as =org-toggle-inline-images= does, draws images in place of their links. The echo area reports how many images it displayed.
6060
61A line shows as an image when it holds nothing but a link to an image file with no description:
61A line shows as an image when it holds nothing but a =file:= or =attachment:= link to an image file with no description:
6262
6363#+BEGIN_SRC org
6464#+ATTR_ORG: :width 400
@@ -67,6 +67,7 @@ A line shows as an image when it holds nothing but a link to an image file with
6767
6868- Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=.
6969- Paths are relative to the file's folder; =~= is expanded. Images at http(s) links show when =org-display-remote-inline-images= is =download= or =cache=; see [[file:09-links.org::*Remote images][Remote images]].
70- =attachment:= links, such as =[[attachment:photo.jpg]]=, show the file from the entry's attachment folder, found as following the link finds it: the =DIR= property, else the =ID= folder under =org-attach-id-dir=. See [[file:04-outlines.org][Outlines]] for attachments.
7071- =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor.
7172- The link text is hidden while its image shows, except on the caret's line.
7273