Commit 87b7d20b2f

87b7d20b2fcaab47afe233bf1c44e13877861bcd

parent: 03b3940a21

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 02:17 UTC

Export: subtree, body only, EXPORT_FILE_NAME

The export dialog exports the subtree at the caret as Org does (heading as title, EXPORT_* properties over the file's keywords, children promoted) and body only. Exports are named by #+EXPORT_FILE_NAME or the subtree's EXPORT_FILE_NAME, extension replaced, on the Mac and iOS. Emacs formats get the subtree and body-only arguments.

Layout: unified · split

Sources/OrgApp/EmacsRunner.swift +7 −2
@@ -85,7 +85,11 @@ public enum EmacsRunner {
85 /// Exports `text`, the buffer of the file at `path`, with an ox function such as 85 /// Exports `text`, the buffer of the file at `path`, with an ox function such as
86 /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source 86 /// `org-latex-export-to-pdf`. The file is written beside `path`, as Emacs does; source
87 /// blocks are not run. Returns the path Emacs wrote. 87 /// blocks are not run. Returns the path Emacs wrote.
88 public static func export(text: String, path: String, function: String, timeout: Duration = .seconds(120)) async throws -> String { 88 /// `subtree` is a point (1-based, in characters) whose subtree alone is exported;
89 /// `bodyOnly` leaves out the document's preamble, as the dispatcher's `C-s` and `C-b`.
90 public static func export(
91 text: String, path: String, function: String, subtree: Int? = nil, bodyOnly: Bool = false, timeout: Duration = .seconds(120)
92 ) async throws -> String {
89 guard let emacs = executable() else { throw Failure(description: "Emacs isn't installed, so this format can't be exported.") } 93 guard let emacs = executable() else { throw Failure(description: "Emacs isn't installed, so this format can't be exported.") }
90 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-export-\(UUID().uuidString)") 94 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-export-\(UUID().uuidString)")
91 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 95 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
@@ -107,7 +111,8 @@ public enum EmacsRunner {
107 (erase-buffer) 111 (erase-buffer)
108 (insert-file-contents \(lisp(snapshot.path))) 112 (insert-file-contents \(lisp(snapshot.path)))
109 (set-buffer-modified-p nil)) 113 (set-buffer-modified-p nil))
110 (let ((file (\(function)))) 114 \(subtree.map { "(goto-char \($0))" } ?? "")
115 (let ((file (\(function)\(subtree == nil && !bodyOnly ? "" : " nil \(subtree == nil ? "nil" : "t") nil \(bodyOnly ? "t" : "nil")"))))
111 (with-temp-file \(lisp(output.path)) (insert (expand-file-name file))))) 116 (with-temp-file \(lisp(output.path)) (insert (expand-file-name file)))))
112 """.write(to: script, atomically: true, encoding: .utf8) 117 """.write(to: script, atomically: true, encoding: .utf8)
113 let process = Process() 118 let process = Process()
Sources/OrgCore/Export/ExportScope.swift added +73
@@ -0,0 +1,73 @@
1import Foundation
2
3/// What an export covers and where it goes, as Org's export dispatcher decides them: the whole
4/// file or the subtree at point (`org-export-as` with SUBTREEP), and `#+EXPORT_FILE_NAME` or
5/// the subtree's `EXPORT_FILE_NAME` (`org-export-output-file-name`).
6public enum ExportScope {
7 /// Subtree properties that stand in for the file's keywords, as `org-export-options-alist`
8 /// and the backends' options name them.
9 static let overrides: [(property: String, keyword: String)] = [
10 ("EXPORT_TITLE", "TITLE"), ("EXPORT_AUTHOR", "AUTHOR"), ("EXPORT_DATE", "DATE"), ("EXPORT_EMAIL", "EMAIL"),
11 ("EXPORT_OPTIONS", "OPTIONS"), ("EXPORT_SELECT_TAGS", "SELECT_TAGS"), ("EXPORT_EXCLUDE_TAGS", "EXCLUDE_TAGS"),
12 ("EXPORT_HTML_HEAD", "HTML_HEAD"), ("EXPORT_HTML_HEAD_EXTRA", "HTML_HEAD_EXTRA"),
13 ]
14
15 /// The subtree containing `offset` as a document of its own: the file's keyword lines, then
16 /// the heading's title as `#+TITLE` and its `EXPORT_*` properties as keywords, then the
17 /// heading's body without its planning line and property drawer, its children promoted so
18 /// the first is level 1. Nil before the first heading.
19 public static func subtree(_ text: String, at offset: Int, settings: OrgSettings = .default) -> String? {
20 let tree = OrgParser.parse(text, defaults: settings)
21 let model = DocumentModel(tree: tree)
22 guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) else { return nil }
23 let heading = model.headings[index]
24 let ns = text as NSString
25 let end = model.headings[(index + 1)...].first { $0.level <= heading.level }?.headingRange.lowerBound ?? ns.length
26 let bodyStart = NSMaxRange(ns.lineRange(for: NSRange(location: heading.headingRange.lowerBound, length: 0)))
27 var body = bodyStart < end ? ns.substring(with: NSRange(location: bodyStart, length: end - bodyStart)) : ""
28 body = body.replacing(#/^(?:[ \t]*(?:SCHEDULED|DEADLINE|CLOSED):[^\n]*\n)?(?:[ \t]*:PROPERTIES:[ \t]*\n(?:[^\n]*\n)*?[ \t]*:END:[ \t]*(?:\n|$))?/#, with: "", maxReplacements: 1)
29 body = ExportPreprocess.shift(body, to: 1)
30
31 var lines = preamble(tree)
32 let property = { (key: String) in heading.properties.last { $0.key.uppercased() == key }?.value }
33 lines.append("#+TITLE: " + (property("EXPORT_TITLE") ?? Links.displayFormat(heading.title).trimmingCharacters(in: .whitespaces)))
34 for (key, keyword) in overrides where key != "EXPORT_TITLE" {
35 if let value = property(key) { lines.append("#+\(keyword): \(value)") }
36 }
37 return lines.joined(separator: "\n") + "\n" + body
38 }
39
40 /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree
41 /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set.
42 public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
43 let tree = OrgParser.parse(text, defaults: settings)
44 if let offset {
45 let model = DocumentModel(tree: tree)
46 if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }),
47 let name = model.headings[index].properties.last(where: { $0.key.uppercased() == "EXPORT_FILE_NAME" })?.value, !name.isEmpty {
48 return name
49 }
50 }
51 var name: String?
52 for line in (settings.setupKeywords.split(separator: "\n").map(String.init) + preamble(tree)) {
53 if let m = line.firstMatch(of: #/(?i)^#\+EXPORT_FILE_NAME:[ \t]*(.*?)[ \t]*$/#), !m.1.isEmpty { name = String(m.1) }
54 }
55 return name
56 }
57
58 /// Where the export of `source` is written: `name` (relative to the source's folder, `~`
59 /// expanded) with its extension replaced by `ext`, or the source's name with `ext`.
60 public static func output(for source: URL, name: String?, extension ext: String) -> URL {
61 guard let name, !name.isEmpty else { return source.deletingPathExtension().appendingPathExtension(ext) }
62 let expanded = (name as NSString).expandingTildeInPath
63 let url = expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : source.deletingLastPathComponent().appendingPathComponent(expanded)
64 return url.deletingPathExtension().appendingPathExtension(ext).standardizedFileURL
65 }
66
67 /// The keyword lines before the first heading.
68 static func preamble(_ tree: OrgTree) -> [String] {
69 tree.root.children.filter { $0.kind == .zerothSection }
70 .flatMap { $0.children.filter { $0.kind == .keyword } }
71 .map { $0.text.trimmingCharacters(in: .newlines) }
72 }
73}
Sources/OrgCore/Export/HTMLExport.swift +8 −3
@@ -39,8 +39,11 @@ public enum HTMLExport {
39 39
40 /// A standalone page: the body under the document's title, with a small stylesheet, as 40 /// A standalone page: the body under the document's title, with a small stylesheet, as
41 /// `#+OPTIONS` and the export keywords ask. `path` is the file's, for `#+INCLUDE` and 41 /// `#+OPTIONS` and the export keywords ask. `path` is the file's, for `#+INCLUDE` and
42 /// `{{{input-file}}}`. 42 /// `{{{input-file}}}`. `bodyOnly` returns what goes inside `<body>` without the title and
43 public static func page(_ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date()) -> String { 43 /// byline: the table of contents, the document and its footnotes, as Org's body-only export.
44 public static func page(
45 _ text: String, fallbackTitle: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false
46 ) -> String {
44 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() } 47 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
45 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords) 48 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
46 let options = ExportOptions.parse(settings.setupKeywords + text) 49 let options = ExportOptions.parse(settings.setupKeywords + text)
@@ -56,7 +59,9 @@ public enum HTMLExport {
56 let byline = [options.author ? meta.author : nil, options.date ? meta.date : nil].compactMap { $0 }.filter { !$0.isEmpty } 59 let byline = [options.author ? meta.author : nil, options.date ? meta.date : nil].compactMap { $0 }.filter { !$0.isEmpty }
57 if !byline.isEmpty { header += "<p class=\"byline\">\(byline.map(HTMLRenderer.escape).joined(separator: " · "))</p>\n" } 60 if !byline.isEmpty { header += "<p class=\"byline\">\(byline.map(HTMLRenderer.escape).joined(separator: " · "))</p>\n" }
58 let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text))) 61 let body = renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
59 header += renderer.tableOfContents() 62 let contents = renderer.tableOfContents()
63 if bodyOnly { return contents + body }
64 header += contents
60 var head = options.htmlHead.map { $0 + "\n" }.joined() 65 var head = options.htmlHead.map { $0 + "\n" }.joined()
61 if renderer.hasMath { 66 if renderer.hasMath {
62 head += """ 67 head += """
Sources/OrgCore/Export/MarkdownExport.swift +5 −2
@@ -5,14 +5,17 @@ import Foundation
5public enum MarkdownExport { 5public enum MarkdownExport {
6 /// As the HTML page: `#+INCLUDE`, macros, `#+OPTIONS` and the select and exclude tags. 6 /// As the HTML page: `#+INCLUDE`, macros, `#+OPTIONS` and the select and exclude tags.
7 /// `path` is the file's, for `#+INCLUDE`, `{{{input-file}}}` and `#+bibliography:`. 7 /// `path` is the file's, for `#+INCLUDE`, `{{{input-file}}}` and `#+bibliography:`.
8 public static func document(_ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date()) -> String { 8 /// `bodyOnly` leaves out the title heading.
9 public static func document(
10 _ text: String, settings: OrgSettings = .default, path: String? = nil, now: Date = Date(), bodyOnly: Bool = false
11 ) -> String {
9 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() } 12 let directory = path.map { URL(fileURLWithPath: $0).deletingLastPathComponent() }
10 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords) 13 let text = ExportPreprocess.macros(ExportPreprocess.includes(text, directory: directory), path: path, now: now, setup: settings.setupKeywords)
11 let options = ExportOptions.parse(settings.setupKeywords + text) 14 let options = ExportOptions.parse(settings.setupKeywords + text)
12 let renderer = MarkdownRenderer(settings: settings, options: options) 15 let renderer = MarkdownRenderer(settings: settings, options: options)
13 var out = "" 16 var out = ""
14 renderer.inTitle = true 17 renderer.inTitle = true
15 if options.title, let title = HTMLExport.metadata(text, settings: settings).title { out = "# " + renderer.inlineString(title) + "\n\n" } 18 if options.title, !bodyOnly, let title = HTMLExport.metadata(text, settings: settings).title { out = "# " + renderer.inlineString(title) + "\n\n" }
16 renderer.inTitle = false 19 renderer.inTitle = false
17 renderer.citations = CiteProcessor(text: text, directory: directory) 20 renderer.citations = CiteProcessor(text: text, directory: directory)
18 out += renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text))) 21 out += renderer.document(renderer.citations == nil ? text : renderer.citations!.inliningNotes(CiteProcessor.removingNocite(text)))
Sources/Orgstar/ContentView.swift +39 −9
@@ -250,7 +250,9 @@ struct ContentView: View {
250 case .columns(_, let view): 250 case .columns(_, let view):
251 ColumnViewSheet(view: view) { offset in commands.editor?.reveal(offset) } 251 ColumnViewSheet(view: view) { offset in commands.editor?.reveal(offset) }
252 case .export(_, let source): 252 case .export(_, let source):
253 ExportSheet(source: source) { format, destination, open in export(format, to: destination, open: open) } 253 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
254 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
255 }
254 case .conflict: 256 case .conflict:
255 ConflictSheet(session: session) 257 ConflictSheet(session: session)
256 case .syncCopies: 258 case .syncCopies:
@@ -393,10 +395,26 @@ struct ContentView: View {
393 } 395 }
394 } 396 }
395 397
396 /// Writes the export beside the file, as Emacs's export dispatcher does, or to 398 /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
397 /// `destination`, and opens it with `open`. 399 private var exportSubtreeAvailable: Bool {
398 private func export(_ format: String, to destination: URL? = nil, open: Bool = false) { 400 guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
399 guard let path = session.path, let text = session.document?.text else { 401 return ExportScope.subtree(text, at: caret) != nil
402 }
403
404 /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
405 /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
406 private func exportTarget(_ ext: String, subtree: Bool) -> URL {
407 let path = session.path ?? ""
408 let text = session.document?.text ?? ""
409 let caret = subtree ? commands.editor?.context().caret : nil
410 return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
411 }
412
413 /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
414 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
415 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
416 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
417 guard let path = session.path, var text = session.document?.text else {
400 commands.show("No file is open") 418 commands.show("No file is open")
401 return 419 return
402 } 420 }
@@ -404,13 +422,21 @@ struct ContentView: View {
404 let base = url.deletingPathExtension() 422 let base = url.deletingPathExtension()
405 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile) 423 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
406 let open = open || format == "html-open" 424 let open = open || format == "html-open"
425 let caret = commands.editor?.context().caret ?? 0
426 let whole = text
427 if subtree {
428 guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
429 text = narrowed
430 }
407 switch format { 431 switch format {
408 case "html", "html-open", "markdown": 432 case "html", "html-open", "markdown":
409 let target = destination ?? base.appendingPathExtension(format == "markdown" ? "md" : "html") 433 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
434 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
410 let content = format == "markdown" 435 let content = format == "markdown"
411 ? MarkdownExport.document(text, settings: defaults, path: path) 436 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
412 : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path) 437 : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly)
413 do { 438 do {
439 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
414 try content.write(to: target, atomically: true, encoding: .utf8) 440 try content.write(to: target, atomically: true, encoding: .utf8)
415 commands.show("Exported to \(target.lastPathComponent)") 441 commands.show("Exported to \(target.lastPathComponent)")
416 if open { NSWorkspace.shared.open(target) } 442 if open { NSWorkspace.shared.open(target) }
@@ -423,7 +449,11 @@ struct ContentView: View {
423 commands.show("Exporting with Emacs…") 449 commands.show("Exporting with Emacs…")
424 commands.runInEmacs { 450 commands.runInEmacs {
425 do { 451 do {
426 var written = URL(fileURLWithPath: try await EmacsRunner.export(text: text, path: path, function: function)) 452 // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
453 let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
454 var written = URL(fileURLWithPath: try await EmacsRunner.export(
455 text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
456 ))
427 if let destination, destination.standardizedFileURL != written.standardizedFileURL { 457 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
428 try? FileManager.default.removeItem(at: destination) 458 try? FileManager.default.removeItem(at: destination)
429 try FileManager.default.moveItem(at: written, to: destination) 459 try FileManager.default.moveItem(at: written, to: destination)
Sources/Orgstar/ExportSheet.swift +22 −6
@@ -4,9 +4,15 @@ import SwiftUI
4/// Export… (`app.export-dialog`): the format, where the file goes, and whether to open it after. 4/// Export… (`app.export-dialog`): the format, where the file goes, and whether to open it after.
5struct ExportSheet: View { 5struct ExportSheet: View {
6 let source: URL 6 let source: URL
7 let export: (_ format: String, _ destination: URL, _ open: Bool) -> Void 7 /// Whether the caret is in a subtree that can be exported alone.
8 let inSubtree: Bool
9 /// The default destination for an extension, with or without the subtree.
10 let target: (_ ext: String, _ subtree: Bool) -> URL
11 let export: (_ format: String, _ destination: URL, _ open: Bool, _ subtree: Bool, _ bodyOnly: Bool) -> Void
8 @AppStorage("exportFormat") private var format = "html" 12 @AppStorage("exportFormat") private var format = "html"
9 @AppStorage("exportOpenAfter") private var openAfter = false 13 @AppStorage("exportOpenAfter") private var openAfter = false
14 @AppStorage("exportBodyOnly") private var bodyOnly = false
15 @State private var subtree = false
10 @State private var destination: URL? 16 @State private var destination: URL?
11 @Environment(\.dismiss) private var dismiss 17 @Environment(\.dismiss) private var dismiss
12 18
@@ -16,7 +22,9 @@ struct ExportSheet: View {
16 ] 22 ]
17 23
18 private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" } 24 private var ext: String { Self.formats.first { $0.id == format }?.ext ?? "html" }
19 private var target: URL { destination ?? source.deletingPathExtension().appendingPathExtension(ext) } 25 private var chosen: URL { destination ?? target(ext, subtree) }
26 /// PDF and ODT are whole documents.
27 private var allowsBodyOnly: Bool { !["pdf", "odt"].contains(format) }
20 28
21 var body: some View { 29 var body: some View {
22 Form { 30 Form {
@@ -24,9 +32,17 @@ struct ExportSheet: View {
24 ForEach(Self.formats, id: \.id) { Text($0.title).tag($0.id) } 32 ForEach(Self.formats, id: \.id) { Text($0.title).tag($0.id) }
25 } 33 }
26 .onChange(of: format) { destination = destination.map { $0.deletingPathExtension().appendingPathExtension(ext) } } 34 .onChange(of: format) { destination = destination.map { $0.deletingPathExtension().appendingPathExtension(ext) } }
35 Picker("Scope", selection: $subtree) {
36 Text("Whole file").tag(false)
37 Text("Subtree at the caret").tag(true)
38 }
39 .disabled(!inSubtree)
40 Toggle("Body only", isOn: $bodyOnly)
41 .disabled(!allowsBodyOnly)
42 .help("Leave out the title and page wrapper, as Org's body-only export")
27 LabeledContent("Destination") { 43 LabeledContent("Destination") {
28 HStack { 44 HStack {
29 Text(target.path(percentEncoded: false)).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary) 45 Text(chosen.path(percentEncoded: false)).lineLimit(1).truncationMode(.middle).foregroundStyle(.secondary)
30 Button("Choose…") { choose() } 46 Button("Choose…") { choose() }
31 } 47 }
32 } 48 }
@@ -38,7 +54,7 @@ struct ExportSheet: View {
38 Spacer() 54 Spacer()
39 Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction) 55 Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
40 Button("Export") { 56 Button("Export") {
41 export(format, target, openAfter) 57 export(format, chosen, openAfter, subtree && inSubtree, bodyOnly && allowsBodyOnly)
42 dismiss() 58 dismiss()
43 } 59 }
44 .keyboardShortcut(.defaultAction) 60 .keyboardShortcut(.defaultAction)
@@ -50,8 +66,8 @@ struct ExportSheet: View {
50 66
51 private func choose() { 67 private func choose() {
52 let panel = NSSavePanel() 68 let panel = NSSavePanel()
53 panel.directoryURL = target.deletingLastPathComponent() 69 panel.directoryURL = chosen.deletingLastPathComponent()
54 panel.nameFieldStringValue = target.lastPathComponent 70 panel.nameFieldStringValue = chosen.lastPathComponent
55 if panel.runModal() == .OK, let url = panel.url { destination = url } 71 if panel.runModal() == .OK, let url = panel.url { destination = url }
56 } 72 }
57} 73}
Sources/OrgstarMobile/ExportMenu.swift +3 −2
@@ -14,9 +14,10 @@ struct OrgExport: Transferable {
14 let format: Format 14 let format: Format
15 let settings: OrgSettings 15 let settings: OrgSettings
16 16
17 /// `#+EXPORT_FILE_NAME`'s name, or the file's, with the format's extension.
17 var fileName: String { 18 var fileName: String {
18 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension 19 ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: settings), extension: format == .html ? "html" : "md")
19 return base + (format == .html ? ".html" : ".md") 20 .lastPathComponent
20 } 21 }
21 22
22 static var transferRepresentation: some TransferRepresentation { 23 static var transferRepresentation: some TransferRepresentation {
Tests/OrgAppTests/AppTests.swift +13
@@ -829,6 +829,19 @@ struct EmacsExportTests {
829 #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n") 829 #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
830 } 830 }
831 831
832 /// The dispatcher's `C-s` and `C-b`: the subtree at point alone, its EXPORT_FILE_NAME used.
833 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
834 func exportsTheSubtreeBodyOnly() async throws {
835 let notes = try Folder()
836 let file = try notes.write("doc.org", "")
837 let text = "#+TITLE: Doc\n* Ünï\nFirst.\n* Second\n:PROPERTIES:\n:EXPORT_FILE_NAME: second\n:END:\nOnly this.\n"
838 let point = (text as NSString).substring(to: (text as NSString).range(of: "Only").location).unicodeScalars.count + 1
839 let written = try await EmacsRunner.export(text: text, path: file.path, function: "org-ascii-export-to-ascii", subtree: point, bodyOnly: true)
840 #expect(URL(fileURLWithPath: written).lastPathComponent == "second.txt")
841 let out = try String(contentsOfFile: written, encoding: .utf8)
842 #expect(out.contains("Only this.") && !out.contains("First.") && !out.uppercased().contains("DOC"), "\(out)")
843 }
844
832 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 845 @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
833 func exportUsesBabelPath() async throws { 846 func exportUsesBabelPath() async throws {
834 let notes = try Folder() 847 let notes = try Folder()
Tests/OrgCoreTests/ExportScopeTests.swift added +77
@@ -0,0 +1,77 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct ExportScopeTests {
6 static let file = """
7 #+TITLE: Whole file
8 #+AUTHOR: Ann
9 #+OPTIONS: toc:nil num:nil
10 * Intro
11 Some intro.
12 * TODO [#A] Project :work:
13 SCHEDULED: <2026-10-10 Sat>
14 :PROPERTIES:
15 :EXPORT_FILE_NAME: project-notes
16 :EXPORT_AUTHOR: Bob
17 :END:
18 Body of project.
19 ** Step one
20 Do it.
21 *** Deep
22 deep text
23 * Other
24 """
25
26 static var project: Int { (file as NSString).range(of: "Body of").location }
27
28 /// As `org-export-as` with SUBTREEP in Emacs 31: the heading's title is the title, its
29 /// EXPORT_AUTHOR the author; planning and drawer left out; children one level up.
30 @Test func subtreeIsADocumentOfItsOwn() throws {
31 let text = try #require(ExportScope.subtree(Self.file, at: Self.project))
32 #expect(text == """
33 #+TITLE: Whole file
34 #+AUTHOR: Ann
35 #+OPTIONS: toc:nil num:nil
36 #+TITLE: Project
37 #+AUTHOR: Bob
38 Body of project.
39 * Step one
40 Do it.
41 ** Deep
42 deep text
43
44 """)
45 let meta = HTMLExport.metadata(text)
46 #expect(meta.title == "Project" && meta.author == "Bob")
47 let body = HTMLExport.page(text, fallbackTitle: "t", bodyOnly: true)
48 #expect(!body.contains("<html") && !body.contains("class=\"title\"") && !body.contains("Intro"))
49 #expect(body.contains("<h2") && body.contains("Step one") && body.contains("<h3") && !body.contains("table-of-contents"))
50 #expect(ExportScope.subtree(Self.file, at: 0) == nil)
51 }
52
53 @Test func exportTitleOverridesTheHeading() throws {
54 let file = "* Proj\n:PROPERTIES:\n:EXPORT_TITLE: Custom\n:EXPORT_OPTIONS: toc:nil\n:END:\nText.\n"
55 let text = try #require(ExportScope.subtree(file, at: 0))
56 #expect(HTMLExport.metadata(text).title == "Custom")
57 #expect(text.hasSuffix("#+OPTIONS: toc:nil\nText.\n"))
58 }
59
60 /// `org-export-output-file-name`: relative to the file's folder, the extension replaced.
61 @Test func fileNames() {
62 let source = URL(fileURLWithPath: "/notes/t.org")
63 #expect(ExportScope.fileName(Self.file, subtreeAt: Self.project) == "project-notes")
64 #expect(ExportScope.fileName(Self.file, subtreeAt: 0) == nil)
65 #expect(ExportScope.fileName("#+EXPORT_FILE_NAME: out/x\n* A\n") == "out/x")
66 #expect(ExportScope.output(for: source, name: "out/x", extension: "html").path == "/notes/out/x.html")
67 #expect(ExportScope.output(for: source, name: "out/x.txt", extension: "html").path == "/notes/out/x.html")
68 #expect(ExportScope.output(for: source, name: "/tmp/abs", extension: "md").path == "/tmp/abs.md")
69 #expect(ExportScope.output(for: source, name: nil, extension: "md").path == "/notes/t.md")
70 }
71
72 @Test func markdownBodyOnlyHasNoTitle() {
73 let text = "#+TITLE: T\n* A\nx\n"
74 #expect(MarkdownExport.document(text).hasPrefix("# T"))
75 #expect(MarkdownExport.document(text, bodyOnly: true).hasPrefix("## A"))
76 }
77}
docs/manual/guide/12-export.org +6 −5
@@ -20,21 +20,23 @@ Export works on the file in the current editor, using its text as it is now, sav
20 20
21The keys follow Emacs's export dispatcher (=org-export-dispatch=). =C-c C-e= on its own is only a prefix: pause after it and the key hints list the formats. The =SPC m e= keys work in normal state; the =C-c C-e= keys work in every Doom state. The Mac preset has no keys for the single formats; its =⇧⌘E= opens the export dialog. 21The keys follow Emacs's export dispatcher (=org-export-dispatch=). =C-c C-e= on its own is only a prefix: pause after it and the key hints list the formats. The =SPC m e= keys work in normal state; the =C-c C-e= keys work in every Doom state. The Mac preset has no keys for the single formats; its =⇧⌘E= opens the export dialog.
22 22
23All seven commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.tex=, =.odt= or =.txt=. A file already there is replaced. The message area shows "Exported to /name/". 23All seven commands are in File ▸ Export and in the command palette. They write the export beside the Org file, with the same name and the format's extension: =.html=, =.md=, =.pdf=, =.tex=, =.odt= or =.txt=. =#+EXPORT_FILE_NAME:= names it instead, as in Org: relative to the Org file's folder (or absolute, or starting with =~=), with its extension replaced by the format's, so =#+EXPORT_FILE_NAME: out/report= writes =out/report.html=. A file already there is replaced. The message area shows "Exported to /name/".
24 24
25** The export dialog 25** The export dialog
26 26
27*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has: 27*Export…* in the command palette, or =⇧⌘E= in the Mac preset, opens a dialog. The Emacs and Doom presets have no key for it; bind =app.export-dialog= in =keymap.toml= if you want one (see [[file:03-keys.org][Keys and commands]]). The dialog has:
28 28
29- *Format*: HTML, Markdown, PDF (Emacs), ODT (Emacs), LaTeX (Emacs) or Plain text (Emacs). 29- *Format*: HTML, Markdown, PDF (Emacs), ODT (Emacs), LaTeX (Emacs) or Plain text (Emacs).
30- *Destination*: beside the Org file by default. *Choose…* picks another place and name. Changing the format changes the extension. 30- *Scope*: the whole file, or the subtree at the caret (Org's =C-s= in the dispatcher). A subtree is exported as a document of its own: its heading is the title, its text the body, and its child headings move up a level. The file's =#+= keywords still apply, and the heading's =EXPORT_TITLE=, =EXPORT_AUTHOR=, =EXPORT_DATE=, =EXPORT_EMAIL=, =EXPORT_OPTIONS=, =EXPORT_SELECT_TAGS=, =EXPORT_EXCLUDE_TAGS=, =EXPORT_HTML_HEAD= and =EXPORT_HTML_HEAD_EXTRA= properties override them. Its planning line and property drawer are left out. The choice is available when the caret is under a heading.
31- *Body only*: leave out the title and the page around the text (Org's =C-b=). HTML is then the table of contents, the text and the footnotes, without =<html>=, =<head>= or the title; Markdown has no title heading. Not available for PDF and ODT.
32- *Destination*: where =#+EXPORT_FILE_NAME:= says, or the subtree's =EXPORT_FILE_NAME= property for a subtree, else beside the Org file. *Choose…* picks another place and name. Changing the format changes the extension.
31- *Open after export*: opens the file in its default app when the export finishes. 33- *Open after export*: opens the file in its default app when the export finishes.
32 34
33The dialog remembers the format and the *Open after export* setting. 35The dialog remembers the format and the *Open after export* setting.
34 36
35** On iOS 37** On iOS
36 38
37The Export menu offers HTML and Markdown. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac. PDF, LaTeX, ODT and plain text are not available on iOS. 39The Export menu offers HTML and Markdown. It is under More in the editor, and in the toolbar in the reader. Choosing one opens the share sheet with the exported file, named after the Org file or its =#+EXPORT_FILE_NAME:=. Send it to another app, or use Save to Files to keep it. The export is the same as on the Mac. PDF, LaTeX, ODT and plain text are not available on iOS.
38 40
39* HTML export 41* HTML export
40 42
@@ -301,8 +303,7 @@ The publisher part comes from the =publisher=, =journal=, =institution= or =scho
301 303
302* What export does not do 304* What export does not do
303 305
304- There is no subtree export, body-only export, or asynchronous export; each command exports the whole file. 306- Subtree and body-only export are in the export dialog only; the single-format commands export the whole file. There is no asynchronous export.
305- =#+EXPORT_FILE_NAME:= is not used by HTML and Markdown export.
306- Source blocks are not run, and noweb references are not expanded. 307- Source blocks are not run, and noweb references are not expanded.
307- HTML export does not color source code. 308- HTML export does not color source code.
308- Export settings in the dialog are not per file. 309- Export settings in the dialog are not per file.