Show inline images in a line's text and for described links !452

merged merged by cmc on 2026-11-22 08:24 UTC · krz/orgstar:issue-113-inline-images into main

27 files changed, +790 −174

Layout: unified · split

Sources/OrgApp/CommandTitles.swift +1
@@ -283,6 +283,7 @@ enum CommandTitles {
283283 String(localized: "Show or Hide Backlinks", comment: "Command title"),
284284 String(localized: "Show or Hide Columns and Clock", comment: "Command title"),
285285 String(localized: "Show or Hide Inline Images", comment: "Command title"),
286 String(localized: "Show or Hide Inline Images, Including Described Links", comment: "Command title"),
286287 String(localized: "Show or Hide LaTeX Previews", comment: "Command title"),
287288 String(localized: "Show or Hide Line Numbers", comment: "Command title"),
288289 String(localized: "Show or Hide Markup", comment: "Command title"),
Sources/OrgCore/Commands/InlineImages.swift +94 −21
@@ -1,36 +1,109 @@
11import Foundation
22
3/// Image links shown as images (`org-display-inline-images`, Org 9.8.7): a line that is only a
4/// `file:` or `attachment:` link to an image, without a description, and the width
5/// `#+ATTR_ORG: :width` asks for.
3/// Image links shown as images (`org-link-preview-region`, Org 9.8.7): `file:` and
4/// `attachment:` links to an image, and the width `#+ATTR_ORG: :width` asks for.
65public enum InlineImages {
76 public struct Image: Sendable, Equatable {
87 public let path: String
98 public let width: Int?
109 }
1110
11 /// A link shown as an image, and the text the image stands for.
12 public struct Link: Sendable, Equatable {
13 public let range: Range<Int>
14 public let image: Image
15 }
16
1217 static let extensions = "png|jpe?g|gif|svg|webp|tiff?|bmp|heic|avif"
13 static let pattern = try! NSRegularExpression(pattern: "^[ \\t]*\\[\\[(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))\\]\\][ \\t]*$", options: .caseInsensitive)
18 static let imagePath = try! NSRegularExpression(pattern: "^(?:file:)?([^\\]\\n]+\\.(?:\(extensions)))$", options: .caseInsensitive)
19 static let bracketLink = try! NSRegularExpression(pattern: "\\[\\[([^\\]\\n]+)\\](?:\\[([^\\]\\n]+)\\])?\\]")
1420
15 /// The image on the line at `lineStart`, if the line is an image link; with `remote`,
16 /// http and https links too (`org-display-remote-inline-images` other than `skip`).
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? {
20 let line = text.lineRange(for: NSRange(location: lineStart, length: 0))
21 let content = text.substring(with: line).trimmingCharacters(in: .newlines)
22 guard let m = pattern.firstMatch(in: content, range: NSRange(location: 0, length: (content as NSString).length)) 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
21 /// The image links overlapping `range`, in order. A link without a description shows its
22 /// path. One with a description shows the description, and the image stands for the
23 /// description alone, when that is a single `file:` or `attachment:` link, plain or in
24 /// angle brackets; with `includeLinked` (`org-toggle-inline-images` with a prefix
25 /// argument) it shows its path instead. With `remote`, http and https paths too
26 /// (`org-display-remote-inline-images` other than `skip`). `attachment` gives an
27 /// `attachment:` link's file from its name and offset, as `org-attach-expand` does;
28 /// without it those links don't show.
29 public static func links(
30 _ tree: OrgTree, in range: Range<Int>, includeLinked: Bool = false, remote: Bool = false, attachment: ((String, Int) -> String?)? = nil
31 ) -> [Link] {
32 var out: [Link] = []
33 func add(_ target: String?, _ link: Range<Int>, widthFrom line: Int?) {
34 guard let target, let m = imagePath.firstMatch(in: target, range: NSRange(location: 0, length: (target as NSString).length)) else { return }
35 var path = (target as NSString).substring(with: m.range(at: 1))
36 if path.hasPrefix("attachment:") {
37 guard let file = attachment?(String(path.dropFirst("attachment:".count)), link.lowerBound) else { return }
38 path = file
39 }
40 if path.contains("://") {
41 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return }
42 }
43 out.append(Link(range: link, image: Image(path: path, width: line.flatMap { width(above: $0, in: tree.text as NSString) })))
44 }
45 func bracket(path: String, _ link: Range<Int>, description: String?, _ described: Range<Int>?, widthFrom line: Int?) {
46 if let description, let described, !includeLinked {
47 add(plainTarget(description), described, widthFrom: line)
48 } else {
49 add(path, link, widthFrom: line)
50 }
51 }
52 // Org text the tree keeps as a line: its bracket links.
53 func scan(_ line: SyntaxToken, widthFrom start: Int?) {
54 let content = line.text as NSString
55 for m in bracketLink.matches(in: line.text, range: NSRange(location: 0, length: content.length)) {
56 let offset = line.range.lowerBound
57 let described = m.range(at: 2).location == NSNotFound ? nil : m.range(at: 2)
58 bracket(path: content.substring(with: m.range(at: 1)), (offset + m.range.location)..<(offset + NSMaxRange(m.range)),
59 description: described.map(content.substring(with:)), described.map { (offset + $0.location)..<(offset + NSMaxRange($0)) }, widthFrom: start)
60 }
2761 }
28 if path.contains("://") {
29 guard remote, path.range(of: "^https?://", options: [.regularExpression, .caseInsensitive]) != nil else { return nil }
62 func walk(_ node: SyntaxNode, paragraph: Int?) {
63 switch node.kind {
64 case .link:
65 if let path = node.linkPath {
66 let description = node.firstChild(.linkDescription)
67 bracket(path: path, node.range, description: description?.text, description?.range, widthFrom: paragraph)
68 } else {
69 add(plainTarget(node.text), node.range, widthFrom: paragraph)
70 }
71 case .block:
72 // Quote, center, verse and special blocks hold Org text.
73 guard case .token(let opening)? = node.green.children.first,
74 opening.text.range(of: "^[ \\t]*#\\+begin_(?:src|example|export|comment)\\b", options: [.regularExpression, .caseInsensitive]) == nil else { return }
75 let lines = node.tokens.filter { $0.kind == .text }
76 for line in lines.dropFirst().dropLast() where line.range.overlaps(range) { scan(line, widthFrom: line.range.lowerBound) }
77 case .affiliatedKeyword:
78 // A caption is Org text too.
79 for line in node.tokens where line.kind == .text && line.text.range(of: "^[ \\t]*#\\+CAPTION(?:\\[.*\\])?:", options: [.regularExpression, .caseInsensitive]) != nil {
80 scan(line, widthFrom: nil)
81 }
82 case .paragraph:
83 // An item's first paragraph starts after the bullet and takes no affiliated keywords.
84 let start = node.parent?.kind == .item ? nil : node.range.lowerBound
85 for child in node.children(overlapping: range) { walk(child, paragraph: start) }
86 default:
87 for child in node.children(overlapping: range) { walk(child, paragraph: paragraph) }
88 }
3089 }
31 // `#+ATTR_ORG: :width N` in the affiliated keywords above.
90 walk(tree.root, paragraph: nil)
91 return out
92 }
93
94 /// A plain or angle link with an explicit `file:` or `attachment:` type.
95 static func plainTarget(_ link: String) -> String? {
96 var target = Substring(link)
97 if target.hasPrefix("<"), target.hasSuffix(">") { target = target.dropFirst().dropLast() }
98 guard target.hasPrefix("file:") || target.hasPrefix("attachment:"), !target.contains(where: { $0 == "\n" || $0 == "<" || $0 == ">" }),
99 link.hasPrefix("<") || !target.contains(where: \.isWhitespace) else { return nil }
100 return String(target)
101 }
102
103 /// `#+ATTR_ORG: :width N` in the affiliated keywords above the line at `lineStart`.
104 static func width(above lineStart: Int, in text: NSString) -> Int? {
32105 var width: Int?
33 var at = line.location
106 var at = lineStart
34107 while at > 0 {
35108 let previous = text.lineRange(for: NSRange(location: at - 1, length: 0))
36109 let keyword = text.substring(with: previous)
@@ -38,7 +111,7 @@ public enum InlineImages {
38111 if width == nil, let w = keyword.firstMatch(of: /(?i)^[ \t]*#\+ATTR_ORG:.*:width[ \t]+([0-9]+)/) { width = Int(w.1) }
39112 at = previous.location
40113 }
41 return Image(path: path, width: width)
114 return width
42115 }
43116
44117 /// `#+STARTUP: inlineimages` or `noinlineimages`, if the file says.
Sources/OrgCore/Keymap/PresetEmacs.swift +3
@@ -200,6 +200,9 @@ extension KeymapPreset {
200200 keys = "C-c C-x C-v"
201201 command = "org.toggle-inline-images"
202202 [[bind]]
203 keys = "C-u C-c C-x C-v"
204 command = "org.toggle-inline-images-linked"
205 [[bind]]
203206 keys = "C-c C-x C-l"
204207 command = "org.latex-preview"
205208 [[bind]]
Sources/OrgEditorAppKit/EditorCommands.swift +1
@@ -53,6 +53,7 @@ public enum EditorCommands {
5353 EditorCommand(id: "org.widen", title: "Widen", action: .view),
5454 EditorCommand(id: "org.narrow.toggle", title: "Narrow to Subtree or Widen", action: .view),
5555 EditorCommand(id: "org.toggle-inline-images", title: "Show or Hide Inline Images", action: .view),
56 EditorCommand(id: "org.toggle-inline-images-linked", title: "Show or Hide Inline Images, Including Described Links", action: .view),
5657 EditorCommand(id: "org.latex-preview", title: "Show or Hide LaTeX Previews", action: .view),
5758 EditorCommand(id: "editor.complete", title: "Complete at Point", action: .view),
5859 EditorCommand(id: "editor.toggle-spell-check", title: "Check Spelling While Typing", action: .view),
Sources/OrgEditorAppKit/Fragments.swift +49 −19
@@ -45,7 +45,7 @@ final class ShadedFragment: NSTextLayoutFragment, @unchecked Sendable {
4545extension NSAttributedString.Key {
4646 /// The character an entity shows as, on the entity's last character.
4747 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
48 /// The image an image link's line shows under it.
48 /// An image link's image, on the link's line or on its first character.
4949 static let orgImage = NSAttributedString.Key("OrgImage")
5050 /// A LaTeX fragment's typeset math, on its first character.
5151 static let orgLatex = NSAttributedString.Key("OrgLatex")
@@ -63,7 +63,7 @@ final class LatexBox: NSObject, @unchecked Sendable {
6363
6464/// A paragraph with LaTeX previews: each drawn where its hidden fragment starts, on the line's
6565/// baseline, or at the top of an environment's first line.
66final class LatexFragment: NSTextLayoutFragment, @unchecked Sendable {
66class LatexFragment: NSTextLayoutFragment, @unchecked Sendable {
6767 static func hasLatex(_ string: NSAttributedString) -> Bool {
6868 var found = false
6969 string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, _, stop in
@@ -114,42 +114,71 @@ final class LatexFragment: NSTextLayoutFragment, @unchecked Sendable {
114114final class InlineImageBox: NSObject, @unchecked Sendable {
115115 let image: NSImage
116116 let size: CGSize
117 /// Drawn under the line's text, which shows while the caret is on it.
117 /// Drawn under the text, which shows while the caret is on the line.
118118 let below: Bool
119 init(image: NSImage, size: CGSize, below: Bool = false) {
119 /// In the line's text where the link is, on a character as wide and as tall as the image;
120 /// otherwise the link is all the line holds.
121 let inText: Bool
122 init(image: NSImage, size: CGSize, below: Bool = false, inText: Bool = false) {
120123 self.image = image
121124 self.size = size
122125 self.below = below
126 self.inText = inText
123127 }
124128}
125129
126/// An image link's line drawn as the image, with the paragraph spacing making room for its
127/// height.
128final class ImageFragment: NSTextLayoutFragment, @unchecked Sendable {
129 static func image(_ string: NSAttributedString) -> InlineImageBox? {
130 var found: InlineImageBox?
130/// A paragraph with image links drawn as their images: a line's image with the paragraph
131/// spacing making room for its height, an image in the text on its hidden link.
132final class ImageFragment: LatexFragment, @unchecked Sendable {
133 static func hasImages(_ string: NSAttributedString) -> Bool {
134 var found = false
131135 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
132 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
136 if value != nil { found = true; stop.pointee = true }
133137 }
134138 return found
135139 }
136140
137 private var frame: CGRect? {
138 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let line = textLineFragments.first else { return nil }
139 return CGRect(x: line.typographicBounds.minX, y: (box.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: box.size.width, height: box.size.height)
141 /// Each image and where it goes, in the fragment's coordinates.
142 static func frames(of fragment: NSTextLayoutFragment) -> [(box: InlineImageBox, frame: CGRect)] {
143 guard let string = (fragment.textElement as? NSTextParagraph)?.attributedString, let first = fragment.textLineFragments.first else { return [] }
144 let last = fragment.textLineFragments.last { $0.characterRange.length > 0 } ?? first
145 var out: [(InlineImageBox, CGRect)] = []
146 // Images under the paragraph stand side by side.
147 var under = first.typographicBounds.minX
148 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, range, _ in
149 guard let box = value as? InlineImageBox else { return }
150 if !box.inText {
151 out.append((box, CGRect(origin: CGPoint(x: first.typographicBounds.minX, y: (box.below ? first.typographicBounds.maxY : first.typographicBounds.minY) + 2), size: box.size)))
152 } else if box.below {
153 out.append((box, CGRect(origin: CGPoint(x: under, y: last.typographicBounds.maxY + 2), size: box.size)))
154 under += box.size.width + 4
155 } else if let line = fragment.textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) {
156 let bounds = line.typographicBounds
157 let ascender = (string.attribute(.font, at: range.location, effectiveRange: nil) as? NSFont)?.ascender ?? box.size.height
158 out.append((box, CGRect(origin: CGPoint(x: bounds.minX + line.locationForCharacter(at: range.location).x, y: bounds.minY + line.glyphOrigin.y - ascender), size: box.size)))
159 }
160 }
161 return out
162 }
163
164 static func drawImages(of fragment: NSTextLayoutFragment, at point: CGPoint, in context: CGContext) {
165 let frames = frames(of: fragment)
166 guard !frames.isEmpty else { return }
167 NSGraphicsContext.saveGraphicsState()
168 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
169 for (box, frame) in frames {
170 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
171 }
172 NSGraphicsContext.restoreGraphicsState()
140173 }
141174
142175 override var renderingSurfaceBounds: CGRect {
143 frame.map { super.renderingSurfaceBounds.union($0) } ?? super.renderingSurfaceBounds
176 Self.frames(of: self).reduce(super.renderingSurfaceBounds) { $0.union($1.frame) }
144177 }
145178
146179 override func draw(at point: CGPoint, in context: CGContext) {
147180 super.draw(at: point, in: context)
148 guard let box = (textElement as? NSTextParagraph).flatMap({ Self.image($0.attributedString) }), let frame else { return }
149 NSGraphicsContext.saveGraphicsState()
150 NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
151 box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
152 NSGraphicsContext.restoreGraphicsState()
181 Self.drawImages(of: self, at: point, in: context)
153182 }
154183}
155184
@@ -192,6 +221,7 @@ final class FoldedHeadingFragment: NSTextLayoutFragment, @unchecked Sendable {
192221 override func draw(at point: CGPoint, in context: CGContext) {
193222 super.draw(at: point, in: context)
194223 EntityFragment.drawEntities(of: self, at: point, in: context)
224 ImageFragment.drawImages(of: self, at: point, in: context)
195225 guard let line = textLineFragments.first else { return }
196226 let bounds = line.typographicBounds
197227 let ellipsis = NSAttributedString(string: " …", attributes: [
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 +55 −26
@@ -8,18 +8,15 @@ extension OrgEditor {
88
99 private static let imageCache = NSCache<NSString, NSImage>()
1010
11 func toggleImages() {
11 /// `includeLinked` as `org-toggle-inline-images` with a prefix argument: links with a
12 /// description show their image too.
13 func toggleImages(includeLinked: Bool = false) {
1214 showsImages.toggle()
15 imagesIncludeLinked = showsImages && includeLinked
1316 refreshImages()
1417 if showsImages {
15 let ns = textView.string as NSString
16 var count = 0
17 var offset = 0
18 while offset < ns.length {
19 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
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)
22 }
18 let count = InlineImages.links(document.tree, in: 0..<utf16Length, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
19 .count { loadImage($0.image.path) != nil }
2320 onMessage?("\(count) images displayed inline")
2421 } else {
2522 onMessage?("Inline image display turned off")
@@ -34,6 +31,20 @@ extension OrgEditor {
3431 redrawViews()
3532 }
3633
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
3748 /// `attachment:` links' files, for inline images.
3849 private var attachment: ((String, Int) -> String?)? {
3950 guard let attachmentPath else { return nil }
@@ -64,32 +75,50 @@ extension OrgEditor {
6475 return image
6576 }
6677
67 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
68 /// on the line; then the image goes under it.
78 /// Image links in `range` show their image, and the link is hidden unless the caret is on
79 /// its line. A link that is all its line holds keeps the line, with the image over it, or
80 /// under it while the link shows. A link in a line's text is as wide and as tall as its
81 /// image, which goes under the paragraph while the link shows.
6982 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
7083 guard showsImages, isOrg else { return }
7184 let text = storage.string as NSString
72 let maxWidth = max(80, (textView.textContainer?.size.width ?? 600) - 40)
73 var location = range.lowerBound
74 while location < range.upperBound, location < text.length {
75 let line = text.lineRange(for: NSRange(location: location, length: 0))
76 location = NSMaxRange(line)
77 guard let image = InlineImages.image(atLine: line.location, in: text, remote: remote, attachment: attachment), let picture = loadImage(image.path) else { continue }
78 var width = image.width.map(CGFloat.init) ?? picture.size.width
79 width = min(width, maxWidth)
80 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
85 let maxWidth = imageMaxWidth
86 imageWidth = maxWidth
87 let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: remote, attachment: attachment)
88 for placement in Presentation.imagePlacements(links, in: text) {
89 guard let picture = loadImage(placement.link.image.path) else { continue }
90 let size = Presentation.imageSize(natural: picture.size, width: placement.link.image.width, maxWidth: maxWidth)
91 let link = NSRange(placement.link.range)
92 let line = text.lineRange(for: link)
93 let shown = NSLocationInRange(revealed.location, line)
94 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
95 defer { storage.addAttribute(.paragraphStyle, value: style, range: line) }
96 guard placement.ownLine else {
97 let first = NSRange(location: link.location, length: 1)
98 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown, inText: true), range: first)
99 if shown {
100 style.paragraphSpacing = max(style.paragraphSpacing, size.height + 4)
101 continue
102 }
103 // Pretty entities in the link would draw over the image.
104 storage.removeAttribute(.orgEntityDisplay, range: link)
105 storage.addAttributes(theme.hidden, range: link)
106 storage.addAttribute(.underlineStyle, value: 0, range: link)
107 let lineHeight = theme.font.ascender - theme.font.descender + theme.font.leading
108 let font = NSFont(descriptor: theme.font.fontDescriptor, size: Presentation.imageFontSize(height: size.height, pointSize: theme.font.pointSize, lineHeight: lineHeight)) ?? theme.font
109 let advance = text.substring(with: first).size(withAttributes: [.font: font]).width
110 storage.addAttributes([.font: font, .kern: size.width - advance], range: first)
111 continue
112 }
81113 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
82114 // Invisible, keeping the line's height, so line numbers stay apart.
83 let shown = line.location == revealed.location && content.length > 0
84 if !shown, content.length > 0 {
115 if !shown {
85116 storage.addAttributes([.foregroundColor: NSColor.clear, .underlineStyle: 0], range: content)
86117 }
87 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length)))
88 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
118 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown), range: content)
89119 // The image sits where the line is, or under it while the link shows; the spacing
90120 // makes room for the rest of it.
91 style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.boundingRectForFont.height)
92 storage.addAttribute(.paragraphStyle, value: style, range: line)
121 style.paragraphSpacing = shown ? size.height + 4 : max(0, size.height + 4 - theme.font.boundingRectForFont.height)
93122 }
94123 }
95124}
Sources/OrgEditorAppKit/OrgEditor+Styling.swift +2 −2
@@ -85,8 +85,8 @@ extension OrgEditor {
8585
8686 /// Moving to another line shows its markup and hides the last one's.
8787 func revealCaretLine() {
88 // LaTeX previews show their source on the caret's line whether or not markup shows.
89 guard !showMarkup || showsLatex, isOrg else { return }
88 // LaTeX previews and images show their source on the caret's line whether or not markup shows.
89 guard !showMarkup || showsLatex || showsImages, isOrg else { return }
9090 let line = caretLine
9191 guard line != revealedLine else { return }
9292 let text = textView.string as NSString
Sources/OrgEditorAppKit/OrgEditor.swift +9 −2
@@ -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
@@ -583,6 +584,7 @@ public final class OrgEditor: NSObject {
583584 case _ where id.hasPrefix("org.fold."): fold(id)
584585 case "org.narrow.subtree", "org.narrow.block", "org.narrow.toggle", "org.widen": narrow(id)
585586 case "org.toggle-inline-images": toggleImages()
587 case "org.toggle-inline-images-linked": toggleImages(includeLinked: true)
586588 case "org.latex-preview": toggleLatex()
587589 case "editor.toggle-spell-check": toggleSpellCheck()
588590 case "editor.complete": completeAtPoint()
@@ -703,8 +705,13 @@ public final class OrgEditor: NSObject {
703705
704706 // MARK: - Inline images
705707
706 /// `org-toggle-inline-images`: lines that are only an image link show the image.
708 /// `org-toggle-inline-images`: image links show their image.
707709 public internal(set) var showsImages = false
710 /// Links with a description show their image too.
711 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
708715 /// `org-latex-preview`: LaTeX fragments show as typeset math.
709716 public internal(set) var showsLatex = false
710717 /// An `attachment:` link's file, from its name, offset and the tree: the app's
@@ -972,7 +979,7 @@ extension OrgEditor: NSTextLayoutManagerDelegate {
972979 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
973980 if folded.contains(offset) { return FoldedHeadingFragment(textElement: textElement, range: range) }
974981 if shaded.containing(offset) != nil { return ShadedFragment(textElement: textElement, range: range) }
975 if let paragraph = textElement as? NSTextParagraph, ImageFragment.image(paragraph.attributedString) != nil {
982 if let paragraph = textElement as? NSTextParagraph, ImageFragment.hasImages(paragraph.attributedString) {
976983 return ImageFragment(textElement: textElement, range: range)
977984 }
978985 if let paragraph = textElement as? NSTextParagraph, LatexFragment.hasLatex(paragraph.attributedString) {
Sources/OrgPresentation/Display.swift +31
@@ -44,6 +44,37 @@ extension Presentation {
4444 return display
4545 }
4646
47 /// An image link and where its image goes.
48 public struct ImagePlacement: Sendable, Equatable {
49 public let link: InlineImages.Link
50 /// The link is all its line holds, so the image takes the line. Otherwise the image
51 /// stands in the text where the link is, as Org's display property puts it.
52 public let ownLine: Bool
53 }
54
55 public static func imagePlacements(_ links: [InlineImages.Link], in text: NSString) -> [ImagePlacement] {
56 links.filter { $0.range.upperBound <= text.length }.map { link in
57 let line = text.lineRange(for: NSRange(location: link.range.lowerBound, length: 0))
58 let before = text.substring(with: NSRange(location: line.location, length: link.range.lowerBound - line.location))
59 let after = NSMaxRange(line) > link.range.upperBound ? text.substring(with: NSRange(location: link.range.upperBound, length: NSMaxRange(line) - link.range.upperBound)) : ""
60 return ImagePlacement(link: link, ownLine: (before + after).allSatisfy { $0 == " " || $0 == "\t" || $0.isNewline })
61 }
62 }
63
64 /// An image's size in points: `width` from `#+ATTR_ORG`, else its own, never wider than
65 /// `maxWidth`, keeping its proportions.
66 public static func imageSize(natural: CGSize, width: Int?, maxWidth: CGFloat) -> CGSize {
67 let shown = min(width.map { CGFloat($0) } ?? natural.width, maxWidth)
68 return CGSize(width: shown, height: natural.width > 0 ? shown * natural.height / natural.width : 0)
69 }
70
71 /// The size of a font whose line is `height` tall, given a font of `pointSize` whose line
72 /// is `lineHeight` tall. An image in the text sits on a hidden character in that font,
73 /// which makes its line, and no other line of the paragraph, as tall as the image.
74 public static func imageFontSize(height: CGFloat, pointSize: CGFloat, lineHeight: CGFloat) -> CGFloat {
75 lineHeight > 0 ? max(0.01, height * pointSize / lineHeight) : pointSize
76 }
77
4778 /// Whether `role` hides while markup is hidden: link brackets and targets as with
4879 /// `org-link-descriptive`; emphasis markers only when Emacs hides them too.
4980 public static func hidesWithMarkup(_ role: StyleRole, options: EditingOptions) -> Bool {
Sources/OrgstarMobile/EditorScreen.swift +1 −1
@@ -1100,7 +1100,7 @@ struct CommandPalette: View {
11001100 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
11011101 ("app.publish.current-project", "Publish Current Project"),
11021102 ("app.toggle-markup", "Show or Hide Markup"),
1103 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
1103 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
11041104 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
11051105 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
11061106 ("org.table.expand", "Expand Table Columns"),
Sources/OrgstarMobile/MobileEditor+Display.swift +40 −26
@@ -51,19 +51,16 @@ extension MobileEditor {
5151
5252 // MARK: - Inline images
5353
54 func toggleImages() {
54 /// `includeLinked` as `org-toggle-inline-images` with a prefix argument: links with a
55 /// description show their image too.
56 func toggleImages(includeLinked: Bool = false) {
5557 showsImages.toggle()
58 imagesIncludeLinked = showsImages && includeLinked
5659 restyleAll()
5760 if showsImages {
58 let ns = textView.textStorage.string as NSString
59 var count = 0
60 var offset = 0
61 while offset < ns.length {
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", attachment: attachment),
64 loadImage(image.path) != nil { count += 1 }
65 offset = NSMaxRange(line)
66 }
61 let count = InlineImages.links(document.tree, in: 0..<textView.textStorage.length, includeLinked: imagesIncludeLinked,
62 remote: options.remoteInlineImages != "skip", attachment: attachment)
63 .count { loadImage($0.image.path) != nil }
6764 onMessage?("\(count) images displayed inline")
6865 } else {
6966 onMessage?("Inline image display turned off")
@@ -110,33 +107,50 @@ extension MobileEditor {
110107 return image
111108 }
112109
113 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
114 /// on the line; then the image goes under it.
110 /// Image links in `range` show their image, and the link is hidden unless the caret is on
111 /// its line. A link that is all its line holds keeps the line, with the image over it, or
112 /// under it while the link shows. A link in a line's text is as wide and as tall as its
113 /// image, which goes under the paragraph while the link shows.
115114 func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
116115 guard showsImages else { return }
117116 let text = storage.string as NSString
118117 let inset = textView.textContainerInset
119118 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
120 var location = range.lowerBound
121 while location < range.upperBound, location < text.length {
122 let line = text.lineRange(for: NSRange(location: location, length: 0))
123 location = NSMaxRange(line)
124 guard let image = InlineImages.image(atLine: line.location, in: text, remote: options.remoteInlineImages != "skip", attachment: attachment),
125 let picture = loadImage(image.path) else { continue }
126 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
127 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
119 let links = InlineImages.links(document.tree, in: range, includeLinked: imagesIncludeLinked, remote: options.remoteInlineImages != "skip", attachment: attachment)
120 for placement in Presentation.imagePlacements(links, in: text) {
121 guard let picture = loadImage(placement.link.image.path) else { continue }
122 let size = Presentation.imageSize(natural: picture.size, width: placement.link.image.width, maxWidth: maxWidth)
123 let link = NSRange(placement.link.range)
124 let line = text.lineRange(for: link)
125 let shown = NSLocationInRange(revealed.location, line)
126 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
127 defer { storage.addAttribute(.paragraphStyle, value: style, range: line) }
128 guard placement.ownLine else {
129 let first = NSRange(location: link.location, length: 1)
130 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown, inText: true), range: first)
131 if shown {
132 style.paragraphSpacing = max(style.paragraphSpacing, size.height + 4)
133 continue
134 }
135 // Pretty entities in the link would draw over the image.
136 storage.removeAttribute(.orgEntityDisplay, range: link)
137 storage.removeAttribute(.orgEntityColor, range: link)
138 storage.addAttributes(theme.hidden, range: link)
139 storage.addAttribute(.underlineStyle, value: 0, range: link)
140 let font = theme.font.withSize(Presentation.imageFontSize(height: size.height, pointSize: theme.font.pointSize, lineHeight: theme.font.lineHeight))
141 let advance = text.substring(with: first).size(withAttributes: [.font: font]).width
142 storage.addAttributes([.font: font, .kern: size.width - advance], range: first)
143 continue
144 }
128145 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
129146 // Invisible, keeping the line's height.
130 let shown = line.location == revealed.location && content.length > 0
131 if !shown, content.length > 0 {
147 if !shown {
132148 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
133149 }
134 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height), below: shown), range: NSRange(location: line.location, length: max(1, content.length)))
135 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
150 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: size, below: shown), range: content)
136151 // The image sits where the line is, or under it while the link shows; the spacing
137152 // makes room for the rest of it.
138 style.paragraphSpacing = shown ? height + 4 : max(0, height + 4 - theme.font.lineHeight)
139 storage.addAttribute(.paragraphStyle, value: style, range: line)
153 style.paragraphSpacing = shown ? size.height + 4 : max(0, size.height + 4 - theme.font.lineHeight)
140154 }
141155 }
142156
Sources/OrgstarMobile/MobileEditor+Styling.swift +2 −2
@@ -257,8 +257,8 @@ extension MobileEditor {
257257
258258 /// Moving to another line shows its markup and hides the last one's.
259259 func revealCaretLine() {
260 // LaTeX previews show their source on the caret's line whether or not markup shows.
261 guard !showMarkup || showsLatex else { return }
260 // LaTeX previews and images show their source on the caret's line whether or not markup shows.
261 guard !showMarkup || showsLatex || showsImages else { return }
262262 let line = caretLine
263263 guard line != revealedLine else { return }
264264 let text = textView.textStorage.string as NSString
Sources/OrgstarMobile/MobileEditor.swift +8 −6
@@ -128,8 +128,10 @@ final class MobileEditor: NSObject, DocumentBuffer {
128128 var spellSkipCache: (revision: Int, ranges: [Range<Int>])?
129129 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
130130 var revealedLine: NSRange?
131 /// `org-toggle-inline-images`: lines that are only an image link show the image.
131 /// `org-toggle-inline-images`: image links show their image.
132132 var showsImages = false
133 /// Links with a description show their image too.
134 var imagesIncludeLinked = false
133135 /// `org-latex-preview`: LaTeX fragments show as typeset math.
134136 var showsLatex = false
135137 /// The view width images were last sized for.
@@ -383,6 +385,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
383385 case _ where id.hasPrefix("org.fold."): foldCommand(id)
384386 case "org.link.open": openLinkAtCaret()
385387 case "org.toggle-inline-images": toggleImages()
388 case "org.toggle-inline-images-linked": toggleImages(includeLinked: true)
386389 case "org.latex-preview": toggleLatex()
387390 case "editor.toggle-truncate-lines":
388391 truncatesLines.toggle()
@@ -417,7 +420,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
417420 case "org.cycle":
418421 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
419422 case _ where id.hasPrefix("org.fold."): return true
420 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.latex-preview", "editor.toggle-truncate-lines",
423 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.toggle-inline-images-linked", "org.latex-preview", "editor.toggle-truncate-lines",
421424 "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward",
422425 "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
423426 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
@@ -697,7 +700,7 @@ extension MobileEditor: NSTextContentStorageDelegate {
697700}
698701
699702extension MobileEditor: NSTextLayoutManagerDelegate {
700 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
703 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image links
701704 /// show their image; pretty entities draw their character.
702705 nonisolated func textLayoutManager(
703706 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
@@ -708,10 +711,10 @@ extension MobileEditor: NSTextLayoutManagerDelegate {
708711 let folded = hidden.isFolded(offset)
709712 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
710713 let string = (textElement as? NSTextParagraph)?.attributedString
711 let image = string.flatMap(OrgLineFragment.image)
714 let image = string.map(OrgLineFragment.hasImages) ?? false
712715 let entities = string.map(OrgLineFragment.hasEntities) ?? false
713716 let latex = string.map(OrgLineFragment.hasLatex) ?? false
714 guard folded || band != nil || image != nil || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
717 guard folded || band != nil || image || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
715718 let fragment = OrgLineFragment(textElement: textElement, range: range)
716719 fragment.folded = folded
717720 fragment.band = band
@@ -719,7 +722,6 @@ extension MobileEditor: NSTextLayoutManagerDelegate {
719722 fragment.start = offset
720723 fragment.style = fragmentStyle
721724 }
722 fragment.image = image
723725 return fragment
724726 }
725727}
Sources/OrgstarMobile/MobileFragments.swift +36 −15
@@ -116,7 +116,7 @@ extension NSAttributedString.Key {
116116 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
117117 /// The color the entity's character is drawn in.
118118 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
119 /// The image an image link's line shows under it.
119 /// An image link's image, on the link's line or on its first character.
120120 static let orgImage = NSAttributedString.Key("OrgImage")
121121 /// A LaTeX fragment's typeset math, on its first character.
122122 static let orgLatex = NSAttributedString.Key("OrgLatex")
@@ -135,12 +135,16 @@ final class LatexBox: NSObject, @unchecked Sendable {
135135final class InlineImageBox: NSObject, @unchecked Sendable {
136136 let image: UIImage
137137 let size: CGSize
138 /// Drawn under the line's text, which shows while the caret is on it.
138 /// Drawn under the text, which shows while the caret is on the line.
139139 let below: Bool
140 init(image: UIImage, size: CGSize, below: Bool = false) {
140 /// In the line's text where the link is, on a character as wide and as tall as the image;
141 /// otherwise the link is all the line holds.
142 let inText: Bool
143 init(image: UIImage, size: CGSize, below: Bool = false, inText: Bool = false) {
141144 self.image = image
142145 self.size = size
143146 self.below = below
147 self.inText = inText
144148 }
145149}
146150
@@ -168,24 +172,46 @@ final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
168172}
169173
170174/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
171/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
175/// line's ellipsis, a block's band across the view, image links' images, and pretty
172176/// entities' characters where the entities' last (invisible) characters sit.
173177final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
174178 var folded = false
175179 var band: (color: UIColor, width: CGFloat)?
176 var image: InlineImageBox?
177180 /// For a block's lines: where the fragment starts, and where the selection is read.
178181 var start = 0
179182 var style: FragmentStyle?
180183
181 static func image(_ string: NSAttributedString) -> InlineImageBox? {
182 var found: InlineImageBox?
184 static func hasImages(_ string: NSAttributedString) -> Bool {
185 var found = false
183186 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
184 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
187 if value != nil { found = true; stop.pointee = true }
185188 }
186189 return found
187190 }
188191
192 /// Each image and where it goes: a line's image over or under the line, an image in the
193 /// text on its hidden link, or under the paragraph, side by side, while the links show.
194 private var imageFrames: [(box: InlineImageBox, frame: CGRect)] {
195 guard let string = (textElement as? NSTextParagraph)?.attributedString, let first = textLineFragments.first else { return [] }
196 let last = textLineFragments.last { $0.characterRange.length > 0 } ?? first
197 var out: [(InlineImageBox, CGRect)] = []
198 var under = first.typographicBounds.minX
199 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, range, _ in
200 guard let box = value as? InlineImageBox else { return }
201 if !box.inText {
202 out.append((box, CGRect(origin: CGPoint(x: first.typographicBounds.minX, y: (box.below ? first.typographicBounds.maxY : first.typographicBounds.minY) + 2), size: box.size)))
203 } else if box.below {
204 out.append((box, CGRect(origin: CGPoint(x: under, y: last.typographicBounds.maxY + 2), size: box.size)))
205 under += box.size.width + 4
206 } else if let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) {
207 let bounds = line.typographicBounds
208 let ascender = (string.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont)?.ascender ?? box.size.height
209 out.append((box, CGRect(origin: CGPoint(x: bounds.minX + line.locationForCharacter(at: range.location).x, y: bounds.minY + line.glyphOrigin.y - ascender), size: box.size)))
210 }
211 }
212 return out
213 }
214
189215 static func hasLatex(_ string: NSAttributedString) -> Bool {
190216 var found = false
191217 string.enumerateAttribute(.orgLatex, in: NSRange(location: 0, length: string.length)) { value, _, stop in
@@ -232,15 +258,10 @@ final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
232258 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
233259 }
234260
235 private var imageRect: CGRect? {
236 guard let image, let line = textLineFragments.first else { return nil }
237 return CGRect(x: line.typographicBounds.minX, y: (image.below ? line.typographicBounds.maxY : line.typographicBounds.minY) + 2, width: image.size.width, height: image.size.height)
238 }
239
240261 override var renderingSurfaceBounds: CGRect {
241262 var bounds = super.renderingSurfaceBounds
242263 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
243 for rect in [bandRect, imageRect].compactMap({ $0 }) + latexBoxes.map(\.frame) { bounds = bounds.union(rect) }
264 for rect in [bandRect].compactMap({ $0 }) + imageFrames.map(\.frame) + latexBoxes.map(\.frame) { bounds = bounds.union(rect) }
244265 return bounds
245266 }
246267
@@ -256,7 +277,7 @@ final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
256277 UIGraphicsPushContext(context)
257278 defer { UIGraphicsPopContext() }
258279 drawEntities(at: point)
259 if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
280 for (box, frame) in imageFrames { box.image.draw(in: frame.offsetBy(dx: point.x, dy: point.y)) }
260281 for (box, frame) in latexBoxes {
261282 UIImage(cgImage: box.rendering.image, scale: CGFloat(box.rendering.image.width) / max(1, box.rendering.size.width), orientation: .up)
262283 .draw(in: frame.offsetBy(dx: point.x, dy: point.y))
Sources/OrgstarMobile/ReaderScreen.swift +48 −17
@@ -35,6 +35,8 @@ struct ReaderScreen: View {
3535 @State private var loadedPath: String?
3636 /// The file's display: indentation, leading stars, inline images, truncation.
3737 @State private var startup: StartupDisplay?
38 /// The view's width, which images in a line's text are no wider than.
39 @State private var width: CGFloat = 0
3840 @State private var showingOutline = false
3941 @State private var message: String?
4042 /// A file a link opened, shown in Quick Look.
@@ -95,6 +97,7 @@ struct ReaderScreen: View {
9597 }
9698 // Narrower than the view while truncated, the text still starts at the top left.
9799 .defaultScrollAnchor(truncated ? .topLeading : nil)
100 .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }
98101 .background(theme.swiftColor("background") ?? Color(uiColor: .systemBackground))
99102 .onChange(of: pane?.revealRequest?.id) {
100103 guard let offset = pane?.revealRequest?.offset else { return }
@@ -181,7 +184,7 @@ struct ReaderScreen: View {
181184 .font(.caption.weight(.semibold)).foregroundStyle(theme.swiftColor("markup") ?? Color(uiColor: .tertiaryLabel))
182185 .opacity(hasContent ? 1 : 0)
183186 .frame(width: 2 * theme.column, alignment: .leading)
184 lineText(text.trimmingTrailingNewlines(), theme)
187 lineText(Text(text.trimmingTrailingNewlines()), theme)
185188 }
186189 .padding(.leading, headingIndent(entry, theme))
187190 .padding(.top, entry.level == 1 ? 6 : 0)
@@ -199,16 +202,30 @@ struct ReaderScreen: View {
199202 .frame(maxWidth: image.width.map { CGFloat($0) } ?? image.picture.size.width, alignment: .leading)
200203 .accessibilityLabel((image.path as NSString).lastPathComponent)
201204 } else {
202 lineText(attributed(ReadingText.segments(tree, in: part.range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme).trimmingTrailingNewlines(), theme)
205 lineText(text(tree, part, theme), theme)
203206 .textSelection(.enabled)
204207 }
205208 }
206209 }
207210 }
208211
212 /// A part's text, with each image in it standing where its link is.
213 private func text(_ tree: OrgTree, _ part: Part, _ theme: MobileTheme) -> Text {
214 func styled(_ range: Range<Int>) -> AttributedString {
215 attributed(ReadingText.segments(tree, in: range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme)
216 }
217 var text = Text("")
218 var start = part.range.lowerBound
219 for image in part.inText {
220 text = Text("\(text)\(Text(styled(start..<image.range.lowerBound)))\(Image(uiImage: image.picture))")
221 start = image.range.upperBound
222 }
223 return Text("\(text)\(Text(styled(start..<part.range.upperBound).trimmingTrailingNewlines()))")
224 }
225
209226 /// Wrapped to the view's width, or on one line each, scrolling sideways, while truncated.
210 private func lineText(_ text: AttributedString, _ theme: MobileTheme) -> some View {
211 Text(text)
227 private func lineText(_ text: Text, _ theme: MobileTheme) -> some View {
228 text
212229 .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing)))
213230 .fixedSize(horizontal: startup?.truncated ?? false, vertical: false)
214231 .frame(maxWidth: startup?.truncated == true ? nil : .infinity, alignment: .leading)
@@ -216,10 +233,14 @@ struct ReaderScreen: View {
216233
217234 private struct Part {
218235 let range: Range<Int>
236 /// The image of a link that is all its line holds.
219237 var image: (picture: UIImage, path: String, width: Int?)?
238 /// Images in the text, at their size, and the links they stand for.
239 var inText: [(range: Range<Int>, picture: UIImage)] = []
220240 }
221241
222 /// Text, and with inline images on, lines that are only an image link shown as the image.
242 /// Text, and with inline images on, image links shown as their images: a link that is all
243 /// its line holds as a part of its own, others in their part's text.
223244 private func parts(_ tree: OrgTree, _ range: Range<Int>) -> [Part] {
224245 guard startup?.inlineImages == true, let path = shownPath else { return [Part(range: range)] }
225246 // Read so that the view draws again when a remote image arrives.
@@ -227,20 +248,30 @@ struct ReaderScreen: View {
227248 let remote = RemoteImages.Mode(rawValue: session.options.remoteInlineImages) ?? .skip
228249 let base = URL(fileURLWithPath: path).deletingLastPathComponent()
229250 let ns = tree.text as NSString
251 let maxWidth = width > 0 ? max(80, width - 72) : .greatestFiniteMagnitude
230252 var parts: [Part] = []
231 var textStart = range.lowerBound
232 var location = range.lowerBound
233 while location < range.upperBound {
234 let line = ns.lineRange(for: NSRange(location: location, length: 0))
235 location = NSMaxRange(line)
236 guard folded.allSatisfy({ !$0.contains(line.location) }), let image = InlineImages.image(atLine: line.location, in: ns, remote: remote != .skip,
237 attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) }),
238 let picture = MobileEditor.loadImage(image.path, relativeTo: base, remote: remote) else { continue }
239 if textStart < line.location { parts.append(Part(range: textStart..<line.location)) }
240 parts.append(Part(range: line.location..<min(NSMaxRange(line), range.upperBound), image: (picture, image.path, image.width)))
241 textStart = min(NSMaxRange(line), range.upperBound)
253 var pending = Part(range: range.lowerBound..<range.lowerBound)
254 let links = InlineImages.links(tree, in: range, remote: remote != .skip, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) })
255 for placement in Presentation.imagePlacements(links, in: ns) {
256 let link = placement.link
257 guard link.range.lowerBound >= pending.range.lowerBound, link.range.upperBound <= range.upperBound,
258 folded.allSatisfy({ !$0.contains(link.range.lowerBound) }),
259 let picture = MobileEditor.loadImage(link.image.path, relativeTo: base, remote: remote) else { continue }
260 guard placement.ownLine else {
261 let size = Presentation.imageSize(natural: picture.size, width: link.image.width, maxWidth: maxWidth)
262 let sized = picture.cgImage.map { UIImage(cgImage: $0, scale: picture.size.width * picture.scale / max(1, size.width), orientation: picture.imageOrientation) }
263 pending.inText.append((link.range, sized ?? picture))
264 continue
265 }
266 let line = ns.lineRange(for: NSRange(location: link.range.lowerBound, length: 0))
267 if pending.range.lowerBound < line.location {
268 parts.append(Part(range: pending.range.lowerBound..<line.location, inText: pending.inText))
269 }
270 let end = min(NSMaxRange(line), range.upperBound)
271 parts.append(Part(range: line.location..<end, image: (picture, link.image.path, link.image.width)))
272 pending = Part(range: end..<end)
242273 }
243 if textStart < range.upperBound { parts.append(Part(range: textStart..<range.upperBound)) }
274 if pending.range.lowerBound < range.upperBound { parts.append(Part(range: pending.range.lowerBound..<range.upperBound, inText: pending.inText)) }
244275 return parts
245276 }
246277
Tests/OrgAppTests/AttachmentsTests.swift +1 −1
@@ -237,7 +237,7 @@ struct AttachmentImageTests {
237237 let second = ns.range(of: "[[attachment", options: .backwards).location
238238 #expect(DocumentSession.attachmentPath("pic.png", at: first, tree: tree, path: path) == folder.appendingPathComponent("data/202401/01T120000/pic.png").path)
239239 #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
240 #expect(InlineImages.links(tree, in: second..<ns.length, attachment: { DocumentSession.attachmentPath($0, at: $1, tree: tree, path: path) }).first?.image.path
241241 == folder.appendingPathComponent("imgs/pic.png").path)
242242 }
243243}
Tests/OrgAppTests/ImageYankTests.swift +2 −1
@@ -92,7 +92,8 @@ struct ImageYankTests {
9292 let (text, caret) = ImageYank.inserting([ours[2]], into: ours[3], at: NSMaxRange((ours[3] as NSString).range(of: "Free text.")))
9393 #expect(DocumentSession.attachmentPath("clipboard-20240101T120000.png", at: caret, tree: OrgParser.parse(text), path: "\(dir)/b.org")
9494 == "\(dir)/data/6a/1b2c3d-0000-4000-8000-00000000000b/clipboard-20240101T120000.png")
95 #expect(InlineImages.image(atLine: caret - 1, in: text as NSString, attachment: { name, _ in name })?.path == "clipboard-20240101T120000.png")
95 let line = (text as NSString).lineRange(for: NSRange(location: caret - 1, length: 0))
96 #expect(InlineImages.links(OrgParser.parse(text), in: line.location..<NSMaxRange(line), attachment: { name, _ in name }).map(\.image.path) == ["clipboard-20240101T120000.png"])
9697 }
9798
9899 @Test func aSecondPasteInTheSameSecondGetsANewName() throws {
Tests/OrgCoreTests/InlineImagesTests.swift +126 −16
@@ -3,33 +3,143 @@ import Testing
33@testable import OrgCore
44
55struct InlineImagesTests {
6 /// Each image link's text and the path it shows.
7 static func shown(_ text: String, includeLinked: Bool = false, remote: Bool = false, attachment: ((String, Int) -> String?)? = nil) -> [[String]] {
8 let tree = OrgParser.parse(text)
9 return InlineImages.links(tree, in: 0..<(text as NSString).length, includeLinked: includeLinked, remote: remote, attachment: attachment)
10 .map { [(text as NSString).substring(with: NSRange($0.range)), $0.image.path] }
11 }
12
613 @Test func findsImageLines() {
7 let text = "#+STARTUP: inlineimages\n* Images\n[[file:pic.png]]\n#+NAME: x\n#+ATTR_ORG: :width 60\n[[./pic.png]]\n[[pic.png][desc]]\nAfter [[pic.png]] text\n[[https://x.org/a.png]]\n" as NSString
8 func at(_ s: String) -> InlineImages.Image? { InlineImages.image(atLine: text.range(of: s).location, in: text) }
9 #expect(at("[[file:pic") == InlineImages.Image(path: "pic.png", width: nil))
10 #expect(at("[[./pic") == InlineImages.Image(path: "./pic.png", width: 60))
11 #expect(at("[[pic.png][") == nil && at("After") == nil && at("[[https") == nil)
12 #expect(InlineImages.startup(OrgParser.parse(text as String)) == true)
14 let text = "#+STARTUP: inlineimages\n* Images\n[[file:pic.png]]\n#+NAME: x\n#+ATTR_ORG: :width 60\n[[./pic.png]]\n[[pic.png][desc]]\n[[https://x.org/a.png]]\n"
15 let tree = OrgParser.parse(text)
16 let links = InlineImages.links(tree, in: 0..<(text as NSString).length)
17 #expect(links.map(\.image) == [InlineImages.Image(path: "pic.png", width: nil), InlineImages.Image(path: "./pic.png", width: 60)])
18 #expect(links.map(\.range.lowerBound) == ["[[file:pic", "[[./pic"].map { (text as NSString).range(of: $0).location })
19 #expect(InlineImages.startup(tree) == true)
1320 #expect(InlineImages.startup(OrgParser.parse("#+STARTUP: overview noinlineimages\n")) == false)
1421 #expect(InlineImages.startup(OrgParser.parse("* x\n")) == nil)
1522 #expect(InlineImages.startup(OrgParser.parse("#+begin_src org\n#+STARTUP: inlineimages\n#+end_src\n")) == nil)
1623 }
1724
1825 @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)
26 let text = "* Photo\n[[attachment:cat.jpg]]\n#+ATTR_ORG: :width 80\n[[attachment:sub/dog.png]]\n[[attachment:cat.jpg][desc]]\n"
27 #expect(Self.shown(text).isEmpty)
2428 var asked: [(String, Int)] = []
2529 let resolve: (String, Int) -> String? = { name, offset in
2630 asked.append((name, offset))
2731 return "/notes/data/ab/cd/" + name
2832 }
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)
33 let links = InlineImages.links(OrgParser.parse(text), in: 0..<(text as NSString).length, attachment: resolve)
34 #expect(links.map(\.image) == [
35 InlineImages.Image(path: "/notes/data/ab/cd/cat.jpg", width: nil), InlineImages.Image(path: "/notes/data/ab/cd/sub/dog.png", width: 80),
36 ])
37 #expect(asked.map(\.0) == ["cat.jpg", "sub/dog.png"] && asked[0].1 == (text as NSString).range(of: "[[attachment:cat.jpg]]").location)
38 #expect(Self.shown(text, attachment: { _, _ in nil }).isEmpty)
39 }
40
41 /// `org-link-preview-region`: a described link shows only with INCLUDE-LINKED.
42 @Test func describedLinksShowWithThePrefix() {
43 let text = "See [[file:a.png][the figure]] here.\n"
44 #expect(Self.shown(text).isEmpty)
45 #expect(Self.shown(text, includeLinked: true) == [["[[file:a.png][the figure]]", "a.png"]])
46 #expect(Self.shown("[[file:notes.org][the figure]]\n", includeLinked: true).isEmpty)
47 }
48
49 /// A description that is one `file:` or `attachment:` link, plain or in angle brackets,
50 /// shows without the prefix, in place of the description; with it, the path decides.
51 @Test func descriptionThatIsAnImageLink() {
52 #expect(Self.shown("[[https://example.com][file:thumb.png]]\n") == [["file:thumb.png", "thumb.png"]])
53 #expect(Self.shown("[[file:big.png][<file:small thumb.png>]]\n") == [["<file:small thumb.png>", "small thumb.png"]])
54 #expect(Self.shown("[[file:big.png][attachment:t.png]]\n", attachment: { name, _ in "/a/" + name }) == [["attachment:t.png", "/a/t.png"]])
55 #expect(Self.shown("[[file:big.png][file:thumb.png]]\n", includeLinked: true) == [["[[file:big.png][file:thumb.png]]", "big.png"]])
56 #expect(Self.shown("[[https://example.com][file:thumb.png]]\n", includeLinked: true).isEmpty)
57 // Not the whole description, no explicit type, or a remote link.
58 #expect(Self.shown("[[file:big.png][see file:thumb.png]]\n[[file:big.png][./thumb.png]]\n[[file:big.png][https://example.com/t.png]]\n", remote: true).isEmpty)
59 }
60
61 @Test func imagesInALinesText() {
62 let text = "Before [[file:a.png]] between [[./b.jpg]] and file:c.gif and <file:d e.png> after.\n"
63 #expect(Self.shown(text) == [["[[file:a.png]]", "a.png"], ["[[./b.jpg]]", "./b.jpg"], ["file:c.gif", "c.gif"], ["<file:d e.png>", "d e.png"]])
64 // Only the links a range overlaps.
65 let tree = OrgParser.parse(text)
66 let b = (text as NSString).range(of: "[[./b.jpg]]")
67 #expect(InlineImages.links(tree, in: b.location..<(b.location + 1)).map(\.image.path) == ["./b.jpg"])
68 }
69
70 @Test func imagesInHeadingsTablesAndItems() {
71 let text = "* Head [[file:h.png]]\n- item [[file:i.png]]\n 1. [[file:n.png]]\n| a | [[file:t.png]] |\n"
72 #expect(Self.shown(text).map { $0[1] } == ["h.png", "i.png", "n.png", "t.png"])
73 }
74
75 /// Links are objects: none in verbatim text, comments, keywords and literal blocks; quote,
76 /// center and verse blocks and captions hold Org text.
77 @Test func onlyWhereOrgHasLinks() {
78 let text = "=[[file:v.png]]= ~[[file:c.png]]~\n# [[file:comment.png]]\n#+begin_src org\n[[file:s.png]]\n#+end_src\n#+BEGIN_EXAMPLE\n[[file:e.png]]\n#+END_EXAMPLE\n"
79 #expect(Self.shown(text).isEmpty)
80 let quote = "#+begin_quote\n#+ATTR_ORG: :width 40\n[[file:q.png]]\nText [[file:r.png][desc]] end\n#+end_quote\n"
81 #expect(Self.shown(quote) == [["[[file:q.png]]", "q.png"]])
82 #expect(Self.shown(quote, includeLinked: true).map { $0[1] } == ["q.png", "r.png"])
83 #expect(InlineImages.links(OrgParser.parse(quote), in: 0..<(quote as NSString).length).first?.image.width == 40)
84 #expect(Self.shown("#+CAPTION: See [[file:k.png]]\n#+NAME: [[file:n.png]]\nText\n") == [["[[file:k.png]]", "k.png"]])
85 }
86
87 /// The paragraph's `#+ATTR_ORG` sizes every image in it, as `org-display-inline-image--width`
88 /// reads it from the link's paragraph.
89 @Test func widthComesFromTheParagraph() {
90 let text = "#+ATTR_ORG: :width 120\nFirst line\nthen [[file:a.png]] and [[file:b.png]]\n\n- [[file:item.png]]\n* [[file:head.png]]\n"
91 let links = InlineImages.links(OrgParser.parse(text), in: 0..<(text as NSString).length)
92 #expect(links.map(\.image.width) == [120, 120, nil, nil])
93 }
94
95 /// The links `org-link-preview-region` hands to the `file:` preview with an image's name,
96 /// and the text each overlay covers, with and without INCLUDE-LINKED.
97 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable))
98 func linksMatchEmacs() throws {
99 let text = """
100 * Head [[file:h.png]] tail
101 #+ATTR_ORG: :width 60
102 Para [[file:a.png][desc]] and [[./b.jpg]] and file:c.gif and <file:d e.png> end
103 more =[[file:v.png]]= ~[[file:w.png]]~ [[https://example.com][file:t.png]] [[file:big.png][file:small.png]]
104 [[file:big.png][<file:angle.png>]] [[file:big.png][see file:not.png]] [[file:notes.org][notes]] [[file:n.org]]
105
106 - item [[file:i.png]]
107 1. [[file:n.png][n]]
108 | a | [[file:t1.png]] | [[file:t2.png][two]] |
109 #+begin_quote
110 [[file:q.png]]
111 Text [[file:r.png][desc]] end
112 #+end_quote
113 #+begin_src org
114 [[file:s.png]]
115 #+end_src
116 #+begin_example
117 [[file:e.png]]
118 #+end_example
119 # [[file:comment.png]]
120 #+CAPTION: [[file:k.png]]
121 [[file:z.png]]
122
123 """
124 for includeLinked in [false, true] {
125 let emacs = try EmacsOracle.evaluate(text, """
126 (let (out (org-link-preview-batch-size 1000))
127 (advice-add 'org-link-preview-file :override
128 (lambda (ov path _link)
129 (when (string-match-p (image-file-name-regexp) path)
130 (push (format "%s -> %s" (buffer-substring-no-properties (overlay-start ov) (overlay-end ov)) path) out))
131 nil))
132 (org-link-preview-region \(includeLinked ? "t" : "nil") t (point-min) (point-max))
133 (nreverse out))
134 """)
135 #expect(Self.shown(text, includeLinked: includeLinked).map { "\($0[0]) -> \($0[1])" } == emacs, "INCLUDE-LINKED \(includeLinked)")
136 #expect(emacs.count > 8)
137 }
138 }
139
140 @Test func notImagesAndRemoteLinks() {
141 let text = "[[file:notes.org]] [[file:a.png::3]] [[https://x.org/a.png]] [[ftp://x.org/b.png]] https://x.org/c.png\n"
142 #expect(Self.shown(text).isEmpty)
143 #expect(Self.shown(text, remote: true) == [["[[https://x.org/a.png]]", "https://x.org/a.png"]])
34144 }
35145}
Tests/OrgEditorAppKitTests/InlineImagesEditorTests.swift added +157
@@ -0,0 +1,157 @@
1import AppKit
2import OrgCore
3@testable import OrgEditorAppKit
4import Testing
5
6@MainActor
7struct InlineImagesEditorTests {
8 static let filler = String(repeating: "word ", count: 40)
9 static let text = "* Images\n\(filler)[[file:pic.png]] \(filler)\n[[file:pic.png]]\n| a | [[file:pic.png]] | [[./pic.png]] |\n"
10 + "Described [[file:pic.png][a figure]] here\nMissing [[file:missing.png]] here\n"
11
12 /// A folder holding `pic.png`, 100 by 60 points, and `wide.png`, 2000 by 100.
13 static func folder() throws -> URL {
14 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-images-\(UUID().uuidString)")
15 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
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 }
23 return folder
24 }
25
26 static func harness(_ folder: URL) -> Harness {
27 let h = Harness(text)
28 h.editor.baseDirectory = folder
29 return h
30 }
31
32 static func box(_ h: Harness, at offset: Int) -> InlineImageBox? {
33 h.textView.textStorage?.attribute(.orgImage, at: offset, effectiveRange: nil) as? InlineImageBox
34 }
35
36 static func fragment(_ h: Harness, at offset: Int) -> NSTextLayoutFragment? {
37 h.layout()
38 let manager = h.editor.textLayoutManager
39 let content = manager.textContentManager!
40 guard let location = content.location(content.documentRange.location, offsetBy: offset) else { return nil }
41 return manager.textLayoutFragment(for: location)
42 }
43
44 @Test func anImageInWrappedTextMakesOnlyItsLineTall() throws {
45 let folder = try Self.folder()
46 defer { try? FileManager.default.removeItem(at: folder) }
47 let h = Self.harness(folder)
48 let ns = Self.text as NSString
49 let link = ns.range(of: "[[file:pic.png]]")
50 #expect(Self.box(h, at: link.location) == nil)
51 h.editor.run("org.toggle-inline-images")
52
53 let box = try #require(Self.box(h, at: link.location))
54 #expect(box.inText && !box.below && box.size == CGSize(width: 100, height: 60))
55 #expect(Self.box(h, at: link.location + 1) == nil)
56 let fragment = try #require(Self.fragment(h, at: link.location) as? ImageFragment)
57 let lines = fragment.textLineFragments.filter { $0.characterRange.length > 0 }
58 #expect(lines.count > 2)
59 let tall = lines.filter { $0.typographicBounds.height >= 59 }
60 #expect(tall.count == 1 && NSLocationInRange(link.location - NSMaxRange(ns.lineRange(for: NSRange(location: 0, length: 0))), tall[0].characterRange))
61 #expect(lines.filter { $0.typographicBounds.height < 30 }.count == lines.count - 1)
62 // The image covers the link's place: from its first character, 100 points wide, in the tall line.
63 let frame = try #require(ImageFragment.frames(of: fragment).first).frame
64 let bounds = tall[0].typographicBounds
65 #expect(frame.width == 100 && frame.height == 60)
66 #expect(frame.minY >= bounds.minY - 1 && frame.maxY <= bounds.maxY + 1)
67 let start = tall[0].locationForCharacter(at: tall[0].characterRange.location + 0).x
68 #expect(frame.minX >= bounds.minX + start)
69 let paragraphStart = NSMaxRange(ns.lineRange(for: NSRange(location: 0, length: 0)))
70 let before = tall[0].locationForCharacter(at: link.location - paragraphStart).x
71 let after = tall[0].locationForCharacter(at: NSMaxRange(link) - paragraphStart).x
72 #expect(abs(after - before - 100) < 1)
73 }
74
75 @Test func theCaretsLineShowsTheLinkWithTheImageUnderIt() throws {
76 let folder = try Self.folder()
77 defer { try? FileManager.default.removeItem(at: folder) }
78 let h = Self.harness(folder)
79 let ns = Self.text as NSString
80 let link = ns.range(of: "[[file:pic.png]]")
81 h.editor.run("org.toggle-inline-images")
82 h.caret(at: link.location + 3)
83 h.editor.revealCaretLine()
84
85 let box = try #require(Self.box(h, at: link.location))
86 #expect(box.inText && box.below)
87 let storage = try #require(h.textView.textStorage)
88 #expect(storage.attribute(.kern, at: link.location, effectiveRange: nil) == nil)
89 let fragment = try #require(Self.fragment(h, at: link.location) as? ImageFragment)
90 let lines = fragment.textLineFragments.filter { $0.characterRange.length > 0 }
91 #expect(lines.allSatisfy { $0.typographicBounds.height < 30 })
92 let frame = try #require(ImageFragment.frames(of: fragment).first).frame
93 #expect(frame.minY >= lines.last!.typographicBounds.maxY)
94 #expect(fragment.layoutFragmentFrame.height >= frame.maxY)
95
96 // Away again, the image is back in the text.
97 h.caret(at: 0)
98 h.editor.revealCaretLine()
99 #expect(Self.box(h, at: link.location)?.below == false)
100 }
101
102 @Test func aLinkAloneKeepsItsLineAndATableRowShowsEachImage() throws {
103 let folder = try Self.folder()
104 defer { try? FileManager.default.removeItem(at: folder) }
105 let h = Self.harness(folder)
106 let ns = Self.text as NSString
107 h.editor.run("org.toggle-inline-images")
108
109 let alone = ns.range(of: "\n[[file:pic.png]]\n").location + 1
110 let box = try #require(Self.box(h, at: alone))
111 #expect(!box.inText && !box.below)
112 #expect(Self.box(h, at: alone + 5) === box)
113
114 let row = ns.range(of: "| a |").location
115 let fragment = try #require(Self.fragment(h, at: row) as? ImageFragment)
116 let frames = ImageFragment.frames(of: fragment).map(\.frame)
117 #expect(frames.count == 2 && frames[1].minX >= frames[0].maxX)
118 #expect(fragment.textLineFragments[0].typographicBounds.height >= 59)
119 }
120
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
139 @Test func describedLinksNeedTheirCommandAndMissingFilesStayLinks() throws {
140 let folder = try Self.folder()
141 defer { try? FileManager.default.removeItem(at: folder) }
142 let h = Self.harness(folder)
143 let ns = Self.text as NSString
144 let described = ns.range(of: "[[file:pic.png][a figure]]").location
145 let missing = ns.range(of: "[[file:missing.png]]").location
146 var messages: [String] = []
147 h.editor.onMessage = { messages.append($0) }
148
149 h.editor.run("org.toggle-inline-images")
150 #expect(Self.box(h, at: described) == nil && Self.box(h, at: missing) == nil)
151 h.editor.run("org.toggle-inline-images-linked")
152 #expect(!h.editor.showsImages && Self.box(h, at: ns.range(of: "[[file:pic.png]]").location) == nil)
153 h.editor.run("org.toggle-inline-images-linked")
154 #expect(h.editor.showsImages && Self.box(h, at: described)?.inText == true && Self.box(h, at: missing) == nil)
155 #expect(messages == ["4 images displayed inline", "Inline image display turned off", "5 images displayed inline"])
156 }
157}
Tests/OrgPresentationTests/ImagePlacementTests.swift added +45
@@ -0,0 +1,45 @@
1import Foundation
2import OrgCore
3import Testing
4@testable import OrgPresentation
5
6struct ImagePlacementTests {
7 static func placements(_ text: String, includeLinked: Bool = false) -> [Presentation.ImagePlacement] {
8 let links = InlineImages.links(OrgParser.parse(text), in: 0..<(text as NSString).length, includeLinked: includeLinked)
9 return Presentation.imagePlacements(links, in: text as NSString)
10 }
11
12 @Test func aLinkAloneTakesItsLine() {
13 #expect(Self.placements("[[file:a.png]]\n [[file:b.png]] \t\n[[file:c.png]]").map(\.ownLine) == [true, true, true])
14 #expect(Self.placements("[[file:a.png][A figure]]\n", includeLinked: true).map(\.ownLine) == [true])
15 }
16
17 @Test func aLinkWithTextAroundItStandsInTheText() {
18 #expect(Self.placements("See [[file:a.png]]\n[[file:b.png]] here\n").map(\.ownLine) == [false, false])
19 #expect(Self.placements("[[file:a.png]] [[file:b.png]]\n").map(\.ownLine) == [false, false])
20 #expect(Self.placements("* [[file:h.png]]\n- [[file:i.png]]\n| [[file:t.png]] |\n").map(\.ownLine) == [false, false, false])
21 // The image stands for the description, inside the link.
22 #expect(Self.placements("[[https://example.com][file:thumb.png]]\n").map(\.ownLine) == [false])
23 }
24
25 /// A link past the text's end, from a tree older than the text, is left out.
26 @Test func linksPastTheTextAreLeftOut() {
27 let links = InlineImages.links(OrgParser.parse("text\n[[file:a.png]]\n"), in: 0..<20)
28 #expect(Presentation.imagePlacements(links, in: "text\n") == [])
29 }
30
31 @Test func sizeKeepsProportionsWithinTheWidth() {
32 let natural = CGSize(width: 400, height: 200)
33 #expect(Presentation.imageSize(natural: natural, width: nil, maxWidth: 600) == CGSize(width: 400, height: 200))
34 #expect(Presentation.imageSize(natural: natural, width: 100, maxWidth: 600) == CGSize(width: 100, height: 50))
35 #expect(Presentation.imageSize(natural: natural, width: 800, maxWidth: 600) == CGSize(width: 600, height: 300))
36 #expect(Presentation.imageSize(natural: natural, width: nil, maxWidth: 300) == CGSize(width: 300, height: 150))
37 #expect(Presentation.imageSize(natural: .zero, width: nil, maxWidth: 300) == .zero)
38 }
39
40 @Test func fontSizeGivesALineAsTallAsTheImage() {
41 // A 13-point font with a 16-point line: a 160-point image needs a 130-point font.
42 #expect(Presentation.imageFontSize(height: 160, pointSize: 13, lineHeight: 16) == 130)
43 #expect(Presentation.imageFontSize(height: 0, pointSize: 13, lineHeight: 16) == 0.01)
44 }
45}
Tests/OrgPresentationTests/RemoteImagesTests.swift +4 −5
@@ -10,11 +10,10 @@ struct RemoteImagesTests {
1010 }
1111
1212 @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")
13 let text = "[[https://example.com/a.png]]\n[[ftp://example.com/b.png]]\n[[file:c.png]]\n"
14 let tree = OrgParser.parse(text)
15 #expect(InlineImages.links(tree, in: 0..<75).map(\.image.path) == ["c.png"])
16 #expect(InlineImages.links(tree, in: 0..<75, remote: true).map(\.image.path) == ["https://example.com/a.png", "c.png"])
1817 }
1918
2019 @Test func downloadsOnceAndCaches() async throws {
docs/manual/guide/02-the-editor.org +12 −8
@@ -64,20 +64,28 @@ Entities are left as typed on the caret's line, in comment lines and inside bloc
6464
6565Org ▸ 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.
6666
67A line shows as an image when it holds nothing but a =file:= or =attachment:= link to an image file with no description:
67A =file:= or =attachment:= link to an image file shows as its image wherever the link is: on a line of its own, or in the text of a paragraph, a heading, a list item or a table:
6868
6969#+BEGIN_SRC org
7070#+ATTR_ORG: :width 400
7171[[file:images/diagram.png]]
72
73The plot [[file:images/plot.png]] and the photo file:images/photo.jpg share a line.
74
75| Before | [[file:before.png]] |
76| After | [[file:after.png]] |
7277#+END_SRC
7378
7479- Recognised extensions: =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =tif=, =tiff=, =bmp=, =heic=, =avif=.
7580- 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]].
7681- =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.
77- =#+ATTR_ORG: :width N= sets the width in points. Images are never wider than the editor.
78- The link text is hidden while its image shows, except on the caret's line.
82- A link with a description shows as a link, unless the description is itself one =file:= or =attachment:= link to an image, plain or in angle brackets: =[[https://example.com][file:thumbnail.png]]= shows =thumbnail.png=. Show or Hide Inline Images, Including Described Links (=C-u C-c C-x C-v= in the Emacs preset, and in the command palette), as =org-toggle-inline-images= with a prefix argument does, also shows the image a described link points to, such as =[[file:plot.png][the plot]]=; the link's path then decides, not its description.
83- Links in verbatim and code text, comments, keyword lines, and source and example blocks stay text.
84- =#+ATTR_ORG: :width N= above a paragraph sets the width in points of each image in it. Images are never wider than the editor.
85- A link that is all its line holds shows its image on that line. An image in a line's text stands where its link is, and its line is as tall as the image.
86- The link text is hidden while its image shows, except on the caret's line. There the image is drawn under the link, or under the paragraph for an image in a line's text.
7987
80To show images when a file opens, add =#+STARTUP: inlineimages= to the file, or set =org-startup-with-inline-images = true= in =config.toml=. =#+STARTUP: noinlineimages= turns it off for one file.
88To show images when a file opens, add =#+STARTUP: inlineimages= to the file, or set =org-startup-with-inline-images = true= in =config.toml=. =#+STARTUP: noinlineimages= turns it off for one file. Images shown when a file opens leave described links as links, as in Org.
8189
8290** LaTeX previews
8391
@@ -97,10 +105,6 @@ The area is $\pi r^2$, and \(\sqrt{2}\) is irrational.
97105
98106The command switches previews for the whole buffer; Org's =C-u= forms, which act on the section at point, aren't there. To preview when a file opens, add =#+STARTUP: latexpreview= to the file, or set =org-startup-with-latex-preview = true= in =config.toml=. =#+STARTUP: nolatexpreview= turns it off for one file. After switching between light and dark appearance, switch previews off and on to redraw them in the new color.
99107
100** What isn't rendered
101
102Images in links that have a description, and images on lines with other text, show as links.
103
104108* Folding
105109
106110Headings, drawers and blocks fold as in Org. Folding is display only and isn't saved in the file.
docs/manual/guide/03-keys.org +1
@@ -823,6 +823,7 @@ When a key appears in several rows, it runs the command whose condition holds at
823823| Narrow to Subtree or Widen (=org.narrow.toggle=) | — | =⌃⌘N= | — | Narrows to the subtree, or widens when already narrowed (=org-toggle-narrow-to-subtree=). |
824824| Sparse Tree… (=org.sparse-tree=) | =C-c /= | — | =SPC m s s= (N) | Asks for a match and shows only the matching entries and their context (=org-sparse-tree=). =C-c C-c= clears the highlights. |
825825| Show or Hide Inline Images (=org.toggle-inline-images=) | =C-c C-x C-v= | — | — | Shows or hides image links as images (=org-toggle-inline-images=). |
826| Show or Hide Inline Images, Including Described Links (=org.toggle-inline-images-linked=) | =C-u C-c C-x C-v= | — | — | Shows or hides image links as images, those with a description too (=org-toggle-inline-images= with =C-u=). |
826827| Show or Hide LaTeX Previews (=org.latex-preview=) | =C-c C-x C-l= | — | — | Shows or hides LaTeX fragments as typeset math (=org-latex-preview=). |
827828
828829** Outline: headings and subtrees
docs/manual/guide/09-links.org +11 −5
@@ -533,18 +533,24 @@ Markdown or plain text, are not supported.
533533
534534The echo area reports how many images are shown, or that inline display is off.
535535
536A line shows an image when it holds nothing but a bracket link, without a description,
537to a file ending in =.png=, =.jpg=, =.jpeg=, =.gif=, =.svg=, =.webp=, =.tif=, =.tiff=,
538=.bmp=, =.heic= or =.avif= (in any case):
536A link without a description shows an image when it points to a file ending in =.png=,
537=.jpg=, =.jpeg=, =.gif=, =.svg=, =.webp=, =.tif=, =.tiff=, =.bmp=, =.heic= or =.avif= (in
538any case), on a line of its own or in a line's text:
539539
540540#+BEGIN_SRC org
541541[[file:images/diagram.png]]
542542[[./photo.jpg]]
543See [[file:images/plot.png]] and file:images/detail.png here.
543544#+END_SRC
544545
545546Relative paths are resolved against the file's folder, and =attachment:= links against the
546547entry's attachment folder. The link text is hidden while the image is shown, except on the
547line that holds the caret, where the image is drawn under the link.
548line that holds the caret, where the image is drawn under the link or under its paragraph.
549
550A link with a description shows an image when the description is one =file:= or
551=attachment:= link to an image, as in =[[https://example.com][file:thumbnail.png]]=. Show
552or Hide Inline Images, Including Described Links (=C-u C-c C-x C-v= in the Emacs preset)
553shows the image any described link points to. See [[file:02-the-editor.org::*Inline images][Inline images]].
548554
549555** Pasting and dropping images
550556
@@ -627,7 +633,7 @@ Insert Link. Setting up a browser bookmarklet, and =org-protocol://capture=, are
627633
628634The iOS app follows links: tap a link in the reader. Org files open in the app, and
629635web, mail and other files go to the system. The iOS editor shows inline images as the
630Mac 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…
631637are in Commands, and on a hardware keyboard the Emacs keys run them; they work as
632638described above, and stored links last until the app quits. =org-protocol://store-link=
633639links opened on the device are stored and copied too. More ▸ Backlinks lists the same
docs/manual/guide/14-ios.org +1 −1
@@ -110,7 +110,7 @@ While markup is hidden, the line with the caret shows its markup, so you can edi
110110
111111The visibility from =#+STARTUP= applies first, then each heading's =VISIBILITY= property. As on the Mac, =VISIBILITY= properties apply only when =#+STARTUP= sets a visibility (=overview=, =content=, =showall= and the like).
112112
113An image line shows its image, and the link text is hidden except on the caret's line. =#+ATTR_ORG: :width N= sets the width in points; images are never wider than the editor. Show or Hide Inline Images in Commands, or =C-c C-x C-v= on a hardware keyboard, switches images in the open file. Truncate or Wrap Long Lines in Commands, or =C-x x t=, switches long lines. See [[file:02-the-editor.org][The editor]] for which lines show as images.
113An image link shows its image, on a line of its own or in a line's text, and the link text is hidden except on the caret's line. =#+ATTR_ORG: :width N= sets the width in points; images are never wider than the editor. Show or Hide Inline Images in Commands, or =C-c C-x C-v= on a hardware keyboard, switches images in the open file; Show or Hide Inline Images, Including Described Links, or =C-u C-c C-x C-v=, shows the images of links with a description too. Truncate or Wrap Long Lines in Commands, or =C-x x t=, switches long lines. The reader shows images as a file opens with them; in a heading, an image link stays a link there. See [[file:02-the-editor.org][The editor]] for which links show as images.
114114
115115Code in src blocks is highlighted in the theme's =syntax-*= colours, as on the Mac (see [[file:11-code-blocks.org][Code blocks]]).
116116
l10n/Localizable.xcstrings +41
@@ -843,6 +843,12 @@
843843 },
844844 "shouldTranslate": false
845845 },
846 "%@%@": {
847 "shouldTranslate": false
848 },
849 "%@%@%@": {
850 "shouldTranslate": false
851 },
846852 "%lld": {
847853 "shouldTranslate": false
848854 },
@@ -29831,6 +29837,41 @@
2983129837 }
2983229838 }
2983329839 },
29840 "Show or Hide Inline Images, Including Described Links": {
29841 "comment": "Command title",
29842 "localizations": {
29843 "de": {
29844 "stringUnit": {
29845 "state": "translated",
29846 "value": "Eingebettete Bilder ein- oder ausblenden, auch bei Links mit Beschreibung"
29847 }
29848 },
29849 "es": {
29850 "stringUnit": {
29851 "state": "translated",
29852 "value": "Mostrar u ocultar imágenes en línea, también en enlaces con descripción"
29853 }
29854 },
29855 "fr": {
29856 "stringUnit": {
29857 "state": "translated",
29858 "value": "Afficher ou masquer les images intégrées, y compris pour les liens avec description"
29859 }
29860 },
29861 "ja": {
29862 "stringUnit": {
29863 "state": "translated",
29864 "value": "インライン画像を表示/非表示(説明付きリンクを含む)"
29865 }
29866 },
29867 "pt-BR": {
29868 "stringUnit": {
29869 "state": "translated",
29870 "value": "Mostrar ou Ocultar Imagens Embutidas, Incluindo Links com Descrição"
29871 }
29872 }
29873 }
29874 },
2983429875 "Show or Hide LaTeX Previews": {
2983529876 "comment": "Command title",
2983629877 "localizations": {