Commit 4e8f923e9d

4e8f923e9db9ee53f2c3ed3614e827ba046c0d47

parent: 09c5ecd551

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 08:13 UTC

Fit inline images to the Mac editor's width when it changes

Images shown as a file opened were sized before the view had its width,
and were not sized again when the window was resized.

Ref #113

Layout: unified · split

Sources/OrgEditorAppKit/Keys.swift +9
@@ -59,10 +59,19 @@ final class OrgTextView: NSTextView {
5959 didSet { if textWidth != oldValue { updateGutter() } }
6060 }
6161
62 /// The view has another width; during a live resize, called once at its end.
63 var onWidthChange: (() -> Void)?
64
6265 override func setFrameSize(_ newSize: NSSize) {
6366 let widthChanged = newSize.width != frame.width
6467 super.setFrameSize(newSize)
6568 if widthChanged, textWidth > 0 { updateGutter() }
69 if widthChanged, !inLiveResize { onWidthChange?() }
70 }
71
72 override func viewDidEndLiveResize() {
73 super.viewDidEndLiveResize()
74 onWidthChange?()
6675 }
6776 var lineNumbersType = LineNumbersType.absolute {
6877 didSet { if lineNumbersType != oldValue { needsDisplay = true } }
Sources/OrgEditorAppKit/OrgEditor+Images.swift +16 −1
@@ -31,6 +31,20 @@ extension OrgEditor {
3131 redrawViews()
3232 }
3333
34 /// The widest an image shows: the text's width, less a margin.
35 private var imageMaxWidth: CGFloat { max(80, (textView.textContainer?.size.width ?? 600) - 40) }
36
37 /// Sizes images again once the view's width has changed, after the layout pass that changed it.
38 func fitImages() {
39 guard showsImages, !fittingImages else { return }
40 fittingImages = true
41 DispatchQueue.main.async { [weak self] in
42 guard let self else { return }
43 self.fittingImages = false
44 if self.showsImages, self.imageWidth != self.imageMaxWidth { self.refreshImages() }
45 }
46 }
47
3448 /// `attachment:` links' files, for inline images.
3549 private var attachment: ((String, Int) -> String?)? {
3650 guard let attachmentPath else { return nil }
@@ -68,7 +82,8 @@ extension OrgEditor {
6882 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
6983 guard showsImages, isOrg else { return }
7084 let text = storage.string as NSString
71 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
85 let maxWidth = imageMaxWidth
86 imageWidth = maxWidth
7287 let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
7388 for placement in Presentation.imagePlacements(links, in: text) {
7489 guard let picture = loadImage(placement.link.image.path) else { continue }
Sources/OrgEditorAppKit/OrgEditor.swift +4
@@ -184,6 +184,7 @@ public final class OrgEditor: NSObject {
184184 onImage(data, ext)
185185 return true
186186 }
187 view.onWidthChange = { [weak self] in self?.fitImages() }
187188 view.onMouseDown = { [weak self, unowned view] in
188189 self?.active = view
189190 self?.markActive = false
@@ -708,6 +709,9 @@ public final class OrgEditor: NSObject {
708709 public internal(set) var showsImages = false
709710 /// Links with a description show their image too.
710711 var imagesIncludeLinked = false
712 /// The width images were last sized for, and whether sizing them again is waiting.
713 var imageWidth: CGFloat = 0
714 var fittingImages = false
711715 /// `org-latex-preview`: LaTeX fragments show as typeset math.
712716 public internal(set) var showsLatex = false
713717 /// An `attachment:` link's file, from its name, offset and the tree: the app's
Tests/OrgEditorAppKitTests/InlineImagesEditorTests.swift +26 −6
@@ -9,15 +9,17 @@ struct InlineImagesEditorTests {
99 static let text = "* Images\n\(filler)[[file:pic.png]] \(filler)\n[[file:pic.png]]\n| a | [[file:pic.png]] | [[./pic.png]] |\n"
1010 + "Described [[file:pic.png][a figure]] here\nMissing [[file:missing.png]] here\n"
1111
12 /// A folder holding `pic.png`, 100 by 60 points.
12 /// A folder holding `pic.png`, 100 by 60 points, and `wide.png`, 2000 by 100.
1313 static func folder() throws -> URL {
1414 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-images-\(UUID().uuidString)")
1515 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
16 let bitmap = try #require(NSBitmapImageRep(
17 bitmapDataPlanes: nil, pixelsWide: 100, pixelsHigh: 60, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
18 colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
19 ))
20 try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent("pic.png"))
16 for (name, width, height) in [("pic.png", 100, 60), ("wide.png", 2000, 100)] {
17 let bitmap = try #require(NSBitmapImageRep(
18 bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
19 colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
20 ))
21 try #require(bitmap.representation(using: .png, properties: [:])).write(to: folder.appendingPathComponent(name))
22 }
2123 return folder
2224 }
2325
@@ -116,6 +118,24 @@ struct InlineImagesEditorTests {
116118 #expect(fragment.textLineFragments[0].typographicBounds.height >= 59)
117119 }
118120
121 /// Images wider than the text fit it, and fit it again when the view's width changes.
122 @Test func wideImagesFollowTheViewsWidth() async throws {
123 let folder = try Self.folder()
124 defer { try? FileManager.default.removeItem(at: folder) }
125 let h = Harness("* Wide\n[[file:wide.png]]\nIn text [[file:wide.png]] here\n")
126 h.editor.baseDirectory = folder
127 h.editor.run("org.toggle-inline-images")
128 func widths() -> [CGFloat] { [7, 33].compactMap { Self.box(h, at: $0)?.size.width } }
129 let container = try #require(h.textView.textContainer).size.width
130 #expect(container > 300 && widths() == [container - 40, container - 40])
131
132 h.window.setContentSize(NSSize(width: 420, height: 800))
133 h.window.contentView?.layoutSubtreeIfNeeded()
134 try await Task.sleep(for: .milliseconds(100))
135 let narrower = try #require(h.textView.textContainer).size.width
136 #expect(narrower < container && widths() == [narrower - 40, narrower - 40])
137 }
138
119139 @Test func describedLinksNeedTheirCommandAndMissingFilesStayLinks() throws {
120140 let folder = try Self.folder()
121141 defer { try? FileManager.default.removeItem(at: folder) }
docs/manual/guide/09-links.org +1 −1
@@ -633,7 +633,7 @@ Insert Link. Setting up a browser bookmarklet, and =org-protocol://capture=, are
633633
634634The iOS app follows links: tap a link in the reader. Org files open in the app, and
635635web, mail and other files go to the system. The iOS editor shows inline images as the
636Mac does; the reader doesn't. In the editor, Store Link, Store ID Link and Insert Link…
636Mac does, and so does the reader, except in headings. In the editor, Store Link, Store ID Link and Insert Link…
637637are in Commands, and on a hardware keyboard the Emacs keys run them; they work as
638638described above, and stored links last until the app quits. =org-protocol://store-link=
639639links opened on the device are stored and copied too. More ▸ Backlinks lists the same