Insert drawer, org-copy, refile goto, drag element, bullet cycling !262

merged merged by cmc on 2026-10-11 10:01 UTC · krz/orgstar:structure-commands into main

17 files changed, +418 −48

Layout: unified · split

Sources/OrgApp/DocumentSession.swift +15 −13
@@ -604,19 +604,21 @@ public final class DocumentSession {
604604 return nil
605605 }
606606
607 /// Moves the subtree at the caret, or at `from`, under `target`. For another file, that
608 /// file is written first, through the save path; the subtree leaves its file only once it
609 /// has. Returns a message for the echo area.
607 /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it
608 /// there (`org-copy`). For another file, that file is written first, through the save
609 /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
610610 @discardableResult
611 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
611 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
612612 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
613 let done = (keep ? "Copied to " : "Refiled to ") + target.label
613614 if target.path == path {
614615 let answers = ["refile": target.start.map(String.init) ?? ""]
615 let step = from == nil ? buffer?.perform(RefileWithinFile(), now: now, answers: answers)
616 : perform(RefileWithinFile(), path: path, at: from!.offset, expect: nil, answers: answers, now: now)
616 let command = RefileWithinFile(keep: keep)
617 let step = from == nil ? buffer?.perform(command, now: now, answers: answers)
618 : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now)
617619 if case .failed(let message)? = step { return message }
618620 if from == nil { bufferChanged() }
619 return "Refiled to \(target.label)"
621 return done
620622 }
621623 let url = URL(fileURLWithPath: target.path)
622624 let targetName = (target.path as NSString).lastPathComponent
@@ -625,23 +627,23 @@ public final class DocumentSession {
625627 let state = open.buffer.document
626628 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
627629 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
628 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
630 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
629631 let edit = EditResult(baseRevision: state.revision, edits: [result.target])
630632 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
631633 changed(open)
632 if let message = applySource(result.source, path: path, now: now) { return message }
633 return "Refiled to \(target.label)"
634 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
635 return done
634636 }
635637 do {
636638 guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
637639 var state = loaded(bytes, path: url.path)
638640 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
639641 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
640 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
642 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
641643 try state.apply([result.target], baseRevision: state.revision)
642644 if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
643 if let message = applySource(result.source, path: path, now: now) { return message }
644 return "Refiled to \(target.label)"
645 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
646 return done
645647 } catch {
646648 return "Can't refile: \(error.localizedDescription)"
647649 }
Sources/OrgApp/EmacsImport.swift +1 −1
@@ -746,7 +746,7 @@ public struct EmacsImport: Sendable {
746746 "org-babel-execute-src-block": "org.babel.execute", "org-clock-in": "app.clock.in", "org-clock-out": "app.clock.out",
747747 "org-clock-cancel": "app.clock.cancel", "org-clock-goto": "app.clock.goto", "org-clock-in-last": "app.clock.in-last",
748748 "org-resolve-clocks": "app.clock.resolve", "org-clock-mark-default-task": "app.clock.default",
749 "org-refile": "app.refile", "org-archive-subtree": "app.archive", "org-archive-subtree-default": "app.archive",
749 "org-refile": "app.refile", "org-copy": "app.refile.copy", "org-refile-copy": "app.refile.copy", "org-archive-subtree": "app.archive", "org-archive-subtree-default": "app.archive",
750750 "org-capture": "app.capture", "org-agenda": "app.agenda", "org-agenda-list": "app.agenda",
751751 "save-buffer": "app.save", "find-file": "app.quick-open", "projectile-find-file": "app.quick-open", "+default/find-file-under-here": "app.quick-open",
752752 "execute-extended-command": "app.palette", "counsel-M-x": "app.palette",
Sources/OrgCore/Commands/Command.swift +1
@@ -302,6 +302,7 @@ public enum Commands {
302302 OpenLinkAtPoint(), CreateID(), ToggleComment(), ToggleHeading(), ToggleItem(), MarkSubtree(),
303303 CopySubtree(cut: false), CopySubtree(cut: true), CloneSubtree(), SortEntries(), InsertStructureTemplate(), EditSpecial(), TableEditField(), TangleCommand(.all), TangleCommand(.block), TangleCommand(.target),
304304 UpdateDynamicBlock(), ClockReportTable(), SetEffort(), CtrlCCtrlC(), EvaluateTimeRange(), FootnoteAction(), FootnoteAction(special: true), TableEvalFormula(named: false), TableEvalFormula(named: true), SortTableLines(), TransposeTable(), GotoHeading(), SparseTreeCommand(), SetPriority(), SetPriority(value: "A"), SetPriority(value: "B"), SetPriority(value: "C"), SetPriority(value: " "), ReadAndSetProperty(), DeleteProperty(), DeleteProperty(globally: true), PropertyAction(), NextAllowedValue(previous: false), NextAllowedValue(previous: true), InsertColumnView(), ShowColumnView(), ShowColumnView(global: true), ToggleArchiveTag(), ArchiveToSibling(), ToggleOrderedProperty(),
305 InsertDrawer(), DragElement(forward: true), DragElement(forward: false), CycleBullet(previous: false), CycleBullet(previous: true),
305306 ]
306307
307308 public static var everything: [any OrgCommand] { all + TableCommand.Action.allCases.map(TableCommand.init) }
Sources/OrgCore/Commands/ElementCommands.swift added +168
@@ -0,0 +1,168 @@
1import Foundation
2
3// Org 9.8.7: `org-insert-drawer` (C-c C-x d), `org-drag-element-forward` and
4// `org-drag-element-backward` (M-<down> and M-<up> away from headings, items and tables), and
5// `org-cycle-list-bullet` both ways (S-<right> and S-<left> on items).
6
7/// C-c C-x d: `org-insert-drawer`. Asks for the name; inserts an empty drawer at the caret,
8/// or puts the selected lines in it.
9public struct InsertDrawer: OrgCommand {
10 public init() {}
11 public var id: String { "org.drawer.insert" }
12 public var title: String { "Insert Drawer" }
13 public func applies(in context: EditContext) -> Bool { true }
14 public func run(in context: EditContext) -> CommandStep {
15 guard let name = context.answers["drawer"] else { return .prompt(Prompt(key: "drawer", message: "Drawer:")) }
16 guard (":" + name + ":").range(of: "^:[-_\\w]+:$", options: .regularExpression) != nil else { return .failed("Invalid drawer name") }
17 let region = context.selection.first.flatMap { $0.isEmpty ? nil : $0 }
18 return commitBuffer(context) { buffer in
19 guard let region else {
20 if !buffer.bolp { buffer.insert("\n") }
21 buffer.insert(":\(name):\n\n:END:\n")
22 buffer.forwardLine(-2)
23 return
24 }
25 let end = buffer.marker(region.upperBound)
26 defer { buffer.release(end) }
27 buffer.point = buffer.lineStart(region.lowerBound)
28 if buffer.searchForward("^\\*+ ", bound: end.position, caseInsensitive: false) != nil {
29 throw EmacsBuffer.UserError(message: "Drawers cannot contain headlines")
30 }
31 // The drawer opens on the region's first non-blank line and closes after its last,
32 // at the section's indentation, and the caret ends before `:END:`.
33 buffer.point = region.lowerBound
34 buffer.skipForward([32, 9, 10, 13])
35 buffer.point = buffer.lineStart(buffer.point)
36 buffer.insert(":\(name):\n")
37 buffer.point = end.position
38 buffer.skipBackward([32, 9, 10, 13])
39 buffer.insert("\n:END:")
40 if !buffer.eolp { buffer.insert("\n") }
41 buffer.point = buffer.lineStart(buffer.point) - 1
42 if buffer.lookingAtLine("^:END:") == nil { buffer.point = buffer.lineStart(max(0, buffer.point - 1)) - 1 }
43 }
44 }
45}
46
47/// M-<down> and M-<up> on other elements: `org-drag-element-forward` and
48/// `org-drag-element-backward`, the element swapped with the next or previous one in the same
49/// section, drawer or block, the blank lines between them kept.
50public struct DragElement: OrgCommand {
51 public let forward: Bool
52 public init(forward: Bool) { self.forward = forward }
53 public var id: String { forward ? "org.element.drag-forward" : "org.element.drag-backward" }
54 public var title: String { forward ? "Drag Element Forward" : "Drag Element Backward" }
55 public func applies(in context: EditContext) -> Bool { true }
56
57 /// An element with its affiliated keywords, the blank lines after it, and where its own
58 /// text ends (the end of its last non-blank line).
59 struct Unit {
60 let begin: Int
61 var end: Int
62 let bodyEnd: Int
63 let node: SyntaxNode
64 let isHeading: Bool
65 }
66
67 /// The elements of `container`, whose ranges count from `base` in `ns`.
68 static func units(_ container: SyntaxNode, _ ns: NSString, base: Int = 0) -> [Unit] {
69 var units: [Unit] = []
70 var affiliated: Int?
71 for child in container.children {
72 if child.kind == .heading, child.range.lowerBound == container.range.lowerBound { continue }
73 if child.kind == .affiliatedKeyword {
74 affiliated = affiliated ?? base + child.range.lowerBound
75 continue
76 }
77 if child.kind == .zerothSection {
78 units += Self.units(child, ns, base: base)
79 continue
80 }
81 var bodyEnd = base + child.range.upperBound
82 while bodyEnd > base + child.range.lowerBound, [10, 13, 32, 9].contains(ns.character(at: bodyEnd - 1)) { bodyEnd -= 1 }
83 let begin = affiliated ?? base + child.range.lowerBound
84 affiliated = nil
85 if var last = units.popLast() {
86 last.end = begin
87 units.append(last)
88 }
89 units.append(Unit(begin: begin, end: base + container.range.upperBound, bodyEnd: bodyEnd, node: child, isHeading: child.kind == .section || child.kind == .heading))
90 }
91 return units
92 }
93
94 /// A drawer or a block other than src, example, export, comment and verse: its lines are
95 /// elements.
96 static func isGreater(_ node: SyntaxNode) -> Bool {
97 if node.kind == .drawer { return true }
98 guard node.kind == .block, let type = node.text.firstMatch(of: /^[ \t]*#\+(?i:begin)_(\S+)/)?.1.lowercased() else { return false }
99 return !["src", "example", "export", "comment", "verse"].contains(type)
100 }
101
102 /// The element `org-element-at-point` finds at `offset`, with its siblings: the deepest
103 /// section, drawer or greater block's units, and its place among them.
104 static func locate(_ offset: Int, tree: OrgTree, text: NSString) -> (units: [Unit], index: Int)? {
105 // The innermost section (or the text before the first heading) holding the offset.
106 var container = tree.root
107 func holds(_ node: SyntaxNode) -> Bool {
108 node.range.lowerBound <= offset && (offset < node.range.upperBound || (offset == node.range.upperBound && offset == text.length))
109 }
110 while let section = container.children.first(where: { ($0.kind == .section || $0.kind == .zerothSection) && holds($0) }) { container = section }
111 var base = 0
112 while true {
113 let units = Self.units(container, text, base: base)
114 guard let index = units.lastIndex(where: { $0.begin <= offset }) else { return nil }
115 let unit = units[index]
116 // Inside a drawer or a greater block, below its first line and above its last: its
117 // contents' elements.
118 let opening = NSMaxRange(text.lineRange(for: NSRange(location: base + unit.node.range.lowerBound, length: 0)))
119 let closing = text.lineRange(for: NSRange(location: unit.bodyEnd, length: 0)).location
120 if Self.isGreater(unit.node), offset >= opening, offset < closing {
121 let inner = OrgParser.parse(text.substring(with: NSRange(location: opening, length: closing - opening)))
122 guard !Self.units(inner.root, text, base: opening).isEmpty else { return (units, index) }
123 container = inner.root
124 base = opening
125 continue
126 }
127 return (units, index)
128 }
129 }
130
131 public func run(in context: EditContext) -> CommandStep {
132 let ns = context.text as NSString
133 let caret = context.caret
134 let failure = forward ? "Cannot drag element forward" : "Cannot drag element backward"
135 guard let (units, index) = Self.locate(caret, tree: context.tree, text: ns), !units[index].isHeading else { return .failed(failure) }
136 let other = forward ? index + 1 : index - 1
137 guard units.indices.contains(other), !units[other].isHeading else { return .failed(failure) }
138 let (a, b) = forward ? (units[index], units[other]) : (units[other], units[index])
139 let bodyA = ns.substring(with: NSRange(location: a.begin, length: a.bodyEnd - a.begin))
140 let bodyB = ns.substring(with: NSRange(location: b.begin, length: b.bodyEnd - b.begin))
141 let middle = ns.substring(with: NSRange(location: a.bodyEnd, length: b.begin - a.bodyEnd))
142 let edit = TextEdit(range: a.begin..<b.bodyEnd, replacement: bodyB + middle + bodyA)
143 let newCaret: Int
144 if forward {
145 let lineAfterB = b.bodyEnd < ns.length ? b.bodyEnd + 1 : b.bodyEnd
146 let lineAfterA = a.bodyEnd < ns.length ? a.bodyEnd + 1 : a.bodyEnd
147 newCaret = caret + (lineAfterB - b.begin) + (a.end - lineAfterA)
148 } else {
149 newCaret = a.begin + (caret - b.begin)
150 }
151 return .commit(EditResult(baseRevision: context.revision, edits: [edit], selection: [newCaret..<newCaret]))
152 }
153}
154
155/// S-<right> and S-<left> on an item: `org-cycle-list-bullet`, the list's bullets to the next
156/// kind, or with `previous` the one before.
157public struct CycleBullet: OrgCommand {
158 public let previous: Bool
159 public init(previous: Bool) { self.previous = previous }
160 public var id: String { previous ? "org.item.bullet-previous" : "org.item.bullet-next" }
161 public var title: String { previous ? "Previous Bullet Type" : "Next Bullet Type" }
162 public func applies(in context: EditContext) -> Bool {
163 EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).inItem() != nil
164 }
165 public func run(in context: EditContext) -> CommandStep {
166 commitBuffer(context) { try $0.cycleListBullet(previous: previous) }
167 }
168}
Sources/OrgCore/Commands/Refile.swift +14 −8
@@ -86,8 +86,9 @@ extension EmacsBuffer {
8686 }
8787 }
8888
89 /// `org-refile` to a heading in this buffer, or to its end when `target` is nil.
90 func refileWithinBuffer(to target: Int?) throws {
89 /// `org-refile` to a heading in this buffer, or to its end when `target` is nil; with
90 /// `keep`, `org-copy`, which leaves the subtree where it was.
91 func refileWithinBuffer(to target: Int?, keep: Bool = false) throws {
9192 let subtree = try subtreeRange()
9293 if let target, subtree.contains(target) {
9394 throw UserError(message: "Cannot refile to position inside the tree or region")
@@ -97,24 +98,27 @@ extension EmacsBuffer {
9798 defer { release(origin) }
9899 try refileInsert(tree, under: target)
99100 point = origin.position
101 if keep { return }
100102 let range = try subtreeRange()
101103 deleteRegion(range.lowerBound, range.upperBound)
102104 }
103105}
104106
105107/// C-c C-w within one file: moves the subtree at the caret under the heading starting at the
106/// answer's offset, or to the end of the file for an empty answer.
108/// answer's offset, or to the end of the file for an empty answer. With `keep`, C-c M-w
109/// copies it there.
107110public struct RefileWithinFile: OrgCommand {
108 public init() {}
109 public var id: String { "org.refile.local" }
110 public var title: String { "Refile Within File" }
111 public let keep: Bool
112 public init(keep: Bool = false) { self.keep = keep }
113 public var id: String { keep ? "org.refile.local-copy" : "org.refile.local" }
114 public var title: String { keep ? "Copy Within File" : "Refile Within File" }
111115 public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
112116
113117 public func run(in context: EditContext) -> CommandStep {
114118 guard let answer = context.answers["refile"] else {
115119 return .prompt(Prompt(key: "refile", message: "Refile to:"))
116120 }
117 return commitBuffer(context) { try $0.refileWithinBuffer(to: Int(answer)) }
121 return commitBuffer(context) { try $0.refileWithinBuffer(to: Int(answer), keep: keep) }
118122 }
119123}
120124
@@ -125,12 +129,14 @@ public enum Refile {
125129 public let target: TextEdit
126130 }
127131
128 public static func toOtherFile(source context: EditContext, target text: String, under heading: Int?) -> Result? {
132 /// With `keep`, the source's edit leaves its text as it is.
133 public static func toOtherFile(source context: EditContext, target text: String, under heading: Int?, keep: Bool = false) -> Result? {
129134 let target = EmacsBuffer(text, point: 0, settings: context.tree.settings, options: context.options)
130135 var tree = ""
131136 let step = commitBuffer(context) { buffer in
132137 tree = try buffer.copySubtree()
133138 try target.refileInsert(tree, under: heading)
139 if keep { return }
134140 let range = try buffer.subtreeRange()
135141 buffer.deleteRegion(range.lowerBound, range.upperBound)
136142 }
Sources/OrgCore/Commands/ToggleCommands.swift +3 −3
@@ -283,7 +283,7 @@ extension EmacsBuffer {
283283
284284 /// `org-cycle-list-bullet`: the list's bullets go through `-`, `+`, `*` (not at the
285285 /// margin), `1.`, `1)` and, with alphabetical lists, `a.`, `A.`, `a)`, `A)`.
286 func cycleListBullet() throws {
286 func cycleListBullet(previous: Bool = false) throws {
287287 guard let item = inItem() else { throw UserError(message: "Not at an item") }
288288 let origin = marker(point)
289289 defer { release(origin) }
@@ -306,8 +306,8 @@ extension EmacsBuffer {
306306 if lookingAt("\\S") == nil { choices.append("*") }
307307 if !description { choices += ["1.", "1)"] }
308308 if alpha, !description { choices += ["a.", "A.", "a)", "A)"] }
309 let index = choices.firstIndex(of: current).map { $0 + 1 } ?? choices.count
310 let new = choices[index % choices.count]
309 let index = choices.firstIndex(of: current) ?? choices.count
310 let new = choices[((index + (previous ? -1 : 1)) % choices.count + choices.count) % choices.count]
311311 let old = structure
312312 structure.set(first) { $0.bullet = bulletString(new) }
313313 fixBullets(&structure, prevs)
Sources/OrgCore/Keymap/PresetDoom.swift +4
@@ -324,6 +324,10 @@ extension KeymapPreset {
324324 command = "app.refile"
325325 mode = "normal"
326326 [[bind]]
327 keys = "SPC u SPC m r r"
328 command = "app.refile.goto"
329 mode = "normal"
330 [[bind]]
327331 keys = "SPC m s r"
328332 command = "app.refile"
329333 mode = "normal"
Sources/OrgCore/Keymap/PresetEmacs.swift +23
@@ -195,6 +195,23 @@ extension KeymapPreset {
195195 command = "org.columns"
196196 [[bind]]
197197 keys = "S-<right>"
198 command = "org.item.bullet-next"
199 when = "item"
200 [[bind]]
201 keys = "S-<left>"
202 command = "org.item.bullet-previous"
203 when = "item"
204 [[bind]]
205 keys = "C-c C-x d"
206 command = "org.drawer.insert"
207 [[bind]]
208 keys = "M-<up>"
209 command = "org.element.drag-backward"
210 [[bind]]
211 keys = "M-<down>"
212 command = "org.element.drag-forward"
213 [[bind]]
214 keys = "S-<right>"
198215 command = "org.property.next-value"
199216 when = "property"
200217 [[bind]]
@@ -432,6 +449,12 @@ extension KeymapPreset {
432449 keys = "C-c C-w"
433450 command = "app.refile"
434451 [[bind]]
452 keys = "C-u C-c C-w"
453 command = "app.refile.goto"
454 [[bind]]
455 keys = "C-c M-w"
456 command = "app.refile.copy"
457 [[bind]]
435458 keys = "C-c C-x C-s"
436459 command = "app.archive"
437460 [[bind]]
Sources/OrgEditorAppKit/EditorCommands.swift +2
@@ -88,6 +88,8 @@ public enum EditorCommands {
8888 EditorCommand(id: "app.search", title: "Search Notes", action: .app),
8989 EditorCommand(id: "app.reload-keymap", title: "Reload Keymap", action: .app),
9090 EditorCommand(id: "app.refile", title: "Refile…", action: .app),
91 EditorCommand(id: "app.refile.copy", title: "Copy to Refile Target…", action: .app),
92 EditorCommand(id: "app.refile.goto", title: "Go to Refile Target…", action: .app),
9193 EditorCommand(id: "app.archive", title: "Archive Subtree", action: .app),
9294 EditorCommand(id: "app.agenda", title: "Agenda", action: .app),
9395 EditorCommand(id: "app.capture", title: "Capture…", action: .app),
Sources/Orgstar/ContentView.swift +12 −4
@@ -716,7 +716,7 @@ struct ContentView: View {
716716
717717 /// Runs a command from a key, the palette or the Org menu.
718718 private func perform(_ id: String) {
719 let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
719 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
720720 if orgOnly, !session.isOrg {
721721 commands.show("Not an org file")
722722 return
@@ -782,11 +782,19 @@ struct ContentView: View {
782782 case "app.reload-keymap":
783783 loadKeymap()
784784 commands.show("Keymap reloaded")
785 case "app.refile":
785 case "app.refile", "app.refile.copy":
786 let keep = id == "app.refile.copy"
786787 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
787 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
788 commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
788789 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
789 if let message = session.refile(to: target) { commands.show(message) }
790 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
791 }
792 case "app.refile.goto":
793 // `C-u C-c C-w`: the target heading, or the end of a file.
794 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
795 commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
796 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
797 commands.jump(path: target.path, offset: target.start ?? Int.max)
790798 }
791799 case "app.archive":
792800 if let message = session.archive() { commands.show(message) }
Sources/OrgstarMobile/EditorScreen.swift +16 −9
@@ -32,13 +32,15 @@ struct EditorScreen: View {
3232
3333 /// One sheet at a time: two presenters on this screen interfere.
3434 enum Sheet: Identifiable {
35 case palette, conflict, syncCopies, recovery, refile
35 case palette, conflict, syncCopies, recovery
36 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
37 case refile(String)
3638 case block(BlockEdit)
3739
3840 var id: String {
3941 switch self {
4042 case .palette: "palette"
41 case .refile: "refile"
43 case .refile(let command): command
4244 case .conflict: "conflict"
4345 case .syncCopies: "syncCopies"
4446 case .recovery: "recovery"
@@ -106,10 +108,15 @@ struct EditorScreen: View {
106108 case .conflict: ConflictSheet(session: session)
107109 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
108110 case .recovery: RecoverySheet(session: session) { message = $0 }
109 case .refile:
111 case .refile(let command):
110112 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
111113 self.sheet = nil
112 if let target { refile(to: target) }
114 guard let target else { return }
115 if command == "app.refile.goto" {
116 model.openRequest = .offset(target.path, target.start ?? Int.max)
117 } else {
118 refile(to: target, keep: command == "app.refile.copy")
119 }
113120 }
114121 case .block(let edit):
115122 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
@@ -204,8 +211,8 @@ struct EditorScreen: View {
204211 editor.onAppCommand = { id in
205212 if id == "app.save" {
206213 _ = session.save(path)
207 } else if id == "app.refile" {
208 sheet = .refile
214 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
215 sheet = .refile(id)
209216 } else if id == "app.toggle-markup" {
210217 model.showMarkup.toggle()
211218 } else if MobileEditor.linkCommands.contains(id) {
@@ -229,14 +236,14 @@ struct EditorScreen: View {
229236extension EditorScreen {
230237 /// `org-refile` of the entry at the caret, to a target worked out again from the files
231238 /// now, as the agenda's Refile… does.
232 func refile(to target: RefileTarget) {
239 func refile(to target: RefileTarget, keep: Bool = false) {
233240 guard let editor, let path = session.path else { return }
234241 let caret = editor.editContext().caret
235242 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
236243 message = "Can't find \(target.label) any more."
237244 return
238245 }
239 message = session.refile(to: current, from: (path, caret))
246 message = session.refile(to: current, from: (path, caret), keep: keep)
240247 }
241248}
242249
@@ -514,7 +521,7 @@ struct CommandPalette: View {
514521 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
515522 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
516523 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
517 ("app.refile", "Refile…"),
524 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
518525 ("app.toggle-markup", "Show or Hide Markup"),
519526 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"),
520527 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
Sources/OrgstarMobile/MobileEditor.swift +2 −1
@@ -293,7 +293,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
293293 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true
294294 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
295295 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
296 case "app.refile": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
296 case "app.refile.goto": return onAppCommand != nil
297 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
297298 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
298299 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
299300 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
Tests/OrgAppTests/AppTests.swift +20
@@ -409,6 +409,26 @@ struct MoveSubtreeTests {
409409 #expect(session.document?.text == "* two\n")
410410 }
411411
412 @Test func copyLeavesTheSubtree() async throws {
413 let notes = try Folder()
414 let file = try notes.write("a.org", "* one\nbody\n* two\n")
415 let other = try notes.write("b.org", "* inbox\n")
416 let workspace = try WorkspaceModel(directory: nil)
417 try await workspace.addRoot(notes.url)
418 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
419 session.saveMode = .explicit
420 session.open(file.path)
421 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
422 #expect(session.refile(to: targets[2], keep: true) == "Copied to a.org/two")
423 #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n")
424
425 let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
426 StateBufferCaret.set(session, 0)
427 #expect(session.refile(to: inbox, keep: true) == "Copied to b.org/inbox")
428 #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
429 #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n")
430 }
431
412432 @Test func archiveToTheArchiveFile() throws {
413433 let notes = try Folder()
414434 let file = try notes.write("a.org", "* done\n* keep\n")
Tests/OrgCoreTests/ElementCommandTests.swift added +102
@@ -0,0 +1,102 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5/// `org-drag-element-*`, `org-insert-drawer` and `org-cycle-list-bullet` against Org.
6struct ElementCommandTests {
7 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil
8
9 /// Texts with `` where the caret is.
10 static let drags = [
11 "* H\nFirst ¶para\nstill first\n\nSecond para\n\nThird\n",
12 "* H\nFirst para\n\nSecond ¶para\n\nThird\n",
13 "* H\nFirst para\n\n\nSecond para\n\nThird\n",
14 "* H\n#+NAME: x\n#+begin_src sh\necho ¶hi\n#+end_src\n\nAfter\n",
15 "* H\nBefore\n\n#+NAME: x\n#+begin_src sh\necho ¶hi\n#+end_src\n",
16 "* H\nOnly ¶para\n** Child\nbody\n",
17 "* H\nLast ¶para\n* Next\n",
18 "Pre¶amble\n\nmore\n* H\n",
19 "* H\n#+begin_quote\nin ¶quote\n\nsecond in quote\n#+end_quote\n",
20 "* H\n:NOTES:\none\n\n¶two\n:END:\nafter\n",
21 "* H\nA\nB¶",
22 ]
23
24 static func place(_ marked: String) -> (text: String, caret: Int) {
25 let ns = marked as NSString
26 let at = ns.range(of: "").location
27 return (ns.replacingCharacters(in: NSRange(location: at, length: 1), with: ""), at)
28 }
29
30 static func ours(_ command: any OrgCommand, _ text: String, _ caret: Int, answers: [String: String] = [:], selection: Range<Int>? = nil) -> (text: String, caret: Int, failure: String?) {
31 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [selection ?? caret..<caret], answers: answers)
32 switch command.run(in: context) {
33 case .commit(let result):
34 let new = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) }
35 return (new, result.selection?.first?.lowerBound ?? caret, nil)
36 case .failed(let message): return (text, caret, message)
37 default: return (text, caret, "other")
38 }
39 }
40
41 @Test(.enabled(if: oracle))
42 func dragsLikeOrg() throws {
43 var cases: [EmacsOracle.Case] = []
44 var ours: [(String, Int, String?)] = []
45 for marked in Self.drags {
46 let (text, caret) = Self.place(marked)
47 for forward in [true, false] {
48 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: forward ? "(org-drag-element-forward)" : "(org-drag-element-backward)"))
49 ours.append(Self.ours(DragElement(forward: forward), text, caret))
50 }
51 }
52 for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() {
53 let failed = !theirs.error.isEmpty
54 let label = "\(cases[i].form) on \(cases[i].text.debugDescription)"
55 if failed {
56 #expect(mine.2 != nil && mine.0 == cases[i].text, "\(label): emacs \(theirs.error), ours \(mine.0.debugDescription)")
57 } else {
58 #expect(mine.0 == theirs.text && mine.1 == EmacsOracle.offset(theirs.point, in: theirs.text),
59 "\(label)\nours: \(mine.0.debugDescription) @\(mine.1) \(mine.2 ?? "")\nemacs: \(theirs.text.debugDescription) @\(EmacsOracle.offset(theirs.point, in: theirs.text))")
60 }
61 }
62 }
63
64 @Test(.enabled(if: oracle))
65 func insertsDrawersLikeOrg() throws {
66 let texts: [(String, Range<Int>?)] = [
67 ("* H\nbody¶\n", nil), ("* H\n\n", nil), ("* H\nbo¶dy\n", nil),
68 ("* H\n¶one\ntwo\n\nafter\n", 4..<12), ("* H\n ¶indented\n more\n", 4..<22),
69 ]
70 var cases: [EmacsOracle.Case] = []
71 var ours: [(String, Int, String?)] = []
72 for (marked, region) in texts {
73 let (text, caret) = Self.place(marked)
74 let form = region.map { "(progn (transient-mark-mode 1) (set-mark \(EmacsOracle.point($0.lowerBound, in: text))) (goto-char \(EmacsOracle.point($0.upperBound, in: text))) (activate-mark) (org-insert-drawer nil \"NOTES\"))" }
75 ?? "(org-insert-drawer nil \"NOTES\")"
76 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(region?.upperBound ?? caret, in: text), form: form))
77 ours.append(Self.ours(InsertDrawer(), text, region?.upperBound ?? caret, answers: ["drawer": "NOTES"], selection: region))
78 }
79 for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() {
80 #expect(mine.0 == theirs.text && mine.1 == EmacsOracle.offset(theirs.point, in: theirs.text),
81 "\(cases[i].form) on \(cases[i].text.debugDescription)\nours: \(mine.0.debugDescription) @\(mine.1) \(mine.2 ?? "")\nemacs: \(theirs.text.debugDescription) @\(EmacsOracle.offset(theirs.point, in: theirs.text)) \(theirs.error)")
82 }
83 #expect(Self.ours(InsertDrawer(), "x\n", 0, answers: ["drawer": "bad name"]).failure == "Invalid drawer name")
84 }
85
86 @Test(.enabled(if: oracle))
87 func cyclesBulletsBothWaysLikeOrg() throws {
88 let texts = ["- a¶\n- b\n", "+ a¶\n+ b\n", "1. a¶\n2. b\n", "1) a¶\n", " * a¶\n * b\n"]
89 var cases: [EmacsOracle.Case] = []
90 var ours: [(String, Int, String?)] = []
91 for marked in texts {
92 let (text, caret) = Self.place(marked)
93 for previous in [false, true] {
94 cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: previous ? "(org-cycle-list-bullet 'previous)" : "(org-cycle-list-bullet)"))
95 ours.append(Self.ours(CycleBullet(previous: previous), text, caret))
96 }
97 }
98 for (i, (mine, theirs)) in zip(ours, try EmacsOracle.run(cases)).enumerated() {
99 #expect(mine.0 == theirs.text, "\(cases[i].form) on \(cases[i].text.debugDescription)\nours: \(mine.0.debugDescription)\nemacs: \(theirs.text.debugDescription) \(theirs.error)")
100 }
101 }
102}
Tests/OrgCoreTests/KeymapTests.swift +13
@@ -181,6 +181,19 @@ struct KeymapTests {
181181 }
182182 }
183183
184 @Test func structureCommandsAreBound() {
185 let emacs = KeymapPreset.emacs.keymap, doom = KeymapPreset.doom.keymap
186 for (command, keys) in [("org.drawer.insert", "C-c C-x d"), ("app.refile.copy", "C-c M-w"), ("app.refile.goto", "C-u C-c C-w"),
187 ("org.element.drag-forward", "M-<down>"), ("org.item.bullet-next", "S-<right>")] {
188 #expect(emacs.keyLabels(for: command).contains(keys), "\(command)")
189 }
190 #expect(doom.keyLabels(for: "app.refile.goto", modes: ["normal"]).contains("SPC u SPC m r r"))
191 #expect(doom.keyLabels(for: "org.element.drag-backward", modes: ["normal"]).contains("M-k"))
192 let labels = doom.keyLabels(for: "org.item.bullet-previous", modes: ["normal"], limit: 5)
193 #expect(labels.contains("C-H"), "\(labels)")
194 #expect(doom.keyLabels(for: "app.refile.copy", modes: ["normal"]).contains("C-c M-w"))
195 }
196
184197 @Test func shadowedBindingsShowNoKeys() throws {
185198 var problems: [String] = []
186199 let map = Keymap.layered([KeymapPreset.emacs.keymap, try Keymap(toml: "[[bind]]\nkeys = \"C-c C-t\"\ncommand = \"app.save\"\n", problems: &problems)])
docs/manual/guide/03-keys.org +9 −1
@@ -537,7 +537,7 @@ Besides the leader, the preset binds these evil-org and Doom keys in normal stat
537537| =] b=, =[ b= | Next or previous buffer. |
538538| =M-h=, =M-j=, =M-k=, =M-l= | =M-<left>=, =M-<down>=, =M-<up>=, =M-<right>=: promote, move down, move up, demote on headings; the same for items; move columns and rows in tables. Also in insert and visual state. |
539539| =M-H=, =M-J=, =M-K=, =M-L= | The =M-S-= arrow forms: subtree promote and demote, table row and column insert and delete. Also in insert and visual state. |
540| =C-S-h=, =C-S-j=, =C-S-k=, =C-S-l= | The =S-= arrow forms: TODO keyword, priority, timestamp and property value changes. Also in insert state. |
540| =C-S-h=, =C-S-j=, =C-S-k=, =C-S-l= | The =S-= arrow forms: TODO keyword, priority, timestamp, property value and list bullet changes. Also in insert state. |
541541
542542** The leader
543543
@@ -622,6 +622,7 @@ Besides the leader, the preset binds these evil-org and Doom keys in normal stat
622622| =SPC m p u= | Raise Priority (=org.priority.up=) |
623623| =SPC m q= | Set Tags (=org.tags.set=) |
624624| =SPC m r r= | Refile… (=app.refile=) |
625| =SPC u SPC m r r= | Go to Refile Target… (=app.refile.goto=) |
625626| =SPC m s A= | Archive Subtree (=app.archive=) |
626627| =SPC m s N= | Widen (=org.widen=) |
627628| =SPC m s S= | Sort Entries (=org.sort=) |
@@ -820,6 +821,11 @@ When a key appears in several rows, it runs the command whose condition holds at
820821| Toggle Heading (=org.heading.toggle=) | =C-c *= | — | =SPC m h= (N) | Outside a table, turns headings into text and lines or items into headings (=org-toggle-heading=). |
821822| Toggle COMMENT (=org.heading.toggle-comment=) | =C-c ;= | — | — | Adds or removes the =COMMENT= keyword (=org-toggle-comment=). |
822823| Refile… (=app.refile=) | =C-c C-w= | =⌃⌘W= | =SPC m r r= (N), =SPC m s r= (N) | Asks for a target heading in your folders and moves the subtree there (=org-refile=). |
824| Copy to Refile Target… (=app.refile.copy=) | =C-c M-w= | — | =C-c M-w= | Asks for a target and copies the subtree there (=org-copy=). |
825| Go to Refile Target… (=app.refile.goto=) | =C-u C-c C-w= | — | =SPC u SPC m r r= (N) | Asks for a target and jumps to it (=org-refile= with a prefix). |
826| Drag Element Backward (=org.element.drag-backward=) | =M-<up>= | — | =M-k= | Away from headings, items and tables, swaps the element with the one before it (=org-drag-element-backward=). |
827| Drag Element Forward (=org.element.drag-forward=) | =M-<down>= | — | =M-j= | Away from headings, items and tables, swaps the element with the one after it (=org-drag-element-forward=). |
828| Insert Drawer (=org.drawer.insert=) | =C-c C-x d= | — | =C-c C-x d= | Asks for a name and inserts a drawer, or puts the selected lines in one (=org-insert-drawer=). |
823829| Archive Subtree (=app.archive=) | =C-c C-x C-s=, =C-c $= | =⌃⌘A= | =SPC m A= (N), =SPC m s A= (N) | Moves the subtree to the archive file (=org-archive-subtree=). |
824830| Toggle ARCHIVE Tag (=org.archive.toggle-tag=) | =C-c C-x a= | — | =SPC m s a= (N) | Adds or removes the =ARCHIVE= tag (=org-toggle-archive-tag=). |
825831| Archive to Archive Sibling (=org.archive.to-sibling=) | =C-c C-x A= | — | — | Moves the subtree under an =Archive= sibling heading (=org-archive-to-archive-sibling=). |
@@ -837,6 +843,8 @@ When a key appears in several rows, it runs the command whose condition holds at
837843| Move Item Up (=org.item.up=) | =M-<up>= | =⌃⌥⌘↑= | =M-k= | In a list, swaps the item with the one above (=org-move-item-up=). |
838844| Move Item Down (=org.item.down=) | =M-<down>= | =⌃⌥⌘↓= | =M-j= | In a list, swaps the item with the one below (=org-move-item-down=). |
839845| Toggle Checkbox (=org.checkbox.toggle=) | =C-c C-x C-b= | =⌃⌘C= | =SPC m x= (N) | Checks or unchecks the item's checkbox (=org-toggle-checkbox=). |
846| Next Bullet Type (=org.item.bullet-next=) | =S-<right>= | — | =C-S-l= (N, I) | On an item, gives the list the next bullet type (=org-cycle-list-bullet=). |
847| Previous Bullet Type (=org.item.bullet-previous=) | =S-<left>= | — | =C-S-h= (N, I) | On an item, gives the list the previous bullet type (=org-cycle-list-bullet= with =previous=). |
840848| Toggle Item (=org.item.toggle=) | =C-c -= | — | =SPC m i= (N) | Outside a table: on an item, cycles the list's bullet style; elsewhere turns lines into items and items into text (=org-ctrl-c-minus=). |
841849
842850** TODO, priority and tags
docs/manual/guide/04-outlines.org +13 −8
@@ -114,7 +114,10 @@ The subtree at the caret swaps places with the previous or next sibling subtree.
114114can't move past its parent or the start or end of the file. The caret keeps its column.
115115
116116On a list item the same keys move the item; in a table they move the row. On other
117lines they do nothing. orgstar has no =org-drag-element= for paragraphs.
117elements (paragraphs, blocks, drawers, keywords) they drag the element past the one
118before or after it in the same section, drawer or greater block, as
119=org-drag-element-backward= and =org-drag-element-forward= do. The blank lines between
120the two stay where they were.
118121
119122** Moving between headings
120123
@@ -368,8 +371,8 @@ list (=org-cycle-list-bullet=) through:
368371
369372=*= is skipped for a list at the left margin. Description lists skip the numbered and
370373lettered bullets. Lettered bullets are offered only when the list has 26 items or
371fewer. Org also cycles bullets with =S-<left>= and =S-<right>= on an item; orgstar
372does not bind those on items.
374fewer. =S-<right>= and =S-<left>= on an item (Doom =C-S-l= and =C-S-h=) cycle forward
375and backward.
373376
374377Numbered and lettered lists are renumbered whenever a list command changes them, and
375378by =C-c C-c= on any item. To start a list at a given number, put a counter after the
@@ -528,7 +531,9 @@ file opens, as with Org's =org-cycle-hide-drawer-startup= (=true= by default in
528531=config.toml=). =#+STARTUP: nohidedrawers= keeps them open in one file, and
529532=#+STARTUP: hidedrawers= folds them when the setting is off.
530533
531Org's =org-insert-drawer= (=C-c C-x d=) is not available; type the two lines yourself.
534Insert Drawer (=org-insert-drawer=, =C-c C-x d=) asks for a name. With no selection
535it inserts an empty drawer on a new line; with a selection it puts the selected lines
536in the drawer. A selection containing a heading is refused.
532537
533538* Properties
534539
@@ -769,6 +774,10 @@ files, =org-refile-use-outline-path= set to =file=, =org-reverse-note-order= =ni
769774entries go last), =org-log-refile= =nil= and =org-refile-keep= =nil=. None of these is
770775configurable in orgstar. Refiling from the agenda is covered in [[file:07-agenda.org][Agenda]].
771776
777Copy to Refile Target… (=org-copy=, =C-c M-w=) asks the same way and copies the
778subtree there, leaving it in place. Go to Refile Target… (=C-u C-c C-w=, Doom
779=SPC u SPC m r r=) asks the same way and jumps to the heading, or to the end of a file.
780
772781* Archiving
773782
774783** Archive Subtree
@@ -886,11 +895,7 @@ The full list is in [[file:03-keys.org][Keys]].
886895
887896These Org structure features are not in orgstar:
888897
889- =org-insert-drawer=, =org-copy= (refile a copy) and =org-refile= with a prefix
890 (jump to a target).
891898- Editing values in column view, and writing summaries from it; the
892899 =columnview= dynamic block does write summaries.
893900- The =ORDERED= property, radio lists and timer list items in the list commands.
894- =S-<left>= and =S-<right>= to cycle bullets on an item; use =C-c -=.
895- =org-drag-element= (=M-<up>= and =M-<down>= on paragraphs).
896901- Custom =org-refile-targets=.