Remote inline images !282

merged merged by cmc on 2026-10-11 13:40 UTC · krz/orgstar:issue-39 into main

13 files changed, +208 −15

Layout: unified · split

Sources/OrgApp/EmacsImport.swift +3
@@ -543,6 +543,9 @@ public struct EmacsImport: Sendable {
543543 else if let keywords = value.elements?.compactMap(\.string), !keywords.isEmpty, keywords.count == value.elements?.count {
544544 add(name, .string(keywords.joined(separator: " ")))
545545 } else { note("unexpected value \(value.description)") }
546 case "org-display-remote-inline-images":
547 guard let mode = value.symbol, ["skip", "download", "cache"].contains(mode) else { return note("not skip, download or cache") }
548 add(name, .string(mode))
546549 case "org-icalendar-combined-agenda-file":
547550 guard let file = value.string ?? Self.evaluate(value, env)?.string else { return note("not a file name") }
548551 add(name, .string(file))
Sources/OrgApp/OrgPreferences.swift +1
@@ -36,6 +36,7 @@ public enum OrgPreferences {
3636 )
3737 options.electricPair = bool("electricPair", defaults)
3838 options.startupWithLatexPreview = bool("startupWithLatexPreview", defaults)
39 options.remoteInlineImages = string("remoteInlineImages", defaults)
3940 options.enforceTodoDependencies = bool("enforceTodoDependencies", defaults)
4041 options.enforceTodoCheckboxDependencies = bool("enforceTodoCheckboxDependencies", defaults)
4142 options.archiveLocation = string("archiveLocation", defaults).nonEmpty
Sources/OrgApp/UserConfig.swift +3
@@ -147,6 +147,9 @@ public enum UserConfig {
147147 comment: "show image links as images when a file opens; #+STARTUP: (no)inlineimages overrides", legacy: ""),
148148 Setting(section: "", key: "org-startup-with-latex-preview", defaultsKey: "startupWithLatexPreview", kind: .bool, fallback: .bool(false),
149149 comment: "show LaTeX fragments as typeset math when a file opens; #+STARTUP: (no)latexpreview overrides", legacy: ""),
150 Setting(section: "", key: "org-display-remote-inline-images", defaultsKey: "remoteInlineImages",
151 kind: .choice([("skip", "skip"), ("download", "download"), ("cache", "cache")]), fallback: .string("skip"),
152 comment: "images at http(s) links: skip, download (each run) or cache (kept on disk)", legacy: ""),
150153 Setting(section: "", key: "org-use-speed-commands", defaultsKey: "useSpeedCommands", kind: .bool, fallback: .bool(false),
151154 comment: "single keys at the start of a heading line run commands (n, p, t, c, …)", legacy: ""),
152155 Setting(section: "", key: "org-cycle-hide-drawer-startup", defaultsKey: "hideDrawerStartup", kind: .bool, fallback: .bool(true),
Sources/OrgCore/Commands/Command.swift +2
@@ -56,6 +56,8 @@ public struct EditingOptions: Sendable, Equatable, Codable {
5656 public var startupWithInlineImages: Bool
5757 /// `org-startup-with-latex-preview`.
5858 public var startupWithLatexPreview = false
59 /// `org-display-remote-inline-images`: `skip`, `download` or `cache`.
60 public var remoteInlineImages = "skip"
5961 /// `org-startup-indented`: org-indent's virtual indentation.
6062 public var startupIndented = true
6163 /// `org-hide-leading-stars`; org-indent hides them too.
Sources/OrgCore/Commands/InlineImages.swift +7 −3
@@ -11,13 +11,17 @@ public enum InlineImages {
1111 static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif"
1212 static let pattern = try! NSRegularExpression(pattern: "^[ \\t]*\\[\\[(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))\\]\\][ \\t]*$", options: .caseInsensitive)
1313
14 /// The image on the line at `lineStart`, if the line is an image link.
15 public static func image(atLine lineStart: Int, in text: NSString) -> Image? {
14 /// 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 public static func image(atLine lineStart: Int, in text: NSString, remote: Bool = false) -> Image? {
1617 let line = text.lineRange(for: NSRange(location: lineStart, length: 0))
1718 let content = text.substring(with: line).trimmingCharacters(in: .newlines)
1819 guard let m = pattern.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) else { return nil }
1920 let path = (content as NSString).substring(with: m.range(at: 1))
20 guard !path.contains("://"), !path.hasPrefix("attachment:") else { return nil }
21 guard !path.hasPrefix("attachment:") else { return nil }
22 if path.contains("://") {
23 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
24 }
2125 // `#+ATTR_ORG: :width N` in the affiliated keywords above.
2226 var width: Int?
2327 var at = line.location
Sources/OrgEditorAppKit/OrgEditor+Images.swift +15 −2
@@ -1,6 +1,7 @@
11#if os(macOS)
22import AppKit
33import OrgCore
4import OrgPresentation
45
56extension OrgEditor {
67 // MARK: - Inline images
@@ -16,7 +17,7 @@ extension OrgEditor {
1617 var offset = 0
1718 while offset < ns.length {
1819 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
19 if let image = InlineImages.image(atLine: line.location, in: ns), loadImage(image.path) != nil { count += 1 }
20 if let image = InlineImages.image(atLine: line.location, in: ns, remote: remote), loadImage(image.path) != nil { count += 1 }
2021 offset = NSMaxRange(line)
2122 }
2223 onMessage?("\(count) images displayed inline")
@@ -33,7 +34,19 @@ extension OrgEditor {
3334 redrawViews()
3435 }
3536
37 /// Whether http(s) links show, as `org-display-remote-inline-images` says.
38 private var remote: Bool { options.remoteInlineImages != "skip" }
39
3640 private func loadImage(_ path: String) -> NSImage? {
41 if path.contains("://") {
42 guard let url = URL(string: path) else { return nil }
43 let mode = RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip
44 let data = RemoteImages.shared.data(for: url, mode: mode) { [weak self] in
45 guard let self, self.showsImages else { return }
46 self.refreshImages()
47 }
48 return data.flatMap(NSImage.init(data:))
49 }
3750 let expanded = (path as NSString).expandingTildeInPath
3851 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (baseDirectory ?? URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).appendingPathComponent(expanded)
3952 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
@@ -54,7 +67,7 @@ extension OrgEditor {
5467 while location < range.upperBound, location < text.length {
5568 let line = text.lineRange(for: NSRange(location: location, length: 0))
5669 location = NSMaxRange(line)
57 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = loadImage(image.path) else { continue }
70 guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote), let picture = loadImage(image.path) else { continue }
5871 var width = image.width.map(CGFloat.init) ?? picture.size.width
5972 width = min(width, maxWidth)
6073 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
Sources/OrgPresentation/RemoteImages.swift added +74
@@ -0,0 +1,74 @@
1import CryptoKit
2import Foundation
3import Observation
4
5/// `org-display-remote-inline-images`: images at http and https links, fetched in the
6/// background. `download` keeps them while the app runs; `cache` keeps them on disk too.
7@MainActor
8@Observable
9public final class RemoteImages {
10 public static let shared = RemoteImages()
11
12 public enum Mode: String, Sendable {
13 case skip, download, cache
14 }
15
16 /// Changes when an image arrives, for views that show them.
17 public private(set) var version = 0
18 @ObservationIgnored private var memory: [URL: Data] = [:]
19 @ObservationIgnored private var loading: Set<URL> = []
20 @ObservationIgnored private var failed: Set<URL> = []
21 @ObservationIgnored private var waiting: [URL: [@MainActor () -> Void]] = [:]
22 @ObservationIgnored let directory: URL
23 @ObservationIgnored let fetch: @Sendable (URL) async throws -> Data
24
25 public init(directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("RemoteImages"),
26 fetch: @escaping @Sendable (URL) async throws -> Data = RemoteImages.download) {
27 self.directory = directory
28 self.fetch = fetch
29 }
30
31 /// An http(s) GET; other statuses than 2xx fail.
32 public nonisolated static func download(_ url: URL) async throws -> Data {
33 let (data, response) = try await URLSession.shared.data(from: url)
34 if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { throw URLError(.badServerResponse) }
35 return data
36 }
37
38 /// The image's data when it's here; otherwise nil, and `loaded` runs when it has come.
39 /// A link that failed isn't fetched again while the app runs.
40 public func data(for url: URL, mode: Mode, loaded: @escaping @MainActor () -> Void) -> Data? {
41 guard mode != .skip, let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil }
42 if let data = memory[url] { return data }
43 if mode == .cache, let data = try? Data(contentsOf: file(url)) {
44 memory[url] = data
45 return data
46 }
47 guard !failed.contains(url) else { return nil }
48 waiting[url, default: []].append(loaded)
49 guard loading.insert(url).inserted else { return nil }
50 let fetch = self.fetch
51 Task {
52 let data = try? await fetch(url)
53 loading.remove(url)
54 if let data {
55 memory[url] = data
56 if mode == .cache {
57 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
58 try? data.write(to: file(url), options: .atomic)
59 }
60 } else {
61 failed.insert(url)
62 }
63 version += 1
64 for callback in waiting.removeValue(forKey: url) ?? [] { callback() }
65 }
66 return nil
67 }
68
69 /// The cached copy's file, named by a hash of the link.
70 func file(_ url: URL) -> URL {
71 let hash = SHA256.hash(data: Data(url.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined()
72 return directory.appendingPathComponent(hash + (url.pathExtension.isEmpty ? "" : "." + url.pathExtension))
73 }
74}
Sources/OrgstarMobile/MobileEditor+Display.swift +20 −4
@@ -60,7 +60,8 @@ 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), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 }
63 if let image = InlineImages.image(atLine: line.location, in: ns, remote: options.remoteInlineImages != "skip"),
64 loadImage(image.path) != nil { count += 1 }
6465 offset = NSMaxRange(line)
6566 }
6667 onMessage?("\(count) images displayed inline")
@@ -69,8 +70,22 @@ extension MobileEditor {
6970 }
7071 }
7172
72 /// An image link's image, by its path or one relative to `baseDirectory`.
73 static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? {
73 /// An image link's image here: remote ones as `org-display-remote-inline-images` says,
74 /// restyled when they come.
75 func loadImage(_ path: String) -> UIImage? {
76 Self.loadImage(path, relativeTo: baseDirectory, remote: RemoteImages.Mode(rawValue: options.remoteInlineImages) ?? .skip) { [weak self] in
77 guard let self, self.showsImages else { return }
78 self.restyleAll()
79 }
80 }
81
82 /// An image link's image, by its path or one relative to `baseDirectory`; an http(s)
83 /// link's when `remote` allows it and it has come, `loaded` running when it does.
84 static func loadImage(_ path: String, relativeTo baseDirectory: URL?, remote: RemoteImages.Mode = .skip, loaded: @escaping @MainActor () -> Void = {}) -> UIImage? {
85 if path.contains("://") {
86 guard let url = URL(string: path) else { return nil }
87 return RemoteImages.shared.data(for: url, mode: remote, loaded: loaded).flatMap(UIImage.init(data:))
88 }
7489 let expanded = (path as NSString).expandingTildeInPath
7590 let url: URL
7691 if expanded.hasPrefix("/") {
@@ -99,7 +114,8 @@ extension MobileEditor {
99114 while location < range.upperBound, location < text.length {
100115 let line = text.lineRange(for: NSRange(location: location, length: 0))
101116 location = NSMaxRange(line)
102 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue }
117 guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip"),
118 let picture = loadImage(image.path) else { continue }
103119 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
104120 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
105121 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
Sources/OrgstarMobile/ReaderScreen.swift +5 −2
@@ -211,6 +211,9 @@ struct ReaderScreen: View {
211211 /// Text, and with inline images on, lines that are only an image link shown as the image.
212212 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
213213 guard startup?.inlineImages == true, let path = session.path else { return [Part(range: range)] }
214 // Read so that the view draws again when a remote image arrives.
215 _ = RemoteImages.shared.version
216 let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip
214217 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
215218 let ns = tree.text as NSString
216219 var parts: [Part] = []
@@ -219,8 +222,8 @@ struct ReaderScreen: View {
219222 while location < range.upperBound {
220223 let line = ns.lineRange(for: NSRange(location: location, length: 0))
221224 location = NSMaxRange(line)
222 guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns),
223 let picture = MobileEditor.loadImage(image.path, relativeTo: base) else { continue }
225 guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns, remote: remote != .skip),
226 let picture = MobileEditor.loadImage(image.path, relativeTo: base, remote: remote) else { continue }
224227 if textStart < line.location { parts.append(Part(range: textStart..<line.location)) }
225228 parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width)))
226229 textStart = min(NSMaxRange(line), range.upperBound)
Tests/OrgPresentationTests/RemoteImagesTests.swift added +51
@@ -0,0 +1,51 @@
1import Foundation
2import OrgCore
3@testable import OrgPresentation
4import Testing
5
6@MainActor
7struct RemoteImagesTests {
8 final class Counter: @unchecked Sendable {
9 var calls = 0
10 }
11
12 @Test func linksNeedTheSetting() {
13 let text = "[[https://example.com/a.png]]\n[[ftp://example.com/b.png]]\n[[file:c.png]]\n" as NSString
14 #expect(InlineImages.image(atLine: 0, in: text) == nil)
15 #expect(InlineImages.image(atLine: 0, in: text, remote: true)?.path == "https://example.com/a.png")
16 #expect(InlineImages.image(atLine: 30, in: text, remote: true) == nil)
17 #expect(InlineImages.image(atLine: 58, in: text, remote: true)?.path == "c.png")
18 }
19
20 @Test func downloadsOnceAndCaches() async throws {
21 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-remote-\(UUID().uuidString)")
22 defer { try? FileManager.default.removeItem(at: folder) }
23 let counter = Counter()
24 let images = RemoteImages(directory: folder) { url in
25 counter.calls += 1
26 if url.lastPathComponent == "missing.png" { throw URLError(.badServerResponse) }
27 return Data("image".utf8)
28 }
29 let url = URL(string: "https://example.com/a.png")!
30 #expect(images.data(for: url, mode: .skip) {} == nil)
31 var arrived = false
32 #expect(images.data(for: url, mode: .cache) { arrived = true } == nil)
33 #expect(images.data(for: url, mode: .cache) {} == nil)
34 while !arrived { try await Task.sleep(for: .milliseconds(10)) }
35 #expect(images.data(for: url, mode: .cache) {} == Data("image".utf8))
36 #expect(counter.calls == 1)
37 // A new run reads the cached copy.
38 let again = RemoteImages(directory: folder) { _ in Issue.record("fetched again"); return Data() }
39 #expect(again.data(for: url, mode: .cache) {} == Data("image".utf8))
40 #expect(again.data(for: url, mode: .download) {} == Data("image".utf8))
41
42 let missing = URL(string: "https://example.com/missing.png")!
43 var done = false
44 #expect(images.data(for: missing, mode: .download) { done = true } == nil)
45 while !done { try await Task.sleep(for: .milliseconds(10)) }
46 #expect(images.data(for: missing, mode: .download) {} == nil)
47 #expect(counter.calls == 2)
48 #expect(images.version == 2)
49 #expect(images.data(for: URL(string: "file:///tmp/a.png")!, mode: .cache) {} == nil)
50 }
51}
docs/manual/guide/02-the-editor.org +1 −1
@@ -66,7 +66,7 @@ A line shows as an image when it holds nothing but a link to an image file with
6666#+END_SRC
6767
6868- Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=.
69- Paths are relative to the file's folder; =~= is expanded. Remote URLs are not displayed.
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]].
7070- =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor.
7171- The link text is hidden while its image shows, except on the caret's line.
7272
docs/manual/guide/09-links.org +23 −3
@@ -302,9 +302,29 @@ to a file ending in =.png=, =.jpg=, =.jpeg=, =.gif=, =.svg=, =.webp=, =.tif=, =.
302302[[./photo.jpg]]
303303#+END_SRC
304304
305Relative paths are resolved against the file's folder. Web addresses and
306=attachment:= links are not shown as images. The link text is hidden while the image
307is shown, except on the line that holds the caret.
305Relative paths are resolved against the file's folder. =attachment:= links are not
306shown as images. The link text is hidden while the image is shown, except on the line
307that holds the caret.
308
309** Remote images
310
311Images at =http= and =https= links show as =org-display-remote-inline-images= in
312=config.toml= says:
313
314| Value | Remote images |
315|------------+------------------------------------------------------------------------------|
316| =skip= | Not shown; the default |
317| =download= | Fetched the first time they're shown, and kept until orgstar quits |
318| =cache= | Fetched once and kept on disk, in the app's cache folder, for later launches |
319
320#+BEGIN_SRC org
321[[https://example.com/chart.png]]
322#+END_SRC
323
324An image is fetched in the background; the link shows as text until it arrives. A link
325that can't be fetched stays text, and isn't tried again until orgstar starts again. This
326applies to the editor on the Mac and iOS and to the iOS reader. Emacs's =download=
327fetches the image each time it's displayed; orgstar keeps it for the session instead.
308328
309329** Sizing
310330
docs/manual/guide/13-configuration.org +3
@@ -147,6 +147,7 @@ These settings have no control in the Settings window. Some are in the View menu
147147| =org-startup-align-all-tables= | |
148148| =org-startup-with-inline-images= | |
149149| =org-startup-with-latex-preview= | |
150| =org-display-remote-inline-images= | |
150151| =org-cycle-hide-drawer-startup= | |
151152| =org-cycle-hide-block-startup= | |
152153| =org-use-speed-commands= | |
@@ -214,6 +215,7 @@ A key you remove from the file goes back to its default. A key that isn't in the
214215| =spell-check= | boolean | =false= | Check spelling while typing, outside code, links, dates, tags and keywords. |
215216| =electric-pair-mode= | boolean | =true= | Type brackets, =<>= and quotes in pairs. Mirrors =electric-pair-mode=. |
216217| =org-startup-with-inline-images= | boolean | =false= | Show image links as images when a file opens. =#+STARTUP: inlineimages= / =noinlineimages= override it. Mirrors =org-startup-with-inline-images=. |
218| =org-display-remote-inline-images= | string | ="skip"= | Images at http(s) links: =skip=, =download= (kept until orgstar quits) or =cache= (kept on disk). See [[file:09-links.org][Links]]. Mirrors =org-display-remote-inline-images=. |
217219| =org-startup-with-latex-preview= | boolean | =false= | Show LaTeX fragments as typeset math when a file opens. =#+STARTUP: latexpreview= / =nolatexpreview= override it. Mirrors =org-startup-with-latex-preview=. |
218220| =org-use-speed-commands= | boolean | =false= | Single keys at the start of a heading line run commands (=n=, =p=, =t=, =c=, …). Mirrors =org-use-speed-commands=. |
219221| =org-cycle-hide-drawer-startup= | boolean | =true= | Fold drawers when a file opens. =#+STARTUP: hidedrawers= / =nohidedrawers= override it. Mirrors =org-cycle-hide-drawer-startup=. |
@@ -543,6 +545,7 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
543545| =org-icalendar-use-deadline=, =org-icalendar-use-scheduled= | The list's symbols, separated by spaces |
544546| =org-icalendar-include-todo= | =nil=, =t=, =all= or =unblocked=, or a list of keywords separated by spaces |
545547| =org-icalendar-combined-agenda-file= | The file name, from a string or a simple form |
548| =org-display-remote-inline-images= | The symbol as a string, when it's =skip=, =download= or =cache= |
546549| =org-publish-project-alist= | A =[[publish]]= table in =config.toml= per project whose publishing functions are =org-html-publish-to-html=, =org-md-publish-to-md= or =org-publish-attachment=: the directories, =:base-extension=, =:recursive=, =:exclude=, =:include=, =:body-only=, the sitemap properties and =:components=. Other properties are reported as left out |
547550| =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= |
548551| =org-log-into-drawer= | A string as given; =t= becomes ="LOGBOOK"=; =nil= becomes =""= |