Keep attachment links with their entry, and expand them in HTML export !439

merged merged by cmc on 2026-11-22 01:51 UTC · krz/orgstar:attach-link-on-heading into main

10 files changed, +121 −3

Layout: unified · split

Sources/OrgApp/ImageYank.swift +2 −1
@@ -110,7 +110,8 @@ public enum ImageYank {
110110 /// caret after the last link.
111111 public static func inserting(_ links: [String], into text: String, at offset: Int) -> (text: String, caret: Int) {
112112 let ns = text as NSString
113 let offset = min(max(offset, 0), ns.length)
113 // On a heading's line they go under it, in the entry the files were attached to.
114 let offset = OrgAttach.belowHeading(text, at: min(max(offset, 0), ns.length))
114115 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
115116 var contentEnd = NSMaxRange(line)
116117 while contentEnd > line.location, [0x0A, 0x0D].contains(ns.character(at: contentEnd - 1)) { contentEnd -= 1 }
Sources/OrgApp/OrgPreferences.swift +2
@@ -16,6 +16,8 @@ public enum OrgPreferences {
1616 settings.deadlineWarningDays = integer("deadlineWarningDays", defaults)
1717 settings.tagInheritance = .init(string("tagInheritance", defaults))
1818 settings.tagsExcludedFromInheritance = Set(string("tagsExcludedFromInheritance", defaults).split(whereSeparator: \.isWhitespace).map(String.init))
19 settings.attachIDDir = attachIDDir(defaults)
20 settings.attachUseInheritance = attachUseInheritance(defaults)
1921 return settings
2022 }
2123
Sources/OrgCore/Commands/Attach.swift +12
@@ -99,6 +99,18 @@ public enum OrgAttach {
9999 }
100100 }
101101
102 /// Where text under a heading goes when `offset` is on its line: after the planning line,
103 /// drawers and clock lines (`org-end-of-meta-data` with FULL). `offset` itself on any other line.
104 public static func belowHeading(_ text: String, at offset: Int) -> Int {
105 let buffer = EmacsBuffer(text, point: min(offset, (text as NSString).length))
106 return buffer.saveExcursion {
107 buffer.forwardLine(0)
108 guard buffer.atHeading else { return offset }
109 buffer.endOfMetaDataFull()
110 return buffer.point
111 }
112 }
113
102114 /// `org-attach-tag`: the text with `tag` added to or removed from the entry's heading;
103115 /// unchanged before the first heading.
104116 public static func tagging(_ text: String, at offset: Int, on: Bool, tag: String = "ATTACH", options: EditingOptions = .org) -> String {
Sources/OrgCore/Export/ExportOptions.swift +30
@@ -126,6 +126,36 @@ public enum ExportPreprocess {
126126 return text.replacingOccurrences(of: "\r\n", with: "\n")
127127 }
128128
129 /// `org-attach-expand-links`, which Org runs before it parses an export: every `attachment:`
130 /// link of the file at `path` as a `file:` link to the file in its entry's attachment folder,
131 /// or in the file's own folder when the entry has none.
132 public static func attachments(
133 _ text: String, path: String?, settings: OrgSettings,
134 isDirectory: (String) -> Bool = { path in
135 var directory: ObjCBool = false
136 return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue
137 }
138 ) -> String {
139 guard let path, text.contains("attachment:") else { return text }
140 let ns = text as NSString
141 let tree = OrgParser.parse(text)
142 var edits: [(range: Range<Int>, link: String)] = []
143 var search = NSRange(location: 0, length: ns.length)
144 while case let found = ns.range(of: "attachment:", range: search), found.location != NSNotFound {
145 search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
146 guard let (link, range) = Links.link(at: found.location, text: text, tree: tree), link.type == "attachment",
147 range.lowerBound >= (edits.last?.range.upperBound ?? 0),
148 let file = Links.attachmentFile(link, tree: tree, path: path, idDir: settings.attachIDDir, inherit: settings.attachUseInheritance, isDirectory: isDirectory)
149 else { continue }
150 let written = ns.substring(with: NSRange(location: range.lowerBound, length: range.count))
151 let description = written.hasPrefix("[[") ? written.range(of: "][").map { "[" + written[$0.upperBound...].dropLast(2) + "]" } : nil
152 edits.append((range, "[[file:" + file.path + (file.searchOption.map { "::" + $0 } ?? "") + "]" + (description ?? "") + "]"))
153 }
154 return edits.reversed().reduce(into: NSMutableString(string: text)) {
155 $0.replaceCharacters(in: NSRange(location: $1.range.lowerBound, length: $1.range.count), with: $1.link)
156 } as String
157 }
158
129159 /// `#+INCLUDE: "file" [example|export FORMAT|src LANG] [:lines "A-B"] [:minlevel N]`, with
130160 /// `file::*Heading` or `file::#custom-id` for one subtree. Relative to `directory`.
131161 /// `includer` is the exported file's directory, `directory` at the top.
Sources/OrgCore/Export/HTMLExport.swift +2 −1
@@ -52,7 +52,8 @@ public enum HTMLExport {
5252 codeStyle: HTMLCodeStyle? = nil, language: String = "en"
5353 ) -> String {
5454 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
55 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
55 let expanded = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
56 let text = ExportPreprocess.attachments(expanded, path: path, settings: settings)
5657 let options = ExportOptions.parse(settings.setupKeywords + text)
5758 let meta = metadata(text, settings: settings)
5859 let title = meta.title ?? fallbackTitle
Sources/OrgCore/Parser/Settings.swift +5
@@ -54,6 +54,9 @@ public struct OrgSettings: Sendable, Equatable {
5454 /// `org-use-tag-inheritance` and `org-tags-exclude-from-inheritance`.
5555 public var tagInheritance: SemanticSettings.TagInheritance = .all
5656 public var tagsExcludedFromInheritance: Set<String> = []
57 /// `org-attach-id-dir` and `org-attach-use-inheritance` (nil for `selective`), for export.
58 public var attachIDDir = "data/"
59 public var attachUseInheritance: Bool?
5760
5861 /// `org-remove-uninherited-tags` for one tag.
5962 public func inheritsTag(_ tag: String) -> Bool {
@@ -149,6 +152,8 @@ enum SettingsScanner {
149152 settings.deadlineWarningDays = defaults.deadlineWarningDays
150153 settings.tagInheritance = defaults.tagInheritance
151154 settings.tagsExcludedFromInheritance = defaults.tagsExcludedFromInheritance
155 settings.attachIDDir = defaults.attachIDDir
156 settings.attachUseInheritance = defaults.attachUseInheritance
152157 settings.setupKeywords = defaults.setupKeywords
153158 settings.startup = startup
154159 return settings
Tests/OrgAppTests/ImageYankTests.swift +20
@@ -144,6 +144,26 @@ struct ImageYankTests {
144144 #expect(ImageYank.inserting([link], into: " - item\n ", at: 11) == (" - item\n \(link)", 31))
145145 }
146146
147 /// At the start of a heading's line the file is attached to that heading, so its link goes
148 /// under the heading too, where it resolves to the same folder.
149 @Test func linksOnAHeadingLineGoUnderTheHeading() throws {
150 let link = "[[attachment:a.png]]"
151 #expect(ImageYank.inserting([link], into: "* Task\nBody.\n", at: 0).text == "* Task\n\(link)\nBody.\n")
152 #expect(ImageYank.inserting([link], into: "* Task", at: 3).text == "* Task\n\(link)")
153 #expect(ImageYank.inserting([link], into: "* Task\nSCHEDULED: <2026-11-21 Sat>\n:PROPERTIES:\n:ID: x\n:END:\n* Next\n", at: 0).text
154 == "* Task\nSCHEDULED: <2026-11-21 Sat>\n:PROPERTIES:\n:ID: x\n:END:\n\(link)\n* Next\n")
155
156 let folder = try Self.folder()
157 defer { try? FileManager.default.removeItem(at: folder) }
158 let path = folder.appendingPathComponent("n.org").path
159 let original = "Free text.\n* Task\nBody.\n"
160 var entry = Attachments.Entry(text: original, offset: 11, path: path, idDir: "data/")
161 let saved = try ImageYank.save(Data("PDF".utf8), ext: "pdf", method: .attach, in: &entry, date: Self.noon, prefix: "scan")
162 let (text, caret) = ImageYank.inserting([saved], into: entry.text, at: ImageYank.map(entry.offset, from: original, to: entry.text))
163 let file = try #require(DocumentSession.attachmentPath("scan-20240101T120000.pdf", at: caret, tree: OrgParser.parse(text), path: path))
164 #expect(FileManager.default.fileExists(atPath: file))
165 }
166
147167 @Test func caretFollowsTheChangeAboveIt() {
148168 let old = "* Task\nBody."
149169 let new = "* Task\n:PROPERTIES:\n:ID: x\n:END:\nBody."
Tests/OrgCoreTests/AttachmentExportTests.swift added +45
@@ -0,0 +1,45 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `org-attach-expand-links` before HTML export.
6struct AttachmentExportTests {
7 static let text = """
8 :PROPERTIES:
9 :ID: 786d6b41-ff99
10 :END:
11 [[attachment:scan.pdf]]
12 [[attachment:photo.jpg]]
13 #+begin_example
14 [[attachment:kept.png]]
15 #+end_example
16
17 * Task
18 :PROPERTIES:
19 :ID: aa11bb22-cc33
20 :END:
21 See [[attachment:in.png][the picture]].
22
23 """
24
25 @Test func attachmentLinksBecomeFileLinksIntoTheEntrysFolder() {
26 let folder = "/notes/data/78/6d6b41-ff99"
27 let expanded = ExportPreprocess.attachments(Self.text, path: "/notes/a.org", settings: .default) { $0 == folder }
28 #expect(expanded.contains("[[file:\(folder)/scan.pdf]]\n[[file:\(folder)/photo.jpg]]\n"))
29 // No link in an example block, and no folder for the second entry: the file's own.
30 #expect(expanded.contains("[[attachment:kept.png]]"))
31 #expect(expanded.contains("See [[file:/notes/in.png][the picture]]."))
32 }
33
34 @Test func htmlShowsAnAttachedImage() throws {
35 let root = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-attach-\(UUID().uuidString)").standardizedFileURL
36 let folder = root.appendingPathComponent("data/78/6d6b41-ff99")
37 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
38 defer { try? FileManager.default.removeItem(at: root) }
39 let html = HTMLExport.page(Self.text, fallbackTitle: "t", path: root.appendingPathComponent("a.org").path, bodyOnly: true)
40 // An absolute path, which is how this exporter writes a file link to one.
41 #expect(html.contains("<a href=\"\(folder.path)/scan.pdf\">\(folder.path)/scan.pdf</a>"))
42 #expect(html.contains("<img src=\"\(folder.path)/photo.jpg\" alt=\"photo.jpg\">"))
43 #expect(html.contains("<a href=\"\(root.path)/in.png\">the picture</a>"))
44 }
45}
docs/manual/guide/09-links.org +1 −1
@@ -540,7 +540,7 @@ line that holds the caret, where the image is drawn under the link.
540540
541541Paste (⌘V, or Edit ▸ Paste on iOS) with an image on the clipboard and no text runs
542542=yank-media=, as in Emacs 29 and later: the image is saved as =org-yank-image-save-method=
543says and a link to it is inserted at the caret. M-x =yank-media= does the same on the Mac.
543says and a link to it is inserted at the caret; with the caret on a heading's line, under the heading, after its planning line and drawers. M-x =yank-media= does the same on the Mac.
544544
545545| =org-yank-image-save-method= | Where the image goes | Link |
546546|------------------------------+--------------------------------------------------------------------------+-------------------------|
docs/manual/guide/12-export.org +2
@@ -161,6 +161,8 @@ A table.el table (one drawn with =+=, =-= and =|=) becomes a table with each cel
161161
162162A link to an image file without a description becomes an =<img>=. The image types are =png=, =jpg=, =jpeg=, =gif=, =svg=, =webp=, =bmp=, =tif=, =tiff= and =avif=. =#+ATTR_HTML:= before the paragraph adds attributes (=:width 300 :alt "Map"=); without an =:alt=, the file name is used.
163163
164An =attachment:= link is exported as a =file:= link to the file in its entry's attachment folder, with its full path, as Org's =org-attach-expand-links= does; when the entry has no attachment folder, to that name in the Org file's folder. An attached image therefore shows as an image.
165
164166An image paragraph with =#+CAPTION:= or =#+ATTR_HTML:= becomes a =<figure>=; a caption is numbered "Figure 1:", "Figure 2:" and so on.
165167
166168Links to =.org= files point to the =.html= file of the same name. Links to headings (=[[*Heading]]=), to =CUSTOM_ID= targets and to radio targets point to the heading's or target's =id= on the page. =id:= links point to =#= and the ID. Other links are written as they are.