iOS: export names from the open tree, block bands only when needed, org-protocol message !465

merged merged by cmc on 2026-11-22 19:41 UTC · krz/orgstar:issue-230-ios-export-menu into main

11 files changed, +67 −37

Layout: unified · split

Sources/OrgCore/Export/ExportScope.swift +5 −1
@@ -59,7 +59,11 @@ public enum ExportScope {
59 /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree 59 /// The export's name: the subtree's `EXPORT_FILE_NAME` property when exporting the subtree
60 /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set. 60 /// at `offset`, else the file's last `#+EXPORT_FILE_NAME`; nil when neither is set.
61 public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? { 61 public static func fileName(_ text: String, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
62 let tree = OrgParser.parse(text, defaults: settings) 62 fileName(OrgParser.parse(text, defaults: settings), subtreeAt: offset, settings: settings)
63 }
64
65 /// The export's name from a parsed file; `settings` gives the setup files' keywords.
66 public static func fileName(_ tree: OrgTree, subtreeAt offset: Int? = nil, settings: OrgSettings = .default) -> String? {
63 if let offset { 67 if let offset {
64 let model = DocumentModel(tree: tree) 68 let model = DocumentModel(tree: tree)
65 if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }), 69 if let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }),
Sources/OrgEditorAppKit/OrgEditor.swift +1 −11
@@ -759,16 +759,6 @@ public final class OrgEditor: NSObject {
759 invalidateLayout(from: old, to: blocks) 759 invalidateLayout(from: old, to: blocks)
760 } 760 }
761 761
762 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
763 /// them), hold a block delimiter or a fixed-width line.
764 static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
765 let start = min(range.lowerBound, text.length)
766 let end = min(range.upperBound + 1, text.length)
767 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
768 let content = text.substring(with: lines)
769 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
770 }
771
772 fileprivate func storageEdited(range: NSRange, delta: Int) { 762 fileprivate func storageEdited(range: NSRange, delta: Int) {
773 guard !isLoading, let storage = textView.textStorage else { return } 763 guard !isLoading, let storage = textView.textStorage else { return }
774 markActive = false 764 markActive = false
@@ -810,7 +800,7 @@ public final class OrgEditor: NSObject {
810 if isOrg { 800 if isOrg {
811 // Walking the tree for blocks costs more than typing; only an edit on a line that 801 // Walking the tree for blocks costs more than typing; only an edit on a line that
812 // could start or end one (`#+…`, `: …`) needs it, others move the ranges. 802 // could start or end one (`#+…`, `: …`) needs it, others move the ranges.
813 if Self.mayChangeBlocks(oldText, edit.range) || Self.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) { 803 if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
814 shaded.set(Presentation.shadedBlocks(document.tree)) 804 shaded.set(Presentation.shadedBlocks(document.tree))
815 } else { 805 } else {
816 shaded.set(oldShaded.map { mapRange($0, through: edit) }) 806 shaded.set(oldShaded.map { mapRange($0, through: edit) })
Sources/OrgPresentation/Restyling.swift +10
@@ -151,4 +151,14 @@ extension Presentation {
151 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd) 151 let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
152 return min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound) 152 return min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound)
153 } 153 }
154
155 /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
156 /// them), hold a block delimiter or a fixed-width line.
157 public static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
158 let start = min(range.lowerBound, text.length)
159 let end = min(range.upperBound + 1, text.length)
160 let lines = text.lineRange(for: NSRange(location: start, length: end - start))
161 let content = text.substring(with: lines)
162 return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
163 }
154} 164}
Sources/OrgstarMobile/EditorScreen.swift +3 −3
@@ -189,8 +189,8 @@ struct EditorScreen: View {
189 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") } 189 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
190 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") } 190 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
191 } 191 }
192 if let text = session.document(of: path)?.text { 192 if let tree = session.document(of: path)?.tree {
193 ExportMenu(path: path, text: text, report: { message = $0 }, exportSubtree: exportSubtree) 193 ExportMenu(path: path, tree: tree, report: { message = $0 }, exportSubtree: exportSubtree)
194 } 194 }
195 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies } 195 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
196 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery } 196 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
@@ -276,7 +276,7 @@ struct EditorScreen: View {
276 case .crypt(let request): 276 case .crypt(let request):
277 CryptScreen(request: request, session: session, editor: editor) { message = $0 } 277 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
278 case .exportSubtree(let caret): 278 case .exportSubtree(let caret):
279 if let text = session.document(of: path)?.text { SubtreeExportScreen(path: path, text: text, caret: caret) } 279 if let tree = session.document(of: path)?.tree { SubtreeExportScreen(path: path, tree: tree, caret: caret) }
280 case .backlinks: 280 case .backlinks:
281 BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in 281 BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
282 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) } 282 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
Sources/OrgstarMobile/ExportMenu.swift +14 −10
@@ -56,17 +56,16 @@ struct OrgExport: Transferable {
56 let settings: OrgSettings 56 let settings: OrgSettings
57 /// Made on the main actor, where the editor's highlighter is. 57 /// Made on the main actor, where the editor's highlighter is.
58 let codeStyle: HTMLCodeStyle 58 let codeStyle: HTMLCodeStyle
59 /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or nil for the file's.
60 let name: String?
59 /// The subtree at this offset exported alone. 61 /// The subtree at this offset exported alone.
60 var subtree: Int? 62 var subtree: Int?
61 /// Without the title and the page around the text, in the formats that allow it. 63 /// Without the title and the page around the text, in the formats that allow it.
62 var bodyOnly = false 64 var bodyOnly = false
63 65
64 /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or the file's, with the 66 /// `name`, or the file's, with the format's extension.
65 /// format's extension.
66 var fileName: String { 67 var fileName: String {
67 ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings), 68 ExportScope.output(for: URL(fileURLWithPath: path), name: name, extension: format.fileExtension).lastPathComponent
68 extension: format.fileExtension)
69 .lastPathComponent
70 } 69 }
71 70
72 /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export 71 /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export
@@ -165,7 +164,7 @@ struct OrgExport: Transferable {
165/// Save to Files; or copying it as rich text. 164/// Save to Files; or copying it as rich text.
166struct ExportMenu: View { 165struct ExportMenu: View {
167 let path: String 166 let path: String
168 let text: String 167 let tree: OrgTree
169 @Environment(MobileModel.self) private var model 168 @Environment(MobileModel.self) private var model
170 /// Shows what happened, as the screen's message line does. 169 /// Shows what happened, as the screen's message line does.
171 var report: (String) -> Void = { _ in } 170 var report: (String) -> Void = { _ in }
@@ -176,6 +175,9 @@ struct ExportMenu: View {
176 175
177 var body: some View { 176 var body: some View {
178 let bodyOnly = kept.isEmpty ? false : ExportSettings.saved(for: path).bodyOnly 177 let bodyOnly = kept.isEmpty ? false : ExportSettings.saved(for: path).bodyOnly
178 let text = tree.text
179 // From the open tree: SwiftUI evaluates the menu on every edit.
180 let name = ExportScope.fileName(tree, settings: OrgPreferences.orgSettings())
179 Menu("Export", systemImage: "square.and.arrow.up") { 181 Menu("Export", systemImage: "square.and.arrow.up") {
180 ForEach(OrgExport.Format.allCases, id: \.self) { format in 182 ForEach(OrgExport.Format.allCases, id: \.self) { format in
181 if format.locked { 183 if format.locked {
@@ -184,7 +186,7 @@ struct ExportMenu: View {
184 Button(format.name) { report(ExportSettings.noBodyOnly) } 186 Button(format.name) { report(ExportSettings.noBodyOnly) }
185 } else { 187 } else {
186 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(), 188 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
187 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), bodyOnly: bodyOnly) 189 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name, bodyOnly: bodyOnly)
188 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) } 190 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
189 } 191 }
190 } 192 }
@@ -274,7 +276,7 @@ struct AgendaCalendars: Transferable {
274/// The subtree at `caret` shared alone, in each of the export formats. 276/// The subtree at `caret` shared alone, in each of the export formats.
275struct SubtreeExportScreen: View { 277struct SubtreeExportScreen: View {
276 let path: String 278 let path: String
277 let text: String 279 let tree: OrgTree
278 let caret: Int 280 let caret: Int
279 @Environment(MobileModel.self) private var model 281 @Environment(MobileModel.self) private var model
280 @Environment(\.dismiss) private var dismiss 282 @Environment(\.dismiss) private var dismiss
@@ -282,12 +284,14 @@ struct SubtreeExportScreen: View {
282 var body: some View { 284 var body: some View {
283 NavigationStack { 285 NavigationStack {
284 let bodyOnly = ExportSettings.saved(for: path).bodyOnly 286 let bodyOnly = ExportSettings.saved(for: path).bodyOnly
287 let name = ExportScope.fileName(tree, subtreeAt: caret, settings: OrgPreferences.orgSettings())
285 List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in 288 List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
286 if bodyOnly, !format.allowsBodyOnly { 289 if bodyOnly, !format.allowsBodyOnly {
287 LabeledContent(format.name) { Text("No body-only export") }.foregroundStyle(.secondary) 290 LabeledContent(format.name) { Text("No body-only export") }.foregroundStyle(.secondary)
288 } else { 291 } else {
289 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(), 292 let export = OrgExport(text: tree.text, path: path, format: format, settings: OrgPreferences.orgSettings(),
290 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret, bodyOnly: bodyOnly) 293 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name,
294 subtree: caret, bodyOnly: bodyOnly)
291 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) } 295 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
292 } 296 }
293 } 297 }
Sources/OrgstarMobile/MobileEditor+Styling.swift +4 −1
@@ -192,7 +192,10 @@ extension MobileEditor {
192 DispatchQueue.main.async { [weak self] in 192 DispatchQueue.main.async { [weak self] in
193 guard let self, let range = self.restyleScheduled else { return } 193 guard let self, let range = self.restyleScheduled else { return }
194 self.restyleScheduled = nil 194 self.restyleScheduled = nil
195 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) 195 if self.blocksMayChange {
196 self.blocksMayChange = false
197 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
198 }
196 self.restyle(range) 199 self.restyle(range)
197 self.updateHidden() 200 self.updateHidden()
198 self.textView.typingAttributes = self.theme.base 201 self.textView.typingAttributes = self.theme.base
Sources/OrgstarMobile/MobileEditor.swift +10
@@ -144,6 +144,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
144 static let imageCache = NSCache<NSString, UIImage>() 144 static let imageCache = NSCache<NSString, UIImage>()
145 var loading = false 145 var loading = false
146 var restyleScheduled: Range<Int>? 146 var restyleScheduled: Range<Int>?
147 /// An edit since the last restyle touched a line that can start or end a block.
148 var blocksMayChange = false
147 /// Text before its end is styled; after it, the text waits for the background passes. 149 /// Text before its end is styled; after it, the text waits for the background passes.
148 var styled = StyledExtent() 150 var styled = StyledExtent()
149 var stylingScheduled = false 151 var stylingScheduled = false
@@ -583,6 +585,14 @@ final class MobileEditor: NSObject, DocumentBuffer {
583 styled.map(through: edit, in: newText) 585 styled.map(through: edit, in: newText)
584 let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) 586 let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText))
585 vim.changed(edit) 587 vim.changed(edit)
588 // Walking the tree for blocks costs more than typing; only an edit on a line that could
589 // start or end one needs it, others move the ranges.
590 let newEnd = edit.range.lowerBound + (replacement as NSString).length
591 if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
592 blocksMayChange = true
593 } else {
594 shaded.set(ViewState(selection: shaded.all).mapped(through: [edit]).selection, folded: [])
595 }
586 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) } 596 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
587 fold = FoldState( 597 fold = FoldState(
588 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta), 598 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
Sources/OrgstarMobile/OrgstarMobileApp.swift +15 −10
@@ -350,16 +350,7 @@ struct RootView: View {
350 model.reloadConfig() 350 model.reloadConfig()
351 Task { await workspace.refresh() } 351 Task { await workspace.refresh() }
352 } 352 }
353 .onOpenURL { url in 353 .onOpenURL(perform: handle)
354 if let link = AppLink(url: url) {
355 open(link)
356 } else if let request = CaptureRequest(link: url.absoluteString) {
357 capture = request
358 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
359 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
360 UIPasteboard.general.string = link
361 }
362 }
363 // The Live Activity follows the clock, wherever it starts or stops. 354 // The Live Activity follows the clock, wherever it starts or stops.
364 .task { 355 .task {
365 LiveClock.publish(model.clock) 356 LiveClock.publish(model.clock)
@@ -401,6 +392,20 @@ struct RootView: View {
401 showWaiting() 392 showWaiting()
402 } 393 }
403 394
395 /// A widget's or the Live Activity's link, or an org-protocol URL.
396 private func handle(_ url: URL) {
397 if let link = AppLink(url: url) {
398 open(link)
399 } else if let request = CaptureRequest(link: url.absoluteString) {
400 capture = request
401 } else if case .storeLink(let link, let title)? = OrgProtocol.parse(url.absoluteString) {
402 message = StoredLink.add(StoredLink(link: link, description: title), to: &model.storedLinks)
403 UIPasteboard.general.string = link
404 } else if url.scheme == "org-protocol" {
405 message = "orgstar handles org-protocol capture and store-link"
406 }
407 }
408
404 /// A widget's or the Live Activity's link. 409 /// A widget's or the Live Activity's link.
405 private func open(_ link: AppLink) { 410 private func open(_ link: AppLink) {
406 switch link { 411 switch link {
Sources/OrgstarMobile/ReaderScreen.swift +1 −1
@@ -110,7 +110,7 @@ struct ReaderScreen: View {
110 ToolbarItemGroup(placement: .primaryAction) { 110 ToolbarItemGroup(placement: .primaryAction) {
111 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty) 111 Button("Outline", systemImage: "list.bullet.indent") { showingOutline = true }.disabled(outline.isEmpty)
112 if let path = shownPath { 112 if let path = shownPath {
113 if let text = document?.text { ExportMenu(path: path, text: text) { message = $0 } } 113 if let tree = document?.tree { ExportMenu(path: path, tree: tree) { message = $0 } }
114 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") } 114 NavigationLink(value: EditorRoute(path: path, offset: nil)) { Label("Edit", systemImage: "square.and.pencil") }
115 } 115 }
116 } 116 }
Tests/OrgCoreTests/ExportScopeTests.swift +2
@@ -62,6 +62,8 @@ struct ExportScopeTests {
62 #expect(ExportScope.fileName(Self.file, subtreeAt: Self.project) == "project-notes") 62 #expect(ExportScope.fileName(Self.file, subtreeAt: Self.project) == "project-notes")
63 #expect(ExportScope.fileName(Self.file, subtreeAt: 0) == nil) 63 #expect(ExportScope.fileName(Self.file, subtreeAt: 0) == nil)
64 #expect(ExportScope.fileName("#+EXPORT_FILE_NAME: out/x\n* A\n") == "out/x") 64 #expect(ExportScope.fileName("#+EXPORT_FILE_NAME: out/x\n* A\n") == "out/x")
65 #expect(ExportScope.fileName(OrgParser.parse(Self.file), subtreeAt: Self.project) == "project-notes")
66 #expect(ExportScope.fileName(OrgParser.parse("#+EXPORT_FILE_NAME: out/x\n* A\n")) == "out/x")
65 #expect(ExportScope.output(for: source, name: "out/x", extension: "html").path == "/notes/out/x.html") 67 #expect(ExportScope.output(for: source, name: "out/x", extension: "html").path == "/notes/out/x.html")
66 #expect(ExportScope.output(for: source, name: "out/x.txt", extension: "html").path == "/notes/out/x.html") 68 #expect(ExportScope.output(for: source, name: "out/x.txt", extension: "html").path == "/notes/out/x.html")
67 #expect(ExportScope.output(for: source, name: "/tmp/abs", extension: "md").path == "/tmp/abs.md") 69 #expect(ExportScope.output(for: source, name: "/tmp/abs", extension: "md").path == "/tmp/abs.md")
docs/manual/guide/15-alongside-emacs.org +2
@@ -31,6 +31,8 @@ Emacs and Syncthing don't use file coordination, so these checks can't lock them
31 31
32If the file keeps changing through all three attempts, the save fails with an error and your edits stay unsaved. 32If the file keeps changing through all three attempts, the save fails with an error and your edits stay unsaved.
33 33
34In the Mac App Store version, when the folder doesn't let orgstar create the temporary file, orgstar writes the file in place instead.
35
34** Automatic and explicit saving 36** Automatic and explicit saving
35 37
36With =save = "automatic"= (the default), orgstar saves a file one second after you stop typing. With ="explicit"=, only =⌘S= (Save) and =⌥⌘S= (Save All) save. See [[file:13-configuration.org][Configuration]]. The iOS app always saves automatically. 38With =save = "automatic"= (the default), orgstar saves a file one second after you stop typing. With ="explicit"=, only =⌘S= (Save) and =⌥⌘S= (Save All) save. See [[file:13-configuration.org][Configuration]]. The iOS app always saves automatically.