Commit 92e4b38d50

92e4b38d5077c52139787ff3d336aaa24a6b9a20

parent: 2e84e47b2b

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 22:54 UTC

Inline images for attachment: links

attachment: image links show inline in the Mac and iOS editors and the iOS reader, resolved through the entry's attachment folder (DIR, else the ID folder under org-attach-id-dir) as following the link does.

Closes #0

Layout: unified · split

Sources/OrgApp/LinkFollow.swift +7 −1
@@ -83,7 +83,13 @@ extension DocumentSession {
83 return searchCurrent(option) 83 return searchCurrent(option)
84 } 84 }
85 85
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 {
87 var directory: ObjCBool = false 93 var directory: ObjCBool = false
88 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue 94 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
89 } 95 }
Sources/OrgCore/Commands/InlineImages.swift +10 −4
@@ -1,7 +1,8 @@
1import Foundation 1import Foundation
2 2
3/// Image links shown as images (`org-display-inline-images`, Org 9.8.7): a line that is only a 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. 4/// `file:` or `attachment:` link to an image, without a description, and the width
5/// `#+ATTR_ORG: :width` asks for.
5public enum InlineImages { 6public enum InlineImages {
6 public struct Image: Sendable, Equatable { 7 public struct Image: Sendable, Equatable {
7 public let path: String 8 public let path: String
@@ -13,12 +14,17 @@ public enum InlineImages {
13 14
14 /// The image on the line at `lineStart`, if the line is an image link; with `remote`, 15 /// 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 /// 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? {
17 let line = text.lineRange(for: NSRange(location: lineStart, length: 0)) 20 let line = text.lineRange(for: NSRange(location: lineStart, length: 0))
18 let content = text.substring(with: line).trimmingCharacters(in: .newlines) 21 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 } 22 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)) 23 var path = (content as NSString).substring(with: m.range(at: 1))
21 guard !path.hasPrefix("attachment:") else { return nil } 24 if path.hasPrefix("attachment:") {
25 guard let file = attachment?(String(path.dropFirst("attachment:".count)), line.location) else { return nil }
26 path = file
27 }
22 if path.contains("://") { 28 if path.contains("://") {
23 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil } 29 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
24 } 30 }
Sources/OrgEditorAppKit/OrgEditor+Images.swift +9 −2
@@ -17,7 +17,7 @@ extension OrgEditor {
17 var offset = 0 17 var offset = 0
18 while offset < ns.length { 18 while offset < ns.length {
19 let line = ns.lineRange(for: NSRange(location: offset, length: 0)) 19 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 }
21 offset = NSMaxRange(line) 21 offset = NSMaxRange(line)
22 } 22 }
23 onMessage?("\(count) images displayed inline") 23 onMessage?("\(count) images displayed inline")
@@ -34,6 +34,13 @@ extension OrgEditor {
34 redrawViews() 34 redrawViews()
35 } 35 }
36 36
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
37 /// Whether http(s) links show, as `org-display-remote-inline-images` says. 44 /// Whether http(s) links show, as `org-display-remote-inline-images` says.
38 private var remote: Bool { options.remoteInlineImages != "skip" } 45 private var remote: Bool { options.remoteInlineImages != "skip" }
39 46
@@ -67,7 +74,7 @@ extension OrgEditor {
67 while location < range.upperBound, location < text.length { 74 while location < range.upperBound, location < text.length {
68 let line = text.lineRange(for: NSRange(location: location, length: 0)) 75 let line = text.lineRange(for: NSRange(location: location, length: 0))
69 location = NSMaxRange(line) 76 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 }
71 var width = image.width.map(CGFloat.init) ?? picture.size.width 78 var width = image.width.map(CGFloat.init) ?? picture.size.width
72 width = min(width, maxWidth) 79 width = min(width, maxWidth)
73 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 80 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 {
684 public internal(set) var showsImages = false 684 public internal(set) var showsImages = false
685 /// `org-latex-preview`: LaTeX fragments show as typeset math. 685 /// `org-latex-preview`: LaTeX fragments show as typeset math.
686 public internal(set) var showsLatex = false 686 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?)?
687 /// The file's folder, for relative image paths. 690 /// The file's folder, for relative image paths.
688 public var baseDirectory: URL? { 691 public var baseDirectory: URL? {
689 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } } 692 didSet { if showsImages, oldValue != baseDirectory { refreshImages() } }
Sources/Orgstar/PaneView.swift +1
@@ -91,6 +91,7 @@ struct PaneView: NSViewRepresentable {
91 let store = commands.store 91 let store = commands.store
92 editor.onChange = { [weak session] in session?.bufferChanged(path) } 92 editor.onChange = { [weak session] in session?.bufferChanged(path) }
93 editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent() 93 editor.baseDirectory = URL(fileURLWithPath: path).deletingLastPathComponent()
94 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
94 editor.onMessage = { [weak commands] in commands?.show($0) } 95 editor.onMessage = { [weak commands] in commands?.show($0) }
95 editor.onKeysPending = { [weak commands] keys, next in 96 editor.onKeysPending = { [weak commands] keys, next in
96 commands?.pendingKeys = keys 97 commands?.pendingKeys = keys
Sources/OrgstarMobile/EditorScreen.swift +4 −1
@@ -384,10 +384,13 @@ struct EditorScreen: View {
384 384
385 private func makeEditor() -> MobileEditor? { 385 private func makeEditor() -> MobileEditor? {
386 guard let document = session.document(of: path) else { return nil } 386 guard let document = session.document(of: path) else { return nil }
387 return MobileEditor( 387 let editor = MobileEditor(
388 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme, 388 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
389 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent() 389 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
390 ) 390 )
391 let path = path
392 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
393 return editor
391 } 394 }
392 395
393 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus. 396 /// 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 {
60 var offset = 0 60 var offset = 0
61 while offset < ns.length { 61 while offset < ns.length {
62 let line = ns.lineRange(for: NSRange(location: offset, length: 0)) 62 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),
64 loadImage(image.path) != nil { count += 1 } 64 loadImage(image.path) != nil { count += 1 }
65 offset = NSMaxRange(line) 65 offset = NSMaxRange(line)
66 } 66 }
@@ -70,6 +70,13 @@ extension MobileEditor {
70 } 70 }
71 } 71 }
72 72
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
73 /// An image link's image here: remote ones as `org-display-remote-inline-images` says, 80 /// An image link's image here: remote ones as `org-display-remote-inline-images` says,
74 /// restyled when they come. 81 /// restyled when they come.
75 func loadImage(_ path: String) -> UIImage? { 82 func loadImage(_ path: String) -> UIImage? {
@@ -114,7 +121,7 @@ extension MobileEditor {
114 while location < range.upperBound, location < text.length { 121 while location < range.upperBound, location < text.length {
115 let line = text.lineRange(for: NSRange(location: location, length: 0)) 122 let line = text.lineRange(for: NSRange(location: location, length: 0))
116 location = NSMaxRange(line) 123 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),
118 let picture = loadImage(image.path) else { continue } 125 let picture = loadImage(image.path) else { continue }
119 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth) 126 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
120 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0 127 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 {
121 var imageWidth: CGFloat = 0 121 var imageWidth: CGFloat = 0
122 /// The file's folder, for relative image paths. 122 /// The file's folder, for relative image paths.
123 let baseDirectory: URL? 123 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?)?
124 static let imageCache = NSCache<NSString, UIImage>() 127 static let imageCache = NSCache<NSString, UIImage>()
125 var loading = false 128 var loading = false
126 var restyleScheduled: Range<Int>? 129 var restyleScheduled: Range<Int>?
Sources/OrgstarMobile/ReaderScreen.swift +2 −1
@@ -228,7 +228,8 @@ struct ReaderScreen: View {
228 while location < range.upperBound { 228 while location < range.upperBound {
229 let line = ns.lineRange(for: NSRange(location: location, length: 0)) 229 let line = ns.lineRange(for: NSRange(location: location, length: 0))
230 location = NSMaxRange(line) 230 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) }),
232 let picture = MobileEditor.loadImage(image.path, relativeTo: base, remote: remote) else { continue } 233 let picture = MobileEditor.loadImage(image.path, relativeTo: base, remote: remote) else { continue }
233 if textStart < line.location { parts.append(Part(range: textStart..<line.location)) } 234 if textStart < line.location { parts.append(Part(range: textStart..<line.location)) }
234 parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width))) 235 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 {
208 #expect(inbox.batches().isEmpty) 208 #expect(inbox.batches().isEmpty)
209 } 209 }
210} 210}
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 {
14 #expect(InlineImages.startup(OrgParser.parse("* x\n")) == nil) 14 #expect(InlineImages.startup(OrgParser.parse("* x\n")) == nil)
15 #expect(InlineImages.startup(OrgParser.parse("#+begin_src org\n#+STARTUP: inlineimages\n#+end_src\n")) == nil) 15 #expect(InlineImages.startup(OrgParser.parse("#+begin_src org\n#+STARTUP: inlineimages\n#+end_src\n")) == nil)
16 } 16 }
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 }
17} 35}
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
58 58
59Org ▸ 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. 59Org ▸ 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.
60 60
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:
62 62
63#+BEGIN_SRC org 63#+BEGIN_SRC org
64#+ATTR_ORG: :width 400 64#+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
67 67
68- Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=. 68- Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=.
69- 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]]. 69- 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.
70- =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor. 71- =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor.
71- The link text is hidden while its image shows, except on the caret's line. 72- The link text is hidden while its image shows, except on the caret's line.
72 73